Friday, January 01, 2010

Introduction

This blog is made to help anyone that is having trouble with C Language programming and anyone who is keen to start learning programming. I would say C language would be the easiest to start and some functions and syntax in C Language can be used in other programming languages such as C++ and Java.

These documentations can be used for the subjects AACS1074, AACS1084, Programming Concepts and Design I and Programming Concepts and Design II of TARC.

This Blog will cover the following things:
  • Start programming using Microsoft Visual C++ Express Edition
  • Basic Structure of a C program
  • Comments
  • Introduction to variables and how to manipulate, store data into variables
  • Data types
  • Using output functions to display text on screen
  • Display values of variables
  • Using input functions to enter data into variables
  • Escape Sequences
  • Mathematical operators and expressions
  • Logical operators and relational operators
  • Using conditional functions (if, if-else, case)
  • using looping functions (while-loop, for-loop, do-while-loop)
  • And many others.
Check out other topics on on the right hand side of the navigation bar

Sunday, March 15, 2009

Useful functions


In this section, we will use functions can can be quite useful, especially for mathematical operations. These functions are not available in the standard input out library (stdio). Therefore other libraries must be included in the preprocessor directive to be able to use special functions. E.g. math.h, ctype.h, stdlib.h and windows.h

Lets look at the math.h library functions first, and it contains useful functions such as
  • sqrt()
  • pow()
  • ceil()
  • floor()
These function can help a lot when performing mathematical operations.

sqrt()
This function allows you to perform square root operation.
Function syntax:
sqrt(int x);
where int x is an integer variable and returns the square root of the variable x.
Example:
y= sqrt(25);//returns the value of 5 and stores it into variable y

OR
x=25;
y=sqrt(x);//returns the value of 5 and stores it into variable y.

If you wondered is there any other functions that might do cube roots, or fourth roots or nth root, then the answer is on the next function.

pow()
This function, as its name suggests, computes power functions.
Function syntax:
pow(base_number, powerof_n);
Where base_number is the number you want to compute the power, and the powerof_n is the number of the power.

Example:
5 cube would be pow(5, 3);

Lets say you want to compute the 7th root of 5, then we can simply write:

pow(5, (1/7));

since 5 to the power of 1/7 is the same as the 7th root of 5.


Saturday, February 28, 2009

To start programming.you must have a C++ compiler or C compilers. But mostly we use C++ compilers because they can also compile C codes. We will be using
  • Microsoft Visual Studio C++ Express Edition 2008
Download it at http://www.microsoft.com/eXPress/download/

Install it.
To start writing programs
1. Click File, New, Project.
2. Enter your project name and click OK.

3. Click Next and check Empty project, and click finish.


4. Right click Source Files, Add , New item

5. Click C++ File(.cpp) and enter your file name for that program, remember to end it with a .c extension if not the program assumes that you are creating a c++ file.


And you're done! You can start coding right away!
Basic Structure of a C Program

To ensure easy understanding of this language, a lot of examples will be given to make sure you understand better.

A basic program that displays the message "Hello World!"is as below


#include< stdio.h>
int main()
{
printf("Hello World!\n");
return 0;
}


We shall look each of the statements one at a time.

#include <>stdio.h<>
This line tells the program to include stdio.h library functions into the program, so that input and output functions can be used.This is a preprocessor directive, which always starts with a hash, #. This does not affect the program in anyway, it is just to enable the compiler to recognize input and output functions.

int main()
Every program needs to start at a certain point. Therefore, he compiler will always start the program from the main function. The 2 curly braces that can be found in the beginning of the main function and the end of the program indicates the functions that are inclusive in the main function. All functions, statements , expressions and code are to be entered inbetween those 2 curly braces.

printf("Hello World!\n");
This line tells the program to produce the message "Hello World!". The printf() function is an output function where it displays messages and other stuff. We will talk about that later.

return 0;
Each function, such as int main() returns a value back to the function, which indicates that all the statements and code before the return 0; statement are successfully executed. This can be marked as an end point, in this case, your program.


Note: The program can also be coded as below:


#include< stdio.h>
int main(){printf("Hello World!\n");return 0;}

