Sie sind auf Seite 1von 21

A C Program is made up of statements.

Statement is a part of
your program that can be executed. In other words every
statement in your program alone or in combination specifies an
action to performed by your program. C provides variety of
statements to help you attain any function with maximum
flexibility and efficency. One of the reason for popularity of C is
because of the extreme power provided to programmer in C due
to it rich and diverse set of statements define in C. For becoming
a top notch programmer you must have clear understanding of
the C statments and the situations where staments in C are
applicable.

Contents -

1. Type of Statements
2. if - else Statement
3. switch Statement
4. for Statement
5. while Statement
6. do Statement
7. return Statment
8. goto Statement
9. break Statment
10. continue Statements
11. Expressions Statements
12. Block Statements

1. Types Of Statements

Staments in C are categorized into following types-

1. Selection/Conditional Statement - They decide the flow of


statements on based on evaluation of results of conditons. if -
else and switch statements come under this category.
2. Iteration Statements - These are used to run a particluar block
statments repeatedly or in other words form a loop. for, while
and do-while statements come under this category.

3. Jump Statements - The are used to make the flow of your


statments from one point to another. break, continue, goto and
return come under this category.

4. Label Statements - These are used as targets/waypoints for


jump and selection statements. case (discussed with switch) and
label (discussed with goto) come under this category

5. Expression Statements - Any valid expression makes an


expression statement. To study expressions in detail click here .

6. Block Statement - A group of staments which are binded


together to form a logic are called block statemetns. Block
statement begins with a { and ends with a }.

Below we discuss each types of statements in detail with all


thier variant forms.

Block Statements

2. if - else Statement

if - else statement is a selection statement. It selects one piece of


code for execution among two on basis of a outcome of a
conditonal logic. The piece of code being refer here can be a s
tament, a block statement or even a empty statement depending
upon the logic of your program.

General form of if - else statement is :

if (condition) statement;
else statement;

else block here is optional.

Conditon here evaluates to true or false ie. zero or non-zero in c


respectively.It can be any valid data type which can be
interpreted by C compiler as 1 or 0. If the code evaluates to be
true the one assosiated with if is executed otherwise one
associated with else is executed. Hence the if - else statment
helps the programmer in controlling the flow of statements in
his program. The important thing to note is code of if and else
block are inversely related in logic ie. either code of if block or
code of else block will be executed never both.

Also in a professionally written code if the variable alone is able


to control the condtion using a comparison is considered a bad
style. For example say i an integer variable can attain any value
then this value can be directly interpreted as zero or non-zero
and is sufficient to control the loop. In this case conditons like (i
== 0) or (i != 0) are considered bad programming style and
should be avoided.

Here is a code showing the if - else statement in action -

// Code showing if - else statement in action.

#include <stdio.h>
#include <string.h>

void onlyif (char value[]);

