You are on page 1of 30

Introduction to C Programming - 22CPR13/23 UNIT - 2

Module-2: Decision Control and Looping Statements


Introduction to Decision Control Statements, Conditional Branching Statements (if, if-else, if
else-if, switch), Iterative Statements (while, do-while, for), Nested Loops, Break and Continue
Statements, Example Programs.
Decision Control Statement in C
In the case of decision control statements in C language (nested if and if-else), a group of
available statements will get executed in case the conditions we have are true. The execution
of the else part statements won’t occur whenever these available conditions happen to be
false.
The decision-making statements would require that the programmer handling the program
provides the program with the specification of single or multiple conditions that the program
gets to test or evaluate. It also needs to specify a statement or various other statements that
will get executed in case the determined condition is false.

∙ Use Of Decision Control Statement In C

∙ Types Of Decision Control Statement In C

∙ Summary Of Decision Control Statement In C

∙ The If Statement In C Language


o Syntax
o Use
o Example
∙ The If-Else Statement In C Language
o Syntax
o Use
o Example
∙ The Nested If Statement In C Language
o Syntax
o Example
∙ Practice Problems On Decision Control Statement In C

Use of Decision Control Statement in C


In a programming language, we must perform various tasks based on the conditions available
to us. For instance, let us consider an online website. Whenever someone enters the wrong
password or ID, it will display an error page, while if they enter the correct credentials, then
the website will display them a welcome page. Thus, there might be some type of logic here
that checks the available conditions (password and ID). If the conditions return to be true, then
it will perform the assigned task (in this case, displaying the welcome page). Or else, it will
perform a very different task (in this place, displaying the error page).
When we use the decision control statements, we get to control the flow of any program with
us in such a way that it gets to execute some statements on the basis of an available
condition’s outcome (the condition can be both true or false).
Types of Decision Control Statement in C
We have three major types of decision control statements that we use in the C programming
language. These are:

∙ nested if statements

∙ if-else statements

Page 1 of 29
Introduction to C Programming - 22CPR13/23 UNIT - 2

∙ if statements

Summary of Decision Control Statement in C


In the table available below, we have the syntax for every decision control statement in C
language, along with its description:
Type of Syntax Description
Decision
Control
Statements in C

if if (condition x) In the case of such a statement,


{ Statements; } when the available condition is
true, there occurs an execution of
a certain block of code.

if…else if (condition x) In the case of such a statement,


{ Statement x; Statement when the available condition is
y; } else true, then there occurs an
{ Statement a; Statement b; } execution of a certain group of
statements.
In case this available condition
turns out to be false, there occurs
an execution of the statement
specified in the else part.

nested if if (condition x){ Statement When the condition x is true, we


x; } else_if(condition y) get a resultant statement x.
{ Statement y; } When it is false, then the program
else Statement Z; automatically checks for the
condition y.
When condition y is true, there
occurs an execution of the
statement y.
When the condition y also fails,
then the final execution of the else
part occurs.

The if Statement in C Language


The execution of the statements available inside an if block will only happen when the
condition defined by this statement turns out to be true. In case the available condition is false,
the compiler will skip the available statement that gets enclosed in the body of the if
statement. One can have as many numbers of if statements in a program (in C language) as
we want.
Syntax:
The Syntax available for the if statement will be:
if (condition x)
{
// A block of statements for the C program
// The execution of these statements will only happen when this condition turns to be
true

Page 2 of 29
Introduction to C Programming - 22CPR13/23 UNIT - 2

}
There will be an execution of the statements available inside the body of the if block
whenever the given condition returns to be true. In case this condition returns to be false, then
the program will skip the statements that we have inside the if block.
Use:
This statement is one of the very simplest forms of decision control statements. We often use
it in the cases of simple decision-making cases in the C language.
Example:
Let us look at an example of a program that will ultimately print the highest
number. #include <stdio.h>
void main()
{
int x;
printf(―We enter any number:‖);
scanf(―%d‖, &x);
printf (―The number entered here is %d‖, x);
if (x>100)
printf (―Hi. You have entered a comparatively higher number.‖);
}
Here, in this program, the compiler will accept a number provided by the user as an input and
will generate an output accordingly. Here, we have also given the expression n>100. It means
that if the number given by the user is higher than the value of 100, then only we will get the
message as the output. Else, this statement will be skipped once and for all.
Thus,
Case #1:
If x = 300,
The output generated here will be:
Hi. You have entered a comparatively higher number.

