Pages

Tuesday, 2 August 2011

The if Statement



The if statement allows a programmer to test the truth value of a conditional expression and to either select or reject the execution of certain statements depending on this value. It is a powerful decision making or branching tool.
In C language, the syntax of if statement is as follows:
if (conditional expression)
Statement;
The condition (which can be simple or compound) following the keyword if is always enclosed in parenthesis. The statement may be a single statement or any valid block of statements enclosed within {and}. If the conditional expression is true, the statement is executed, otherwise nothing is executed. Consider the following C program for Illustration.
/* magic number program */ 
 #include <stdio.h>
 main (   )
 {
int magic = 223;
int guess;
printf ("Enter  your  guess   for  the  number \n");
scanf   ("%  d"  &guess);
if   (guess = = magic)
printf   ("\n Congratulation! Right guess");
}

This program prompts the user to enter a number.   It reads the number entered through keyboard and stores it in the variable guess. It then compares this value with 223.  If the value .entered is equal to 233 then the message - Congratulation! Right guess - is displayed otherwise nothing is displayed.
The if statement has another form also, as given below:
if(conditional expression)    
statement1;                                
else
statement2;
In this form statement 1 is executed if the conditional expression evaluates to true, otherwise statement 2 is executed. Consider the following C program for illustration.
/* magic number program */ 
 #include <stdio.h> 
  main (   )

{
int magic = 223;
int guess;
printf ("Enter your guess for the number \n");
scanf ("% d" &guess);
if (guess = = magic)
printf ("\n Congratulation ! Right guess"); else
printf ("\n Sorry ! Wrong guess");
}
 Nesting ifs: Note that the statement part of if statement can be another if statement. Such structure is referred to as nested ifs.   Consider the following C program for illustration that prints the largest of three values stored in variables.


                                            Flow Chart of if else statement in Nested Form

/ * finding the largest of 3 numbers * /

#include <stdio.h>
 main( )
{
float a » 5, b = 2 , c = 7;
if (a >  b)
{
if (a > c)

printf ("a is greatest");

else

printf   ("c  is  greatest");
}
else
{

                   if   (b > c)

  printf   ("b is greatest");
               }
                    else
printf   ("c is greatest");

               }

 else if Ladder. There is another way of putting ifs together when multipath decisions are involved. Multipath decision is a chain of ifs in which statement associated with each else is an if.
It takes the following general form:
if   (condition  1)
Statement l;
else if   (condition 2)
Statement 2;
 else if  (condition 3)
Statement 3;
Statement x;
The conditions in elseif ladder are evaluated from the top (of the ladder) downwards. As soon as the true condition is found associated statement is executed and control is transferred to statement x.
#include   <stdio.h>
main(   )
{
int unit,   cust;
float charges;
printf   ("Enter Customer No.   and Units   Consumed:   \n");

scanf   ("% d % d",   &cust,   &unit);

if   (unit <=   200)

charges = 0.5 *unit;
else if (unit < = 400)
                                                              
charges = 100 + 0.65* (unit - 200);

else if (unit <= 600)

charges = 230 + 0.8 * (unit - 600);

printf ("\n \n Customer No:  % charges:  %0.2f \n" Cust, Charges);
}
Remember that each else is associated with the nearest preceding if as is illustrated below:

if   (condition-1)
if   (condition-2)
                     
   Statement-1;

else

Statement-2;

Here if condition-1 is true then condition-2 is evaluated. If condition-2 is also true then statement-1 is executed. If condition-2 is false then statement-2 is executed. Note that if condition-1 is false nothing is executed because there is no else part associated with condition-1 even though the indentation of the program suggests that.

                                              
c programmming online,basic of c language,structure of c programming,c language statements,Compiling a C Program,Pseudo Codes in c,basis data type in c ,variables in C Program,constants in C Program,c operators in C Program,special operators in C ,Decision Making,Branching & Looping in C Program,if statement in C Program,for loop in C Program

Wednesday, 27 July 2011

