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.

Monday, February 23, 2009

Placeholders

Placeholders are used to determine when what type of values are going to be input or displayed, depending on what type of functions that you use

Input Placeholders
scanf() function requires input placeholders to allow data to be transferred to the specific variable depending on which placeholder you will use.

Data type..............Placeholder
int.......................... %d
char....................... %c
double................... %lf
float....................... %f
string.................... %s

Note: for data that contains spaces in character arrays(strings) we use the %[^\n] symbol instead of %s because %s will only store strings without spaces.


Output Placeholders
Output placeholders are used to display data onto the screen. printf() function uses the output placeholder when necessary. The only difference with the input placeholders is the double data type placeholder for input function is %lf, while the double data type placeholder for output function is %f.

Data type..............Placeholder
int.......................... %d
char....................... %c
double................... %f
float....................... %f
string.................... %s (can also be used for strings with spaces)

Examples:

#include< stdio.h>
int main()
{
int number1 = 10;
int number2 = 20;
int number3 = 30;

printf("number1 contains %d \n", number1);
printf("number2 contains %d \n", number2);
printf("number3 contains %d \n", number3);

return 0;
}

Output:
number1 contains 10
number2 contains 20
number3 contains 30

#include< stdio.h>
int main()
{
int number1 = 10;
double number2 = 20.532;
double number3 = 30.88812;

printf("number1 contains %d \n", number1);
printf("number2 contains %f \n", number2);
printf("number3 contains %f \n", number3);

return 0;
}

Output:
number1 contains 10
number2 contains 20.532000
number3 contains 30.888120

#include< stdio.h>
int main()
{

char letter = 'A';
char letter2 = 'B';
char letters[] = "ABC";

printf("first letter = %c\n", letter);//character
printf("second letter = %c\n", letter2);//character
printf("letters contain %s", letters);//string
return 0;
}

Output:
first letter = A
second letter = B
letters contain ABC
Examples of inputs that uses placeholders:

#include< stdio.h>
int main()
{
int integernumber;

printf("Integernumber = ");
scanf("%d", &integernumber);
printf("\n variable integer contains: %d", integernumber);
}

Output:
Integernumber = 200
variable integer contains: 200


#include< stdio.h>
int main()
{
double lengthOfWall;

printf("Enter length of wall:");
//note the difference btw %lf for scanf
//and printf, %f for double
scanf("%lf", &lengthOfWall);
printf("\n lengthOfWall is %f", lengthOfWall);
}

Output:
Enter length of wall:35.886
lengthOfWall is 35.886000


#include< stdio.h>
int main()
{
char letter;

printf("enter a letter: ");
scanf("%c", &letter);
printf("\n letter is %c", letter);
}

Output:
enter a letter: E
letter is E

#include< stdio.h>
int main()
{
char fullname[21];

printf("enter full name: ");
//note: %s not used because fullname might
//be of a name with spaces.%[^\n] is used instead.
scanf("%[^\n]", fullname);

//for display, always use %s for string
//eventhough there are spaces
printf("welcome %s", fullname);
}


Output:
enter full name: Kelvin Chan
welcome Kelvin Chan

Note: that the ampersand symbol , & is required in front of the variable name in the input list of scanf() function, on int, double, float and char data types. Strings does not require &.
Escape Sequence/Characters
These characters starts with a frontslash / and the character. These escape characters have special functions, such as \n is to break the current line to form a new line and so on.

The table bellow are some escape characters:

Mathematical Operators and expressions
Mathematical operators can be used for calculation purposes and logical purposes.

Mathematical Operators
These operators compute different types of calculation based on the operators.
These are the basic mathematical operators:
+ (used for addition)
- (used for subtraction)
* (used for multiplication)
/ (used for division)
% is the modulus/modulo operator. This is used to get the remainder of a calculation

Unary expressions
Unary expressions consist of 1 operator and 1 operand. Operands are the numbers or the variables or both.
Example of unary expressions are:
-5, +5.

Binary expressions
Binary expressions consits of 2 operands and 1 operator and commonly seen then the following form:
[operand][operator][operand]
Example:
5 + 2
8*a
a/b

To store a computed value from a binary expression into a variable, the assignment operator is used, denoted as =.This is different from mathematics where = is equal but almost similar.
a= a+1 is not valid in mathematics because a does not equal a+1. In C language or most languages, a = a+1 is perfectly fine as this tells that the value of a plus 1 is then stored into the variable a.
Examples:
a= b*c;
b=(5*2)+c;

NOTE: The assignment operator can only be used to assign values to a variable, where the left hand side is always the variable. Any other expressions such as:
b+c = a
2+3 = a
are invalid in programming languages.

There are 3 forms of assignments: simple assignments, compound assignments and multiple assignments.

  • Simple Assignments
These are normal and commonly used assignments. Examples:
b= 4+a;
a= a*b;

  • Similarly, some simple assignments can be re-written in another form called compound assignments.
Example:
a=a*b can be rewritten to a *= b
a = a/b can be rewritten to a /=b
a = a+b can be rewritten to a +=b
a = a -b can be rewritten to a -=b
a = a%b can be rewritten to a %=b

Therefore, we can conclude that compound assignments can be used when the first operand is the same as the variable is assigned to it.

  • Multiple assignments
This is used to assign the same value to more than 1 different variable. Example
a = b = 1+2
The expression above can be separated as below:
b= 1+2
a=b
This tells us that the value of 1+2 is stored/assigned into b and the value of b is assigned to variable a.

And another note, all expressions and statements are to end with a terminated colon unless specified otherwise.
Postfix and prefix expressions

Postfix expressions
Postfix expressions can be recognized by the following examples.
a++;
i--;
Note that there is no other postfix/prefix expressions such as a// and i**. The symbol ++ means plus one.
However, the variable is first used and is later added by 1 and stored into memory. Thus the word postfix. This can be seen much more clearer in the following animation




Hover on the C statements to understand better.

Prefix expressions
Prefix expressions, as its name suggests, that the value of the variable is added by 1 first and stored in the memory which will be used later. Examples:
++a;
++i;
This is also the same as a = a+1 and i= i+1;

Sunday, February 22, 2009

Logical Operators and Relational Operators


Logical Operators
Logical operators are usually used to convey whether a given condition is true or false.
Since C language does not have data type to convey true and false, C uses a non-zero number as true while false is represented as zero, 0.

There are 3 logical operators: NOT, AND , OR.

The NOT logical operator is denoted as !
The AND logical operator is denoted as &&
The OR logical operator is denoted as ||

The following truth tables clearly explain the usage of the 3 logical operators.
NOT (!)

AND(&&)
As you can see, if either 1 of the condition is false, the whole condition is false.
OR(||)
As you can see, if either 1 of the condition is true the whole condition is true.