Sie sind auf Seite 1von 21

Control Statements

November 15, 2018

1 Control Statements in C

Figure 1: Program control statements/ constructs in C

2 Test Expression
1. #include <stdio.h>
int main()
{
int a=3;
printf("\n%d",a>3);
return 0;
}
Output 0
2. #include <stdio.h>
int main()
{
int a=3;
printf("\n%d",a>2);
return 0;
}

Output 1

1
3. #include <stdio.h>
int main(void)
{
_Bool isPrime =5;
printf("\n isPrime = %d", isPrime);
return 0;
}

Output isPrime = 1

3 Selection
Selection is used to take a decision between one or two or more alternatives. Decision in a program
is concerned with choosing to execute one set of statement over the others. Selection is also known
as branching. There are different types of selection that can be employed in a program.

Figure 2: Types of selection constructs

For one-way selection. if..... without else part is used. The if...else...construct is used to im-
plement two-way selection. Nested-if and if...elseif.. ladder is used to implement nested selection
construct. For implementing multi-way selection switch case is used.

3.0.1 One-way and Two-way decisions

Figure 3: Flow chart of if and if-else construct

2
Check whether the two given numbers are equal.
1. #include <stdio.h>
int main()
{
int a=2, b=3;
if(a == b)
printf("EQUAL");
else
printf("UNEQUAL");
return 0;
}

Output UNEQUAL

2. #include <stdio.h>
int main()
{
int a=2, b=3;
if(a = b)
printf("EQUAL");
else
printf("UNEQUAL");
return 0;
}

Output EQUAL

3.0.2 Multiway decisions


Multi-way decision statements use if-else-if nested if or switch statements. They are used to
evaluate a test expression that could have several possible values.

• if-else-if ladder
The form of a multi-way decision construct using if-else if statements is as follows:

if(TestExpr1)
stmtT1;
else if(TestExpr2)
stmtT2;
else if(TestExpr3)
stmtT3;
.
.
.
else if(TestExprN)
stmtTN;
else
stmtF;

3
Figure 4: Flowchart of an if-else-if construct

The following program prints the grade according to the score secured by a student.

#include <stdio.h>
int main()
{
int score;
char grade;
printf("\n ENTER SCORE : ");
scanf("%d", &score);
if(score >= 90)
grade = A;
else if(score >= 80)
grade = B;
else if(score >= 70)
grade = C;
else if(score >= 60)
grade = D;
else
grade = F;
printf("GRADE IS: %c", grade);
return 0;
}

4
3.0.3 Nested-if

Figure 5: Syntax for Nested if

3.0.4 Dangling else problem

Program

int main()
{ int a = 2;
int b = 2;
if (a == 1)
{
if (b == 2) printf("a was 1 and b was 2\n");
}
else printf("a wasnt 1\n");
return 0;
}

4 The Conditional Operator


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

5
int a,b,c;
printf("\n ENTER THE TWO NUMBERS: ");
scanf("%d %d", &a, &b);
c= a>b? a : b>a ? b :-1;
if(c==-1)
printf("\n BOTH NUMBERS ARE EQUAL");
else
printf("\n LARGER NUMBER IS %d",c);
return 0;
}

5 The switch statement


switch(expr)
{
case constant1: stmtList1;
break;
case constant2: stmtList2;
break;
case constant3: stmtList3;
break;
,
,
default: stmtListn;
}

• When there is a switch statement, it evaluates the expression expr and then looks for a match-
ing case label. If none is found, the default label is used. If no default is found, the statement
does nothing. The case constants must be integer or character constants

• The biggest defect in the switch statement is that cases do not break automatically after the
execution of the corresponding statement list for the case label.

• When the break statement is executed within a switch, C executes the next statement outside
the switch construct.

• The switch statement enables you to choose one course of action from a set of possible
actions, based on the result of an integer expression.

• No two case labels can have the same value.

• The case constants must be integer or character constants. The expression must evaluate to
an integral type.

• The break statement is optional. If a break statement is omitted in any case of a switch
statement, the program flow is followed through the next case label.