Case #2:
If x = 50,
The compiler will skip the statement, ―Hi. You have entered a comparatively higher number. ‖

Page 3 of 29
Introduction to C Programming - 22CPR13/23 UNIT - 2

The if-else Statement in C Language


We have two blocks of statements in the case of this type of decision control statement- one if
the available condition is true and another one when this condition is false. When the
statement available in the if body results to be true, then the statement inside that block will
surely execute. In case it is false, then there will be an execution of the statement inside the
else block. It means that the else statement cannot exist in a program if there is no if
statement.
Syntax:
The syntax available for the if-else statement will be:
if (condition x)
{
// The statements present inside the body of if
}
else {
// The statements present inside the body of else
}
When the statement present in the if condition returns true, then the program will execute the
statement that is present inside the body of this block. Here, the compiler will skip the
statement that is present inside the body if the else block.
Conversely, when the condition present inside the if block is false, then the compiler will skip
the block and will execute the statement present in the else block.
Use:
Various times when a user writes that if a condition/ expression is true, then the compiler
must take an action. Else, if that statement is false, then the compiler will take a different
action. Thus, we can include an action for either of the conditions or include just a single
statement for the true condition and no action for any other condition. We use the if-else
statement here.
Example:
Let us look at an example of a program that we use in case of a leap
year. #include <stdio.h>
void main()
{
int year;
clrscr();
printf(―We will enter a year here:‖);
scanf(―%d‖, &yr);
if ((year%4 == 0) && ((year%100 !=0) || (year%400==0)))

Page 4 of 29
Introduction to C Programming - 22CPR13/23 UNIT - 2

printf(―Yes. The provided year is a leap year. Great job…!!!!‖);


else
printf (―No. The provided year is not a leap year. Try again….!!!‖);
}

Case #1:
year = 1893
The output generated here will be:
We enter a year: 1893
No. The provided year is not a leap year….!!!

Case #2:
year = 1564
The output generated here will be:
We enter a year: 1564
Yes. The provided year is a leap year. Great job…!!!!

The nested if Statement in C Language


The nested if statement is fairly useful in case a user needs to evaluate multiple types of
conditions. Here, the if block is present to define a condition (or an expression). The resultant
statement will get executed on the basis of the result of this expression (when the condition is
true or false).
Syntax:
The syntax available for the nested if statement will be:
{
if (condition x)
{ Statement x; }
// The C Statement for this condition
else_if(condition y)
// The C Statement for this condition
{ Statement y; }
else
Statement z;

Page 5 of 29
Introduction to C Programming - 22CPR13/23 UNIT - 2

default:

// The C Statement for this default condition


;
}
When the condition available in the if block is true, there will be an execution of the provided
statement. When it is false, the program will check the next condition. If it is true, the
execution of the statement associated with this condition will occur. In case this one is also
false, then there will be a default execution of a final statement. Here, we may have as many
types of cases as possible. However, there must be just one type of default statement.
Example:
Let us look at an example of a program that we use for finding out about two variables that
might be greater than or smaller than each other.
Case #1:
#include <stdio.h>
int main()
{
int a=40,b=20;
if (a>b) {
printf(―The number a is greater than the number b‖);
}
else if(a<n) {
printf(―The number a is less than the number b‖);
}
else {
printf(―The number a is equal to the number b‖);
}
}
The output generated here would be:
The number a is greater than the number b

Page 6 of 29
Introduction to C Programming - 22CPR13/23 UNIT - 2

Case #2:
#include <stdio.h>
int main()
{
int a=20,b=40;
if (a>b) {
printf(―The number a is greater than the number b‖);
}
else if(a<n) {
printf(―The number a is less than the number b‖);
}
else {
printf(―The number a is equal to the number
b‖); }
}
The output generated here would be:
The number a is less than the number b