Decision Making, Branching & Looping




Introduction
Execution of a program is essentially sequential in nature. Statements are executed in the order of their appearance in a program. However, this causes a serious limitation on the programming capabilities. Consequently every programming language provides programming constructs that allow altering the sequence of execution. In this section we will consider, the programming constructs of this type provided with C language.
Control Statement
The statements that allow programmers to alter the sequential flow of execution of the program and control the flow are called control statements. Control statements enable the programmers to specify the order in which the various instructions in a program are to be executed by the computer. In short, they determine the flow of control in a program.

Why Control Statement?
Control statements are probably most desirable feature of any programming language. Consider writing program that prints " HELLO WORLD" 10 times. Without using any control programming construct the program would look like the one listed below:
#include<stdio.h>
main( )
{
printf ("HELLO WORLD");
printf ("HELLO WORLD") ;
printf ("HELLO WORLD");
printf ("HELLO WORLD");
printf ("HELLO WORLD");
printf ("HELLO WORLD");
printf ("HELLO WORLD");
printf ("HELLO WORLD");
printf ("HELLO WORLD");
printf ("HELLO WORLD");
Obviously this is not convenient way of programming. Without any control structure you will have to repeat printf statement as many times as you want them to print. Imagine what will you do if you have to print this statement 1000 times. Control statements let you write such programming problems in only few lines. Thus, using for loop (to be discussed later) the above program can be written as follows:
#include<stdio.h>
main(   )
{
for (i=l; i<=1000; i++) printf ("HELLO WORLD");
;"    }  
This program is just one liner but prints HELLO WORLD 1000 times.. Such is the power of control statements.
Consider another class of problems where you wish to execute certain statement only when some condition is true. Control statements allow you to select or reject statements to be executed depending on the truth value of a conditional expression.
But for the control statements a programming language would have only limited
application.
                           
C language provides 4 types of control statements, which are sufficient to form any desired form of execution control. These control statements are:

a)                Sequence control statements
b)                Decision control statements or conditional statement
c)                   Case control statements                             
d)              Repetition or loop control statements


c programmming online,basic of c language,structure of c programming,c language statements,Compiling a C Program,Pseudo Codes in c,basis data type in c ,variables in C Program,constants in C Program,c operators in C Program,special operators in C ,Decision Making,Branching & Looping in C Program,if statement in C Program,for loop in C Program

Thursday, 21 July 2011

Special Operators



C language also provides number of special operators which have no counter parts in other languages. These operators include comma operator, size of operator, pointer operators (& and *), and member selection operators (. and ->). Pointer operators will be discussed while introducing pointers and member selection operators will be discussed with structures and union.
We will discuss comma operator and size of operator in this section.
Comma Operator
This operator is used to link the related expressions together.
e.g.:     int    x, y, z;
z  =   (x =   10,   y=20,   x+y) ;
Here, the first statement will create three integer type variables - x, y and z. In the second statement, right-hand side will be evaluated first. Consequently, 10 will be stored in variable x, then 20 will be stored in variable y~, and then values in x and y will be multiplied result of which will be stored in variable z. Thus, the value stored in the variable z will be 200 at the end of execution.
Size of Operator      
The size of operator works on variables, constants and even on data types. It returns the number of bytes the operand occupies in the memory. Consider the following C program for illustration.
#include<stdio.h>    
main()
{
       printif("%d, %d", sizeof (int) , sizeof (float));
}
The output of this program will be 2, 4. Don't get disheartened if you get different result. This is only because the machine on which this program was run allotted 2 bytes for int type and 4 bytes for float type. The result that you get depends on the number of bytes allocated to these types on your machine. Nevertheless in all cases sizeof operator returns the number of bytes occupied by its operand on that particular machine.

Operators Precedence