{
if ( !strcmp (value,"Password")// Strcmp functions return zero
if string passed are same otherwise non - zero.
{
printf ("\nRight");
}

}
void ifandelse (char value []);

{
if ( !strcmp (value,"Password")
{
printf ("\nRight");
}
else
{
printf ("\nWrong");
}

}
int main ()
{
char value [1000];
printf ("Enter Password : ");
scanf ("%s", value);
return 0;
}

One property of if -else statement is that they can be nested.


This means that if statement can be target of another if
statement.
C89 specifies that compiler must support 15 levels of nesting
and C -99 increase that number to 127 but in reality most
compilers allow a large number of nesting much much greater
than defined in C.

In a nested else statement is assosiate with nearest if statement.


This association can be change by used of code block. Also you
should use proper indenting in your program to make sure you
remove any visual ambiguity/

General representation of nested if in C can be -

if (condition1) statement1;
if (condition2) statement2;
if (condition 3) statement3;
............. n levels;
else statement n+1
else statement n+2
else statement n+3

Another popular variant of if-else statement is if-else ladder


in this we create a series of generally one level deep. It has a
special property that when any one of the condition statement is
found to be true only statement associate with the if having that
condition true is executed and all other statements in the ladder
are by-passed. If none of the conditions evaluate to be true then
the final statement associated with else is executed if present.
Also it is recommended to use standard identation pattern.

General representation of nested if in C can be -

if (condition1) statement1
else
if (condition2) statement2
else
.
.
.
.
... n height
if (condition n+1) statement n+1
else
if (condition n+2) statement n+2
else
statement n+3 // Final Statement

Another option to if-else statement is ternary operator ?


(Question Mark) discussed under Expressions.

3. switch Statement

switch is a selection statement provided by C. It has a buil in


multiple - branch structure and work similar to if else ladder
generally. The input value to to the switch statemetnt construct
is a int or char variable. Note that no float or any other data is
allowed. This input variable is compared against a group of
integer constant. All the statments in and after the case in which
thier is a match is executed until a break statement is
encountered or end of switch is reached. We are also allowed to
give a default case which will be executed if no other statement
match is found. Also use of standard indenting is recommended.

General representation of switch in C can be -

switch (input) {
case constant1 :
statement1;
break;
case constant2 :
statement2;
break;
case constant3 :
statement3;
break;
.
.
.
.
... n cases
case constant n+1 :
statement n+1;
break;
case default :
statement n+2;
break;
It is defined by C that a compiler must support a minmum of
257 case statements in C89 and 1023 case statements in C99
though you may want to keep this to minimum in consideration
of efficiency.

Common use of switch is in for menus and other selection


interfaces.

Also break in the switch statements is optional and if no break is


present in a case the flow of statements transfer to next case and
so on till the break statement is encountered or switch case ends.

#include <stdio.h>

int main (void)


{
char ch;
printf ("\nEnter Character A,B or C: ");
ch = getchar ();

switch (ch)
{
case 'A' : printf ("You Entered A");
break;
case 'B' : printf ("You Entered B");
break;
case 'C' : printf ("You Entered C");
break;
default : printf ("You Didnot Entered A, B or C");

}
return 0;
}

Another variant of switch present is nested switch in which one


switch case is nested in another switch case. Eg. of such case
can be shown in the code below -

int main (void)


{
char ch;
int num;
printf ("\nEnter Character A for number 1&2 B for number 3&4:
");
ch = getchar ();

switch (ch)
{
case 'A' : printf ("You Entered A");
printf ("Enter Number 1 or 2);
scanf ("%d", &num);
switch (num)
{
case 1 : printf ("You Entered 1");
break;
case 2 : printf ("You Entered 1");
break;
default : printf ("You Did not Entered 1 or 2");
}
break;
case 'B' : printf ("You Entered B");
printf ("Enter Number 1 or 2);
scanf ("%d", &num);
switch (num)
{
case 3 : printf ("You Entered 1");
break;
case 4 : printf ("You Entered 1");
break;
default : printf ("You Did not Entered 1 or 2");
}
break;
default : printf ("You Did not Entered A or B");

}
return 0;
}

4. for Statement

for statement is one of the iteration statement provided by C. It


is the most popular of all iteration statments because it provides
unmatched flexiblity and power to the program.

Loops generated by for statement is are also called entry


controlled or close ended because the condition for iteration of
loop is check at the starting of the loop and loop will not execute
even once if the conditon will to satisfy even once.

General form of for statement is -

for (initialization; condition, increment)


statement;
for statement declaration as shown above can be divided into 3
parts -

1. Intialization - In this we intialize the loop control value to a


starting value. Also C99 like C++ permits the declaration of
loop control variable whose scope is only the for block.

2. Condition - In this evaluate the condition for the iteration of


the loop and loop repeat only when this is true.

3. Increment - In this we determine how the value of loop


control value changes with each iteration of the loop. It can be
increment, decrement or any mathematical expression.

Also statement in above form can be a single statement, block


statement or a blank statement.

Also note that each part is seprated by a semi colon.

Following source cod shows the use of for loop to generate


number 1-100 and back.

#include <stdio.h>

int main (void)


{
int num;
int i;
for (i = 0; i<100;i++) printf ("\n%d",i); // C89 Style for loop
for (int j = 100; j>0;j--) printf ("\n%d",i); //C99 Style for loop
return 0;
}

There are many variations or mutant forms of for loop which


can be created enhancing the general for loops flexibility and
power.
1. Multiple loop control variable - In this form more than 1 loop
control variable is used to control the execution of loop. The
multiple statements are combined together using comma
operator. The possible use is shown in the following source code
in which we generate numbers from 0 to 50 using two loop
control variables.

#include <stdio.h>

int main (void)


{
int num;
int i,j;
for (i = 0,j = 100; i<j;i++,j--) printf ("\n%d",i); // print numbers
0 to 50.
return 0;
}

2. Missing Parts - In a for statement declaration any or all of the


three parts of the statement are optional and can be replaced by
blank statements. Its show in the code below -

#include <stdio.h>

int main (void)


{
int num;
int i = 0;
for (;i< 100 ;)
{
printf ("\n%d",i);
i++;
}
return 0;
}
3.Infinite loop - In this a non - ending infinte loop is formed by
removing all three parts of the for statement. This loop can only
be stopped if a break statement is encountered inside the body of
the loop. Infinite loop find use in many algorithms such as game
programming engine.

#include <stdio.h>

int main (void)


{
int num;
for (;;)
{
printf ("This loop will run forever");
}
return 0;
}

4. No Body Loop - In this variation the body of the loop does


not exist. It maybe used in special circumstances such as in
which body of loop is not needed. For example the code below
shows a loop which moves the input string pointer to a character
in the same string removing the unwanted intial white spaces.

#include <stdio.h>

int main (void)


{
char* input;
gets (input);
for (;input == ' ' ;*input++); // For loop with no body
puts (input);
return 0;
}
Many new variations can be obtained by combining variations
above. For loop is most widely use loop statement and its should
be clear now why it is so.

5. while Statement

while is an iteration statement available in C. It is used to create


loops. While produce entry controlled loops ie. loops in which
condition check is performed at starting.

General form of while statement is -

while (condition)
statment;

Above condition is any valid expression which evaluates to zero


or non - zero and statement can be a single statement, block
statement or empty statement. Also if you want to run loop
forever you can write condition 1 and if you want it to never run
you can write condition 0. While like for can be made without
any bodies for specific purposes. Also unlike for the increment
has to been inside the statement block and initalization outside
the while statement block.

Following C Source code will help you grasp the detail of


application of while -

#include <stdio.h>

int main (void)


{
int i = 0;
while (i>10)
{

printf ("\n%d", i); // Loop prints values 0 to 9.


i++;
}
return 0;
}

6. do - while Statment

do - while is also iteration statement provided by C. It is similar


to while but has many diffrent properties. It is an exit controlled
loop which means that condition for next loop iteration is
checked at bottom of the loop. This makes sure that the do-while
loop will run atleast once.

General form of do - while statement is -

do {
statement;
}
while (condition);

Curly brackets are not required if statment is blank or single but


they are recommended in every case to avoid confusion.
Conditional as usual is vaild expression statement which
evaluates to zero or non-zero. The loop will continue to run till
the conditions evaluates to non - zero. As in while increment
part should be contained inside loop and intialization should be
outside loop. One the most important use of do-while is menus
where you want menu to run atleast once and also until user
chooses a valid choice.
C Source Code below will clarify the use of do-while -

#include <stdio.h>

int main ()
{
int i = 0;

do
{

printf ("\n%d", i);


i++;
} while (i>10) // Loop prints values 0 to 9.

return 0;
}

7. return Statement

return is a jump statement in c. It is used to return from the


executing function to the function which called this executing
function. If encounter in main the program exits and return to
the operating system or the source from which it was called
from.

Return statement also has a special property that it can return a


value with it to the calling function if the fuunction is declared
non - void. Void functions are the one which are explicitly
declared not to return a value and hence a return statement with
value when encountered in such a function leads to an error by
compiler. Also a function declared non-void should always
return a value of the respective type. Some compiler allow a
relaxation which could lead to severe problems, they return
garbage value if a return statement containing the value is not
found in the function. You should always make sure such a
situation never happens.

General form of return statement is -

return expression;In such a statement the value of the expression


is returned. Value can also be explicitly mentioned making a
function always return a fixed constant value.

Return will discussd in greater detail in further tutorials


specially one explaining functions.

Following Code shows return statment in action -

#include <stdio.h>

int function (void)


{

int b;
b = scanf ("%d", &b);
return b; // returns the value of b to the calling function.
}

int main ()
{
printf ("\n%d", function ());
return 0;
}

8. goto Statement

goto statement is a jump staments and is perhaps the most


controversial feature in C. Goto in unstructured language such
as basic was indispensable and the soul of the programming
lanugage but in a structured language they are critcized beyond
limit. The critics say that due to other jump statements in c goto
is not all required and more over it destoys the structure of your
program and make it unreadable. But on other hand goto
statement of C provides some very powerfull programming
options in very compicated situation. This tutorial will take an
neutral stand in such an argument and neither recommend nor
discourage use of goto.

Goto is used for jumping from one point to another point in your
function. You can not jump from one function to another. Jump
points or way points for goto are marked by label statements.
Label statement can be anywhere in the function above or below
the goto statement. Special situation in which goto find use is
deeply nested loops or if - else ladders.

General form of goto statement is -

.
.
.
goto label1;
.
.
.
.
label1 :
.
.
.
label2 :
.
.
.
.
goto label2;
To further clarify the concpet of goto statement study the C
Source Code below -

#include <stdio.h>

int main (void)// Print value 0 to 9


{
a = 1;
loop:; // label stament
printf ("\n%d",a);
a++;
if (a < 10) goto loop ; // jump statement
retrun 0;
}

9. break Statement

break statment is a jump statment in C and is generally used for


breaking from a loop or breaking from a case as discussed in
switch stament.

Break statement when encountered within a loop immediately


terminates the loop by passing condition check and execution
transfer to the first statment after the loop. In case of switch it
terminates the flow of control from one case to another.

Also one important thing to remember about break is that it


terminates only the innermost switch or loop construct in case of
nested switch and loop variations.

The C source code below shows an simple application of break


statement-

#include <stdio.h>
int main ()
{
for (int i = 0; i<100; i++)
{
printf ("\n%d", i);
if (i == 10); // This code prints value only upto 10.
break;
}

return 0;
}

10. continue Statement

continue is a jump statement provided by C. It is analogus to


break statement. Unlike break which breaks the loop, continue
stament forces the next execution of loop bypassing any code in
between.

For for staments it causes the conditional check and increment


of loop variable, for while and do-while it passes the control to
the conditon check jumping all the statements in between.
Continue plays an important role in efficiently applying certain
algorithms.

Below is a C source code showing the application of continue


statement -

#include <stdio.h>

int main ()
{
for (int i = 0; i<100; i++)
{
if (i == 10); // This code prints value only upto 9 even though
loop executes 100 times.
continue ;
printf ("\n%d", i);
}
return 0;
}

11. Expression Statments

Any valid expression forms an expression statement. Expression


covered in great depth in another tutorial. Click here to learn
every thing about c expressions.

All c expression statments end with a ; (semi - colon).

You can also create an empty statement just by placing a semi -


colon

12. Block Statments

Block statment is in itself not a statment but represents a


combined logical statement made up of a group of statments.

It is also known as compound statment.

They form a logical group of statements which are always


executed together ie. if one is executed all others will also be
executed otherwise none of them will be executed.

Block statement begins with a { and ends with }

Block statements generally represent something logical such as


a target for another statements such as if, while, do-while, for,
etc.
It is also possible to use block statements for no good reason but
you are recommended not to do so because it may confuse you
or some other person reading the source code who assumes it is
put there for a purpose. For example you should never use
expression statements as shown in the code below -

// Never use code as shown below -

#include <stdio.h>

int main (void)


{
{
int a = 0;
{
int age b;
{
b = 10;
{
printf ("%d %d", a,b);
}
}
}
}

{
return 0;
}
}

Das könnte Ihnen auch gefallen