6
Program using a switch statement to check whether a number given by the user is odd or even.

#include <stdio.h>
int main()
{
int n;
printf("\n Enter the number:");
scanf("%d", &n);
switch(n%2)
{
case 0: printf("\n EVEN");
break;
case 1: printf("\n ODD");
break;
}
return 0;
}

What will the following switch statement print?

1. char c = y;
switch(c)
{
case Y: printf("Yes/No");
break;
case N: printf("No/Yes");
break;
default: printf("Other");
}
Output Other

2. int main()
{
int choice=3;
switch(choice)
{
default:
printf("Default");
case 1: printf("Choice1");
break;
case 2: printf("Choice2");
break;
}
return 0;
}
Output DefaultChoice1

7
6 Iteration

Figure 6: Loop variations: pre-test and post-test loops

Figure 7: Comparison between a pre-test and post-test loop

6.1 While Construct

Figure 8: Expanded syntax of while and its flowchart representation

8
Consider an example of a program that asks the user to enter some numbers and then find their
average.
Algorithm

1. START
2. PRINT "HOW MANY NUMBERS:"
3. INPUT N
4. S = 0
5. C=1
6. PRINT "ENTER THE NUMBER"
7. INPUT A
8. S <- S + A
9. C <- C + 1
10. IF C<=N THEN GOTO STEP 6
11. AVG<- S/N
12. PRINT "AVERAGE IS" AVG
13. STOP

C Program

#include <stdio.h>
int main()
{ int n, a, c=1,s=0;
float avg;
printf("\n HOW MANY NUMBERS?");
scanf("%d", &n);
while(c<=n)
{
printf("\n Enter the number: ");
scanf("%d", &a);
s+=a;
c++;
}
avg=(float)s/n;
printf(" \n AVERAGE IS %f ", avg);
return 0;
}

In this example, typecasting is needed as both s and n are integers and avg is a float.Otherwise
the program evaluates avg as an integer.A better way to implement the above program is given as
follows.
Algorithm

1. START
2. S <- 0
3. N <- 0
4. ANS <- Y
5. PRINT "ENTER THE NUMBER"
6. INPUT A
7. S <- S + A

9
8. N <- N + 1
9. PRINT "WILL U ADD MORE (Y/N)?"
10. INPUT ANS
11. IF ANS=Y THEN GOTO STEP 5
12. AVG<- S/N
13. PRINT "AVERAGE IS", AVG
14. STOP

C Program

#include <stdio.h>
int main()
{ int n=0, a, s=0;
float avg;
char ans=y;
while(ans == y|| ans == Y)
{
printf("\n Enter the number: ");
scanf("%d", &a);
s+=a;
n++;
printf("\n will U add more(y/ n)?");
scanf("%c",&ans);
}
avg=(float)s/n;
printf(" \n AVERAGE IS %f", avg);
return 0;
}

6.1.1 Developing infinite loop using while construct


Consider the following progams:

#include <stdio.h>
int main()
{ int c=5;
while(c)
{
printf("\t %d",c);
c--;
}
return 0;
}

Here, the output will be 5 4 3 2 1


Now, the above program is rewritten to print the odd numbers between 5 and 0.

#include <stdio.h>
int main()
{ int c=5;

10
while(c)
{
printf("\t %d",c);
c= c-2;
}
return 0;
}

It will print 5 3 1 -1 -3 -5 ...


That is, it leads to an infinite loop.This is so because after printing 1, the value of c will be -1
and while(c) evaluates true as the value of c is non-zero. As a result, the program will print -1, -3,
-5, and so on.

6.2 for Construct


The general form of the for statement is as follows:

for(initialization; TestExpr; updating)


stmT;

The following figure explains the three expressions in the for loop.

Figure 9: for construct flowchart

How many times does the body of a for() loop execute?

1. The following loop is executed (n-m)+1 times.


for(i=m; i¡=n; i++) ...

2. The following loop is executed (n-m) times.


for(i=m; i¡n; i++) ...

3. The following loop is executed (n-m)/x times.


for(i=m; i¡n; i+=x) ...