An expression may contain more than one operator. Which operator will execute first depends on its precedence. Precedence defines the sequence in which operators are to be applied on the operands, while evaluating the expressions involving more than one operators.
Operators of same precedence are evaluated from left to right or right to left, depending upon the level. This is known as associativity property of an operator. A complete list of operator precedence as applicable in C language is presented below. Some of the operators you are already familiar with, others will be covered elsewhere in the book.


Summary of Precedence and Associativity

DESCRIPTION  OPERATORS      ASSOCIATIVITY
Function expression       ()                  Left—>Right
Array expression            []                   Left—>Right
Structure operator          —>                Left—>Right
Structure operator                              Left—»Right
Unary Minus                    -                  Right-»Left
Increment/Decrement     ++ -            Right—>Left
One's complement         ~                 Right—>Left
. Negation                       !                  Right—>Left
Address of                     &                 Rights-Left
Value at address            *                 Right—>Left
Type cast                   (type)               Right—>Left
Size in bytes              sizeof               Right->Left 
Multiplication                *                   Left—>Right
Division                        /                    Left->Right
Modulus                     %                     Left-»Right
Addition                     +                     Left—>Right
Subtraction                 -                     Left—>Right
Left shift                    < <                   Left->Right
Right shift                 > >                    Left—>Right
Right shift

c programmming online,basic of c language,structure of c programming,c language statements,Compiling a C Program,Pseudo Codes in c,basis data type in c ,variables in C Program,constants in C Program,c operators in C Program,special operators in C ,Decision Making,Branching & Looping in C Program,if statement in C Program,for loop in C Program

Compiling a C Program



Compiling a C program depends on the compiler as well as the operating system under use. Supposing that you are using Turbo C compiler on DOS platform, the compilation of a C program stored in a file called TEST.C, would look like as shown below:

C:\>tc test.c

Here, TC is the name of Turbo C compiler. The compilation would produce an object file called TEST.OBJ, Object files, thus produced, contain the machine language translation of the C program. However, this file is yet not executable. To make it an executable program you need to LINK the object files with library files, when TEST.EXE is produced.

Most often you shall be using an IDE for program development and therefore, you do not need to compile and link the programs explicitly as shown above. Every IDE provides a user friendly set of commands to carry out the compilation and linking automatically.

We will consider how Turbo C IDE may be used to develop and compile a C program. When you start the Turbo C IDE, the IDE provides all the necessary commands that let you write, compile and link your programs. A typical Turbo C IDE is displayed here:


Clearly, the IDE is menu driven. All the commands are grouped into menus such as; File, Edit, Search, Run, Compile, Debug, Project, Options, Window, and Help. You may take your time to navigate through the menus and see what command they offer to you.
To just give you a feel, we will interact with the IDE in form of a session. Let us create a program file called TEST.C containing the following program:
#include
main ()
{
printf("this is the first C program");
}
Never mind if you do not understand what this program means. It is just to demonstrate how you would write your programs and compile them.
To write the program into Test.C file:
1. Go to file menu.
2. Click at New command. Turbo C IDE opens a blank file for you, is shown here:



Note that Turbo C names the file as NONAMEOO.C. You can now enter your program in this file and save it with whatever name you wish to assign to it.
3. Type the program as shown below:


c programmming online,basic of c language,structure of c programming,c language statements,Compiling a C Program,Pseudo Codes in c,basis data type in c ,variables in C Program,constants in C Program,c operators in C Program,special operators in C ,Decision Making,Branching & Looping in C Program,if statement in C Program,for loop in C Program

Tuesday, 5 July 2011

Special Operators



C language also provides number of special operators which have no counter parts in other languages. These operators include comma operator, size of operator, pointer operators (& and *), and member selection operators (. and ->). Pointer operators will be discussed while introducing pointers and member selection operators will be discussed with structures and union.
We will discuss comma operator and size of operator in this section.
Comma Operator
This operator is used to link the related expressions together.
e.g.:     int    x, y, z;
z  =   (x =   10,   y=20,   x+y) ;
Here, the first statement will create three integer type variables - x, y and z. In the second statement, right-hand side will be evaluated first. Consequently, 10 will be stored in variable x, then 20 will be stored in variable y~, and then values in x and y will be multiplied result of which will be stored in variable z. Thus, the value stored in the variable z will be 200 at the end of execution.