Case #3:
#include <stdio.h>
int main()
{
int a=30,b=30;
if (a>b) {
printf(―The number a is greater than the number b‖);
}
else if(a<n) {
printf(―The number a is less than the number b‖);
}
else {
printf(―The number a is equal to the number b‖);

Page 7 of 29
Introduction to C Programming - 22CPR13/23 UNIT - 2

}}
The output generated here would be:
The number a is equal to the number b

Practice Problems on Decision Control Statement in


C 1. Take a look at the following program:
int main()
{
int p=50, q=50;
if (p == q)
{
printf(―The number p and the number q are
equal.‖); }
}
Output:
The number p and the number q are equal.
Is the output:
A. True
B. False
C. Both. It depends.
Answer – A. True

2. What would be the output of the following


program? #include <stdio.h>
int main()
{
int p=80, q=120;
if (p>q) {
printf(―The number p is greater than the number q‖);
}
else if(p<n) {
printf(―The number p is less than the number q‖);

Page 8 of 29
Introduction to C Programming - 22CPR13/23 UNIT - 2

}
else {
printf(―The number p is equal to the number q‖);
}
}

A. The number p is greater than the number q


B. The number p is less than the number q
C. The number p is equal to the number q
D. Compile time error
Answer – B. The number p is less than the number q

3. Take a look at the following program:


#include <stdio.h>
int main()
{
int age;
printf(―Please enter your age here:‖);
scanf(―%d‖,&age);
if(age >=18)
{
printf(―Okay. You are not eligible for voting today.‖);
}
else
{
printf(―Sorry. You are still not eligible for voting
today.‖); }
return 0;
}

Page 9 of 29
Introduction to C Programming - 22CPR13/23 UNIT - 2

Look at the pair of inputs and outputs. Which of these are true?
1. Please enter your age here: 12
Sorry. You are still not eligible for voting today.
2. Please enter your age here: 22
Okay. You are not eligible for voting today.
3. Please enter your age here: 35
Okay. You are not eligible for voting today.
4. Please enter your age here: 09
Sorry. You are still not eligible for voting today.
A. 1, 2, and 3
B. 3, 4
C. 1, 2, and 4
D. 1, 2, 3, and 4
Answer – D. 1, 2, 3, and 4

What is the difference between the if statement and the if-else statement?
The if statement is one of the very simplest forms of decision control statements. We often
use it in the cases of simple decision-making cases in the C language.
Syntax:
if (condition x)
{ Statements; }
The Description is:
In the case of such a statement, when the available condition is true, there occurs an
execution of a certain block of code.
if…else
Various times when a user writes that if a condition/ expression is true, then the compiler
must take an action. Else, if that statement is false, then the compiler will take a different
action. Thus, we can include an action for either of the conditions or include just a single
statement for the true condition and no action for any other condition. We use the if-else
statement here.
Syntax:
if (condition x)
{ Statement x; Statement y; }

Page 10 of 29
Introduction to C Programming - 22CPR13/23 UNIT - 2

else
{ Statement a; Statement b; }
The Description is:
In the case of such a statement, when the available condition is true, then there occurs an
execution of a certain group of statements. In case this available condition turns out to be
false, there occurs an execution of the statement specified in the else part.

Example program for if statement in c:


int main()
{
int m=40,n=40;
if (m == n)
{
printf("m and n are equal");
}
}

#include <stdio.h>
int main()
{
int m=40,n=20;
if (m == n)
{
printf("m and n are equal");
}
else
{
printf("m and n are not equal");
}
}

#include <stdio.h>
int main()

Page 11 of 29
Introduction to C Programming - 22CPR13/23 UNIT - 2

{
int m=40,n=20;
if (m>n) {
printf("m is greater than n");
}
else if(m<n) {
printf("m is less than n");
}
else {
printf("m is equal to n");
}
}

*********************************************************
* Statement - Prefect Leap Year
**********************************************************/
#include <stdio.h>
#include <conio.h>
void main()
{
int year;
clrscr();
printf("Enter the year : ");
scanf("%d",&year);
int temp=year/100;
if(year%100==0)
{
if(temp%4==0)
{
printf("%d is leap year.",year);
}
else

Page 12 of 29
Introduction to C Programming - 22CPR13/23 UNIT - 2

{
printf("%d is ordinary year.",year);
}
}
else
{
if(year%4==0)
{
printf("%d is leap year.",year);
}
else
{
printf("%d is ordinary year.",year);
}
}
getch();
}