11
An example program that calculates the factorial of a number.

int main()
{ int n, c;
long int f=1;
printf("\n Enter the number: ");
scanf("%d",&n);
for(c=1;c<=n;++c)
f*=c;
printf("\n Factorial is %ld",f);
return 0;
}

The alternate program is shown as follows:

int main()
{ int n;
long int f=1;
printf("\n Enter the number: ");
scanf("%d",&n);
for(;n>0;n--)
f*=n;
printf("\n Factorial is %ld",f);
return 0;
}

There must be no semicolon after a for statement or it will lead to a different output. Consider the
following program.

#include <stdio.h>
int main()
{ int c;
for(c=1; c<=5; c++);
printf("%d", c);
return 0;
}

The output will be 6, as the loop continues up to c=5. When the value of c is 6, the loop terminates
as the test expression evaluates false.

6.2.1 Pre increment and post increment


The post- and pre- operations play a different role when they are specified in the test expression.

#include <stdio.h>
int main()
{ int c;
for(c=0; c++; c++)
printf("%d", c);
return 0;
}

12
Output Prints nothing as c has been initialized as zero and the post-increment of c makes a differ-
ence.
#include <stdio.h>
int main()
{ int c;
for(c=0;++c; ++c)
printf("%d", c);
return 0;
}
Output This is an infinite loop. As the first pre-increment takes place, it results in c=1. Then the
test expression evaluates to 1 as c contains a non-zero value. Thus the loop continues.

6.3 Do-while construct


do
{
stmT; /* body of statements would be placed here*/

}while(TestExpr);

Figure 10: The C do-while loop

Consider the program:


#include <stdio.h>
int main()
{ int c=5;
while(c<5)
{
printf(" Hello");
c++;
}
return 0;
}

13
Output The program will print nothing. As the condition c¡5 fails, neither the printf() statement
nor C++ will be executed.

#include <stdio.h>
int main()
{ int c=5;
do
{ printf("Hello");
c++;
} while(c<5);
return 0;
}

Output Hello
Here, the statements within the loop are executed at least once.

7 Which loop should be used?


A question that must be asked is why are there while, do-while, and for loops? Is it a matter of style?

The while and for constructs are pre-test loops and the do-while construct is post-test loop. The
while and do-while loops are event-controlled whereas the for loop is counter-controlled. There are
three ways for controlling repetition in a program:Sentinel values, prime reads and counters

7.1 Using Sentinel values


A sentinel value is used to check for a stopping value. It is like a flag or an indicator. The user
can enter a sentinel value that would let the program know that the user has finished with inputting
information.

[-1] may be used as a sentinel value.

int main()
{int age;
printf("\n Enter an age(-1 to stop ):");
scanf("%d",&age);
while(age != -1)
{
.
.
.
printf("\n Enter an age(-1 to stop ):");
scanf("%d",&age);
}
return 0;
}

14
7.1.1 Using Prime Read
The variable that is inputted by the user and being tested by the expression in the loop is the prime
read; the value of the prime read is what one calls a sentinel value.

[age] is used as a prime read.


#include <stdio.h>
int main()
{
int age;
printf("\n Enter an age(-1 to stop):");
scanf("%d",&age);
while(age != -1)
{
.
.
.
printf("\n Enter an age(-1 to stop):");
scanf("%d",&age);
}
.
.
.
return 0;
}

7.2 Using Counter


Using a counter requires knowledge of the exact number of times something needs to be repeated.

8 GOTO Statement
The form of a goto statement is
goto label_name;
The control is unconditionally transferred to the statement associated with the label specified in the
goto statement. The statement label must be followed by a colon(:).

The following program is used to find the factorial of a number.


#include <stdio.h>
int main()
{
int n, c;
long int f=1;
printf("\n Enter the number:");
scanf("%d",&n);
if(n<0)

15
goto end;
for(c=1; c<=n; c++)
f*=c;
printf("\n FACTORIAL IS %ld", f);
end:
return 0;
}

9 Special Control Statements


There are certain control statements which terminate either a loop or a function. There are 3 such
statements, namely: return, break, and continue.