Sizeof Operator      
The size of operator works on variables, constants and even on data types. It returns the number of bytes the operand occupies in the memory. Consider the following C program for illustration.
#include<stdio.h>    
main()
{
       printif("%d, %d", sizeof (int) , sizeof (float));
}
The output of this program will be 2, 4. Don't get disheartened if you get different result. This is only because the machine on which this program was run allotted 2 bytes for int type and 4 bytes for float type. The result that you get depends on the number of bytes allocated to these types on your machine. Nevertheless in all cases sizeof operator returns the number of bytes occupied by its operand on that particular machine.

Operators Precedence
An expression may contain more than one operator. Which operator will execute first depends on its precedence. Precedence defines the sequence in which operators are to be applied on the operands, while evaluating the expressions involving more than one operators.
Operators of same precedence are evaluated from left to right or right to left, depending upon the level. This is known as associativity property of an operator. A complete list of operator precedence as applicable in C language is presented below. Some of the operators you are already familiar with, others will be covered elsewhere in the book.

Summary of Precedence and Associativity
 DESCRIPTION             OPERATORS            ASSOCIATIVITY
Function expression            ()                                Left—>Right
Array expression                 []                                 Left—>Right
Structure operator               —>                              Left—>Right
Structure operator                                                 Left—»Right
Unary Minus                          -                               Right-»Left
Increment/Decrement         ++ -                           Right—>Left
One's complement              ~                              Right—>Left
. Negation                             !                              Right—>Left
Address of                           &                             Rights-Left
Value at address                  *                              Right—>Left
Type cast                            (type)                         Right—>Left
Size in bytes                      sizeof                          Right->Left 
Multiplication                       *                              Left—>Right
Division                               /                               Left->Right
Modulus                             %                              Left-»Right
Addition                             +                                Left—>Right
Subtraction                         -                                Left—>Right
Left shift                             < <                             Left->Right
Right shift                           > >                            Left—>Right

Less than                           <                                Left—>Right
Less than or equal-to       < =                              Left—»Right
Greater than                     >              .                   Left->Right
Greater than or equal to  >=                              Left—>Right
Equal to                            = =                             Left-»Right
Not equal to                     ! =                              Left—»Right
Bitwise AND                     &                                Left~>Right
Bitwise XOR                       ^                               Left->Right
Bitwise OR                           |                              Left->Right
Logical AND                     &&                            Left—>Right
Logical OR                      | |                                 Left—>Right
Conditional   :                 ?:                                Right—>Left
Assignment                     =                                Right—»Left
                                                                                                            * =   / = % =                                                                                     Right—»Left
                                  + =     - =    & =                 Right—>Left
                                   ^ =      | =                          Right->Left
                                 << =     >> =                     Right->Left
Comma                     \                                     Right—»Left     
Unary operators
 Operators can be classified on the basis of number of operands they operate on. Under this classification, operators can be of the following type:
1.                                  Unary operators
2.                                  Binary Operators
3.                                  Ternary operators
4.                                  n-ary operators  
 Unary operators, as the name suggests, operate on a single operand. Binary operators take two while ternary operators, take three operands respectively. Although, higher order operators are possible, they are not available in language C.
You have already learn about them in the previous section. Here is a list of the unary operators available in C:
1.                                           Minus operator  ,                        -
2.                                  Increment operator                 ++
3.                                  Decrement operator               --
4.                                    Negation operator                    !
5.                                  sizeof operator                      sizeof
  6.       One’s complement operator    ~

c programmming online,basic of c language,structure of c programming,c language statements,Compiling a C Program,Pseudo Codes in c,basis data type in c ,variables in C Program,constants in C Program,c operators in C Program,special operators in C ,Decision Making,Branching & Looping in C Program,if statement in C Program,for loop in C Program