Notice that I have omitted the new lines in the code above. This means that the C language does not take spacing and new lines into consideration, we just add them to make your program look structured and tidy.

Friday, February 27, 2009

Comments

Most of the time when you see a source code of a program, you will notice there are some lines of code that look like this:
//this program displays the message hello world
The above is to display a line of comment only. If more than 1 line of comments will be used, Refer below:
/*
this allows the program to run the functions....
and this is a block of text
*/
These are comments. Comments are added into the source code so that other programmers understand what are you trying to do in your code. This further helps in code maintenance as well in finding bugs in the program. The compiler ignores any line of statements that starts with the // symbol or the /* symbol. To close a comment, or rather finish commenting, simply add */ after the comment.

Thursday, February 26, 2009

Introduction to Variables

Variables are used by programming languages to store and manipulate data contained in it. We can say that a variable is a box, that contains the data. This box, has a name, which the program calls it by its name to manipulate the data inside the variable. These variables are stored in the memory of the computer.

Variables basically consist of several things:
  • Name of variable
  • What type of values are stored
  • Value inside the variable
Name of Variable
You can name anything as the name of the variable. In good software engineering practices, we use names that are meaningful to represent the data inside the box. Example of meaningful names to name your variable are:

NumberOfBooks, which is used to store the number of books.

Bad example:
x.

Having a name of a variable such as x or a or anything that has no meaning at all, is not recommended. Because x can be anything, and when you go back to your program and you want to make changes to it. You go like, "What the heck is x again?".

Even though you can name anything to your variable, there are certain restrictions or rules to follow:

1. Do not use keywords as variables.

Keywords here are words or names that has a predefined meaning in C Language. It means that you cannot name a variable like return because return has a meaning in C Language, which means that return a certain value back to a function. In the English Language, there are many thousands and thousands of words, and only about 40 are used as reserved keywords.

Example of keywords:
auto do goto static typedef
break double if return union
case else int short switch
char enum long long struct
const extern register signed volatile
continue float static unsigned while
default for auto void

2. No symbols are allowed in a variable
Symbols such as !@#$%^&*() are not allowed in naming a variable.
Example:
student&class //this is invalid
$var //this is invalid

3. No numbers allowed in the front of the variables

Example

1variable //this is invalid
var1able //valid

4. No spaces are allowed in variable

Since no spaces are allowed in variables, traditionally variables have underscore _ to represent spaces. Underscores are allowed to be placed in front of variables but not recommended.
Example:
student_score

Modern variables however use Uppercase to represent more than 1 word in a variable
Example:
studentScore
testOfStudents
Data Types of Variables
As stated in the previous post, variables also must have a specific data type associated with it. And only values with the same data type can be stored into the variable. These data type are standards set by the IEEE, Institute for Electrical and Electronics Engineers.

there are 4 basic data types:
  • int
int, short for integer stores numbers that do not contain any decimal number. This data type is used to store whole numbers.
Example : 123
  • float
float , as its name suggests, stores floating-point numbers, which are number that contain decimal number or exponents
Example:12.3
  • double
double, as its name suggests, stores a double precision floating-point number. In these documentations, we will use double rather than float.
Example:3.141592654
  • char
char, short for character, stored a single letter uppercase and lowercase accepted into the variable.
Example: 'A', 'e'

If more than 1 characters are wished be stored into a variable, we call them as character arrays, or strings. This will be discussed later on.

Wednesday, February 25, 2009

Declaring Variables

To use those variables, we need to declare them first.
Syntax is :

Data_type Variable_name;

Examples:
  • Declaring a variable, which stores the number of students in a classroom.

int NumStudents;


  • Declaring a variable, which stores the price of an item in a convenience store.

double priceofItem1;


Some of you might be asking, example 1 : why int? why can't we use double too? Isn't 1 and 1.0 the same?
Of course both are the same, but we need to specify the most suitable data type for different variables. In example 1, the variable NumStudents stores the number of students, and there is no such thing as "Oh, my class has around 35.6 students."

  • Declaring a variable which stores the gender of the a student.


char studentGender;


I hope by now, everything should be clear about declaring variables.
Assigning values to variables