/********************************************************************
Statement - ATM money dispatch count while currencies are 1000,500 and 100
*********************************************************************
#include<stdio.h>
#include<conio.h>
int totalThousand =1000;
int totalFiveFundred =1000;
int totalOneHundred =1000;
void main(){
unsigned long withdrawAmount;
unsigned long totalMoney;
int thousand=0,fiveHundred=0,oneHundred=0;
clrscr();
printf("Enter the amount in multiple of 100: ");

Page 13 of 29
Introduction to C Programming - 22CPR13/23 UNIT - 2

scanf("%lu",&withdrawAmount);
if(withdrawAmount %100 != 0){
printf("Invalid amount;");
getch();
return;
}
totalMoney = totalThousand * 1000 + totalFiveFundred* 500 +
totalOneHundred*100;
if(withdrawAmount > totalMoney){
printf("Sorry,Insufficient money");
getch();
return;
}
thousand = withdrawAmount / 1000;
if(thousand > totalThousand)
thousand = totalThousand;
withdrawAmount = withdrawAmount - thousand * 1000;
if (withdrawAmount > 0){
fiveHundred = withdrawAmount / 500;
if(fiveHundred > totalFiveFundred)
fiveHundred = totalFiveFundred;
withdrawAmount = withdrawAmount - fiveHundred * 500; }
if (withdrawAmount > 0)
oneHundred = withdrawAmount / 100;
printf("Total 1000 note: %d\n",thousand);
printf("Total 500 note: %d\n",fiveHundred);
printf("Total 100 note: %d\n",oneHundred);
getch();
}

Page 14 of 29
Introduction to C Programming - 22CPR13/23 UNIT - 2

/*******************************************************
Statement - Display Day of the month.
*******************************************************/
#include<stdio.h>
#include<conio.h>
#include<math.h>
int fm(int date, int month, int year) {
int fmonth, leap;
//leap function 1 for leap & 0 for non-leap
if ((year % 100 == 0) && (year % 400 != 0))
leap = 0;
else if (year % 4 == 0)
leap = 1;
else
leap = 0;
fmonth = 3 + (2 - leap) * ((month + 2) / (2 * month))
+ (5 * month + month / 9) / 2;
//bring it in range of 0 to 6
fmonth = fmonth % 7;
return fmonth;
}

int day_of_week(int date, int month, int year) {


int dayOfWeek;
int YY = year % 100;
int century = year / 100;
printf("\nDate: %d/%d/%d \n", date, month, year);
dayOfWeek = 1.25 * YY + fm(date, month, year) + date - 2 * (century % 4);
//remainder on division by 7
dayOfWeek = dayOfWeek % 7;
switch (dayOfWeek) {

Page 15 of 29
Introduction to C Programming - 22CPR13/23 UNIT - 2

case 0:
printf("weekday = Saturday");
break;
case 1:
printf("weekday = Sunday");
break;
case 2:
printf("weekday = Monday");
break;
case 3:
printf("weekday = Tuesday");
break;
case 4:
printf("weekday = Wednesday");
break;
case 5:
printf("weekday = Thursday");
break;
case 6:
printf("weekday = Friday");
break;
default:
printf("Incorrect data"); }
return 0;
}
//-----------------------------------------
- void main() {
int date, month, year;
clrscr();
printf("\nEnter the year ");
scanf("%d", &year);

Page 16 of 29
Introduction to C Programming - 22CPR13/23 UNIT - 2

printf("\nEnter the month ");


scanf("%d", &month);
printf("\nEnter the date ");
scanf("%d", &date);
day_of_week(date, month, year);
getch();
}
/**********
Output :
Enter the year 2015
Enter the month 12
Enter the date 16
Date: 16/12/2015
weekday = Wednesday
************/

Write a program to print the highest number.


#include <stdio.h>
void main()
{
int n;
printf("Enter a number:");
scanf("%d", &n);
printf ("The entered number %d", n);
if (n>100)
printf ("You entered a higher number"); }

Page 17 of 29
Introduction to C Programming - 22CPR13/23 UNIT - 2

Program for leap year