9.1 return statement


The return statement is used to terminate execution of the function. The return statement has two
forms.

Functions with return type void use the following form:

return;

Functions with non-void return type use the following form:

return expression;

9.2 break statement


The break statement is used in loop constructs such as for, while, and do-while, and switch state-
ment to terminate execution of the loop or switch statement. The form of a break statement is

break;

The statement while(1) leads to an infinite loop but by using the break statement it can be made to
a finite loop. This is illustrated in the following example.
Program 1

#include <stdio.h>
int main( )
{
int c=1;
while(1)
{
printf("\t %d", c);
c++;
}
return 0;
}

16
It is an infinite loop. It will print 1 2 3 4...

Program 2

#include <stdio.h>
int main( )
{
int c=1;
while(1)
{
if(c==5)
break;
printf("\t %d", c);
c++;
}
return 0;
}

or

#include <stdio.h>
int main( )
{
int c;
for(;;)
{
if(c==5)
break;
printf(" \t %d", c);
c++;
}
return 0;
}

It is a finite loop. It will print 1 2 3 4

9.3 Continue statement


The continue statement does not terminate the loop but goes to the test expression in the while and
do-while statements and then goes to the updating expression in a for statement. The form of a
continue statement is

continue;

Program code with break

#include <stdio.h>
int main( )
{ int c=1;
while(c<=5)
{

17
Figure 11: The jumps by continue in different pre-test and post-test loops are shown here.

if(c==3)
break;
printf("\t %d", c);
c++;
}
return 0;
}

Output 1 2
Program code with continue

#include <stdio.h>
int main()
{ int c = 0;
while(c<=5)
{
c++;
if(c==3)
continue;
printf("\t %d", c);
}
return 0;
}

Output 1 2 4 5 6

18
10 Nested loops
A nested loop refers to a loop that is contained within another loop.

for(count = 1; count < 100; count++)


{ do
{
/* the do...while loop */
}while(x != 0);
} /* end of for loop */

Example 1:

#include <stdio.h>
int main()
{ int row,col;
for(row=1;row<=4;++row)
{
for(col=1;col<=row;++col)
printf("%d \t", row);
printf("\n");
}
return 0;
}

Output:
1
22
333
4444

Example 2

#include <stdio.h>
int main ()
{
int i,j;
for (i = 1; i <= 10; i++)
{
for (j = 1; j <= 10; j++)
{
printf ("%5d",i * j);
}
printf ("\n");
}
return 0;
}

Output

19
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100
Example 3
#include <stdio.h>
int main()
{ int i,j;
for (i = 1; i <= 10; i++)
{
for (j = 1; j <= 10; j++)
{
printf ("%5d",i * j);
if(i==j)
break;
}
printf ("\n");
}
return 0;
}
Output:
1
2 4
3 6 9
4 8 12 16
5 10 15 20 25
6 12 18 24 30 36
7 14 21 28 35 42 49
8 16 24 32 40 48 56 64
9 18 27 36 45 54 63 72 81
10 20 30 40 50 60 70 80 90 100
Program for printing prime numbers between 1 and 100
#include <stdio.h>
#include <math.h>
int main()
{int i, j;
printf("%d\n", 2);
for(i = 3; i <= 100; ++i)
{

20
for(j = 2; j < i; ++j)
{
if(i % j == 0)
break;
if(j > sqrt(i))
{
printf("%d\n", i);
break;
}
}
}
return 0;
}

The following program is a simplied form of the previous program.

#include <stdio.h>
#include <math.h>
main(){ int i, j,r;
for(i = 2; i <= 100; ++i)
{
r=1;
for(j = 2; j <= sqrt(i); ++j)
{
r=i%j;
if(r == 0)
break;
}
if(r!=0)
printf("%d\n", i);
}
}

11 Common Programming Errors


11.1 Floating point equality
Do not use the equality operator with floating point numbers. To test for equality of floating point
operands such as a == b, use

if(fabs(a-b) < 0.000001)

21

Das könnte Ihnen auch gefallen