You can assign values to variables via compile-time initialization and run time initialization. In both ways, to assign a value to a variable, or let a variable have a initial value, we use the assigning operator =.
  • compile-time initialization
Compile time initialization is the process of assigning, or initializing values to variables while declaring the variables.
Example:

int NumStudents = 5;
double Price = 21.8;
char letter = 'A';
  • run-time initialization
Run time initialization is the process of assigning or initializing values to variables after you have declared the variables.
Example:

int NumStudents;
double Price;
char letter;

NumStudents = 5;
Price = 21.8;
letter = 'A';
If you have more than 1 variable of the same data type, you can rewrite your code to make it neater. Example:

int NumStudents = 5;
int NumTeachers = 10;
int NumAdmins = 3;

We can rewrite it to:

int NumStudents = 5, NumTeachers = 10, NumAdmins = 3;

We can declare int on 1 line rather than each variable, since NumTeachers and NumAdmins share the same data type with NumStudents, which is int.

Tuesday, February 24, 2009

Output Functions
There are 3 basic functions that produces output on the screen:
  • putchar()
  • puts()
  • printf()
putchar()
Function Syntax:
putchar(char variable);

The putchar() function displays a character of a character type variable. Example:

#include< stdio.h>
int main()
{
char letter = 'A'; //Initialize a char type variable with the value of 'A'.

putchar(letter); //display variable letter on screen.
return 0;
}

Ouput:
A

puts()
Function Syntax:
puts(char string[]); OR
puts("format string");

The puts() function displays a character array or a string.
Example:

#include< stdio.h>
int main()
{
//Initialize a char array (String)
char message[] = "hi! this is a character array!";

//display the string variable on screen.
puts(message);
//displays anything you put between the double quotes""
puts("Hello World!");
return 0;
}


Output:
hi! this is a character array!
Hello World!

printf()
Function syntax:
printf("format string"); OR
printf("format string", output list);

printf() function display anything you want it to display.
Format string is anything that you entered is a format string. Output list is the list of variables that its data will be displayed, but you need to specify the appropriate placeholders

Example:

#include< stdio.h>
int main()
{
//declaring and initializing variable studentNumber.
int studentNumber = 50;

printf("Hello World!\n");//Display hello world
//Displays the data of the variable studentNumber with placeholder(%d)
printf("The number of students is %d", studentNumber);

return 0;
}

Output:
Hello World!
The number of students is 50.

We will be using a lot of printf() functions because it can be used to display text and variables together.
Input Functions

3 basic types of input functions that receives any value entered from the keyboard (standard input stream).

  • getchar()
  • gets()
  • scanf()
getchar()
This function receives a character type data from the keyboard and stores into a char type variable.
Function syntax:

char variable = getchar();

Example:(outputs in bold are what the user has input)

#include< stdio.h>
int main()
{
char gender;
//prompt for user input
printf("Enter your gender:");
//input function to store data from keyboard into variable gender
gender = getchar();
//displays the gender.
printf("\nGender = %c", gender);

return 0;
}
Output:
Enter your gender:M
Gender = M


gets()

This function receives a string of characters from the keyboard and stores into a character array type variable. Note that the array must be bigger than the number of characters you are going to input.

Function syntax:

gets(char array[]);

Example:

#include< stdio.h>
int main()
{
//declare a character array to store multiple
//letters to form a word.
char name[21];

//prompts user to input data
printf("Enter your name:");
//get the data from keyboard and store into
//variable 'name'
gets(name);
//displays the content of the variable name
printf("\n Your name is %s", name);
return 0;
}
Output:
Enter your name:Programmer
Your name is Programmer

scanf()
This function is used to accept anything, integer numbers, decimal numbers, characters, and character arrays(string).

Function syntax:
scanf("placeholders", inputlist);

Placeholders tell the function what kind of data will be input, and the input list contains which variable to store the data from keyboard into it.

Example:

#include< stdio.h>
int main()
{
//declare int type variable
int mark;
//prompt user to enter mark
printf("Enter your mark: ");
//assigns the value into the variable mark
scanf("%d", &mark);
//display content of variable mark
printf("\nYour mark is %d", mark);
}

Output:
Enter your mark: 89
Your mark is 89

Placeholders will be explained in more detail in the next post.