#include <stdio.h>
void main()
{
int yr;
clrscr();
printf("Enter a year:");
scanf("%d", &yr);
if ((yr%4 == 0) && ((yr%100 !=0) || (yr%400==0)))
printf("It's a leap year...!!!!");
else
printf ("It's not a leap year....!!!");
}

Program to find largest of the three numbers by using &&


operator. #include <stdio.h>
void main()
{
int n1=10, n2=30, n3=75;
if (n1>n2 && n1>n3)
printf("%d is the largest number",n1);
if(n2>n1 && n2>n3)
printf("%d is the largest number", n2);
else
printf("%d is the largest number", n3);
}

Write a program to check if the character entered is a vowel or not.


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

Page 18 of 29
Introduction to C Programming - 22CPR13/23 UNIT - 2

char ch;
printf("Enter any character:");
scanf("%c", &ch);
switch(ch)
{
case 'A':
case 'a':
case 'E':
case 'e':
case 'I':
case 'i':
case 'O':
case 'o':
case 'U':
case 'u':
printf("%c is a vowel",ch);
break;
default:
printf("%c is not a vowel", ch);
}

Write a c program to find out biggest of two


numbers. #include<stdio.h>
main()
{
int x,y,big;
printf(―enter the value for x = ―);
scanf(―%d‖, &x);
printf(―enter the value for y = ―);
scanf(―%d‖, &y);
if(x>y)
{

Page 19 of 29
Introduction to C Programming - 22CPR13/23 UNIT - 2

big=x;
printf(―biggest of given two number is %d‖, big);
}
else
{
big=y;
printf(―biggest of given two number is %d‖, big);
}

Iterative Statements

∙ C’s iteration statements are used to set up loops.

∙ A loop is a statement whose job is to repeatedly execute some other statement (the loop
body).
∙ In C, every loop has a controlling expression.

∙ Each time the loop body is executed (an iteration of the loop), the controlling expression
is evaluated.
– If the expression is true (has a value that’s not zero) the loop continues to execute.

C provides three iteration statements:

∙ The while statement is used for loops whose controlling expression is tested before the
loop body is executed.
∙ The do statement is used if the expression is tested after the loop body is executed. ∙ The
for statement is convenient for loops that increment or decrement a counting variable.

The while Statement

∙ Using a while statement is the easiest way to set up a loop.


∙ The while statement has the form

while ( expression ) statement

∙ expression is the controlling expression; statement is the loop body.

Example of a while statement:


while (i < n) /* controlling expression */
i = i * 2; /* loop body */

∙ When a while statement is executed, the controlling expression is evaluated first. ∙


If its value is nonzero (true), the loop body is executed and the expression is tested
again.

Page 20 of 29
Introduction to C Programming - 22CPR13/23 UNIT - 2

∙ The process continues until the controlling expression eventually has the value zero.

The while Statement


A while statement that computes the smallest power of 2 that is greater than or equal to a
number n:
i = 1;
while (i < n) i = i * 2;
A trace of the loop when n has the value 10:

The while Statement


Although the loop body must be a single statement, that’s merely a technicality. If
multiple statements are needed, use braces to create a single compound statement:
while (i > 0) {
printf("T minus %d and counting\n", i); i--;
}
Some programmers always use braces, even when they’re not strictly
necessary: while (i < n) { i = i * 2;
}

The while Statement


The following statements display a series of ―countdown‖ messages:
i = 10;
while (i > 0) {
printf("T minus %d and counting\n", i); i--;
}
The final message printed is T minus 1 and counting.

Page 21 of 29
Introduction to C Programming - 22CPR13/23 UNIT - 2

Observations about the while statement:


The controlling expression is false when a while loop terminates. Thus, when a loop
controlled by i>0 terminates, i must be less than or equal to 0.
The body of a while loop may not be executed at all, because the controlling expression is
tested before the body is executed.
A while statement can often be written in a variety of ways. A more concise version of the
countdown loop: while (i > 0)
printf("T minus %d and counting\n", i--);

Infinite Loops
A while statement won’t terminate if the controlling expression always has a nonzero value.
C programmers sometimes deliberately create an infinite loop by using a nonzero constant as
the controlling expression:
while (1) …
A while statement of this form will execute forever unless its body contains a statement that
transfers control out of the loop (break, goto, return) or calls a function that causes the
program to terminate.

Program: Printing a Table of Squares


The square.c program uses a while statement to print a table of
squares. The user specifies the number of entries in the table:
This program prints a table of squares. Enter number of entries in table: 5
11
24
39
4 16
5 25
square.c
/* Prints a table of squares using a while statement */
#include <stdio.h>
int main(void)
{

Page 22 of 29
Introduction to C Programming - 22CPR13/23 UNIT - 2

int i, n;

printf("This program prints a table of squares.\n"); printf("Enter number of entries in table:


"); scanf("%d", &n);
i = 1;
while (i <= n) { printf("%10d%10d\n", i, i * i); i++;
}
return 0;
}

Program: Summing a Series of Numbers


The sum.c program sums a series of integers entered by the user:
This program sums a series of integers. Enter integers (0 to terminate): 8 23 71 5 0 The sum
is: 107
The program will need a loop that uses scanf to read a number and then adds the number to a
running total.

/* Sums a series of numbers */ #include <stdio.h>


int main(void)
{
int n, sum = 0;
printf("This program sums a series of integers.\n"); printf("Enter integers (0 to terminate): ");

scanf("%d", &n); while (n != 0) {


sum += n; scanf("%d", &n);
}
printf("The sum is: %d\n", sum);

return 0;
}

Page 23 of 29
Introduction to C Programming - 22CPR13/23 UNIT - 2

The do Statement

∙ General form of the do statement:


statement expression
∙ When a do statement is executed, the loop body is executed first, then the controlling
expression is evaluated.
∙ If the value of the expression is nonzero, the loop body is executed again and then the
expression is evaluated once more.
The countdown example rewritten as a do statement:
i = 10;
do {
printf("T minus %d and counting\n", i);
--i;
} while (i > 0);

The do statement is often indistinguishable from the while statement.


The only difference is that the body of a do statement is always executed at least once.
It’s a good idea to use braces in all do statements, whether or not they’re needed, because a
do statement without braces can easily be mistaken for a while statement:
do
printf("T minus %d and counting\n", i--); while (i > 0);
A careless reader might think that the word while was the beginning of a while statement.

Program: Calculating the Number of Digits in an Integer


The numdigits.c program calculates the number of digits in an integer entered by the user:
Enter a nonnegative integer: 60 The number has 2 digit(s).
The program will divide the user’s input by 10 repeatedly until it becomes 0; the number of
divisions performed is the number of digits.
Writing this loop as a do statement is better than using a while statement, because every
integer— even 0—has at least one digit.
/* Calculates the number of digits in an integer */ #include <stdio.h>
int main(void)
{
int digits = 0, n;

Page 24 of 29
Introduction to C Programming - 22CPR13/23 UNIT - 2

printf("Enter a nonnegative integer: "); scanf("%d", &n);

do {
n /= 10; digits++;
} while (n > 0);
printf("The number has %d digit(s).\n", digits); return 0;
}

The for Statement


The for statement is ideal for loops that have a ―counting‖ variable, but it’s versatile enough
to be used for other kinds of loops as well.
General form of the for statement:
for ( expr1 ; expr2 ; expr3 ) statement
expr1, expr2, and expr3 are expressions.
Example:
for (i = 10; i > 0; i--)
printf("T minus %d and counting\n", i);

The for statement is closely related to the while statement.


Except in a few rare cases, a for loop can always be replaced by an equivalent while loop:
expr1;
while ( expr2 ) {
statement expr3;
}
expr1 is an initialization step that’s performed only once, before the loop begins to execute.
The for Statement
expr2 controls loop termination (the loop continues executing as long as the value of expr2 is
nonzero).
expr3 is an operation to be performed at the end of each loop iteration.
The result when this pattern is applied to the previous
for loop:
i = 10;

Page 25 of 29
Introduction to C Programming - 22CPR13/23 UNIT - 2

while (i > 0) {
printf("T minus %d and counting\n", i); i--; }
for Statement Idioms
The for statement is usually the best choice for loops that ―count up‖ (increment a
variable) or ―count down‖ (decrement a variable).
A for statement that counts up or down a total of n
times will usually have one of the following forms:

∙ Counting up from 0 to n–1: for (i = 0; i < n; i++) …

∙ Counting up from 1 to n: for (i = 1; i <= n; i++) …

∙ Counting down from n–1 to 0: for (i = n - 1; i >= 0; i--) …

∙ Counting down from n to 1: for (i = n; i > 0; i--) …

The Comma Operator

∙ On occasion, a for statement may need to have two (or more) initialization expressions
or one that increments several variables each time through the loop.
∙ This effect can be accomplished by using a comma expression as the first or third
expression in the for statement.
A comma expression has the form
expr1 , expr2
where expr1 and expr2 are any two expressions.

A comma expression is evaluated in two steps:


1. First, expr1 is evaluated and its value discarded.
2. Second, expr2 is evaluated; its value is the value of the entire expression. ∙ Evaluating
expr1 should always have a side effect; if it doesn’t, then expr1 serves no purpose.
∙ When the comma expression ++i, i + j is evaluated, i is first incremented, then i + j is
evaluated.
o If i and j have the values 1 and 5, respectively, the value of the expression will
be 7, and i will be incremented to 2.

Program: Printing a Table of Squares (Revisited)


/* Prints a table of squares using a for statement */
#include <stdio.h> int main(void)
{
int i, n;

Page 26 of 29
Introduction to C Programming - 22CPR13/23 UNIT - 2

printf("This program prints a table of squares.\n"); printf("Enter number of entries in table: ");
scanf("%d", &n);
for (i = 1; i <= n; i++) printf("%10d%10d\n", i, i * i);
return 0;
}

Program: Printing a Table of Squares (Revisited)


/* Prints a table of squares using an odd method */
#include <stdio.h>
int main(void)
{
int i, n, odd, square;
printf("This program prints a table of squares.\n"); printf("Enter number of entries in table: ");
scanf("%d", &n);
i = 1;
odd = 3;
for (square = 1; i <= n; odd += 2) { printf("%10d%10d\n", i, square);
++i;
square += odd;
}
return 0;
}

Exiting from a Loop


The normal exit point for a loop is at the beginning (as in a while or for statement) or at the
end (the do statement).
Using the break statement, it’s possible to write a loop with an exit point in the middle or a
loop with more than one exit point.

∙ The break statement can transfer control out of a switch statement, but it can also be used
to jump out of a while, do, or for loop.
∙ A loop that checks whether a number n is prime can use a break statement to terminate the
loop as soon as a divisor is found:
for (d = 2; d < n; d++) if (n % d == 0)
break;

Page 27 of 29
Introduction to C Programming - 22CPR13/23 UNIT - 2

The break Statement


After the loop has terminated, an if statement can be use to determine whether termination
was premature (hence n isn’t prime) or normal (n is prime):
if (d < n)
printf("%d is divisible by %d\n", n, d); else
printf( %d is prime\n , n);

∙ The break statement is particularly useful for writing loops in which the exit point is in
the middle of the body rather than at the beginning or end.
Loops that read user input, terminating when a particular value is entered, often fall
into this category:
for (;;) {
printf("Enter a number (enter 0 to stop): "); scanf("%d", &n);
if (n == 0) break;
printf("%d cubed is %d\n", n, n * n * n);
}

∙ A break statement transfers control out of the innermost enclosing while, do, for, or
switch.
∙ When these statements are nested, the break statement can escape only one level of
nesting.
Example:
while (…) { switch (…) {

break;

}
}

∙ break transfers control out of the switch statement, but not out of the while loop.

Page 28 of 29
Introduction to C Programming - 22CPR13/23 UNIT - 2

The continue Statement


The continue statement is similar to break:
o break transfers control just past the end of a loop.
o continue transfers control to a point just before the end of the loop body. ∙ With break,

control leaves the loop; with continue, control remains inside the loop. ∙ There’s another
difference between break and continue: break can be used in switch statements and loops
(while, do, and for), whereas continue is limited to loops.

The continue Statement


o A loop that uses the continue statement:

sum = 0;
while (n < 10) { scanf("%d", &i); if (i == 0)
continue; sum += i; n++;
/* continue jumps to here */
}

o The same loop written without using continue:


sum = 0;
while (n < 10) { scanf("%d", &i); if (i != 0) {
sum += i; n++;
}
}

Page 29 of 29

You might also like