0% found this document useful (0 votes)
14 views191 pages

Module 2 Part B

The document provides an introduction to decision control statements in C programming, focusing on conditional branching statements such as if, if-else, and if-else-if. It explains how these statements allow for selective execution of code based on certain conditions and includes examples of their usage. Additionally, it covers the syntax and structure of these statements, along with programming tips to avoid common pitfalls.

Uploaded by

Raghu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views191 pages

Module 2 Part B

The document provides an introduction to decision control statements in C programming, focusing on conditional branching statements such as if, if-else, and if-else-if. It explains how these statements allow for selective execution of code based on certain conditions and includes examples of their usage. Additionally, it covers the syntax and structure of these statements, along with programming tips to avoid common pitfalls.

Uploaded by

Raghu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 191

TAKEAWAYS

* Decision control statements


* Conditional branching statements

ETB INTRODUCTION TO DECISION


CONTROL STATEMENTS

Till now we know that the code in a C program is executed


sequentially from the first line of the program to its last
line, i.c., the second statement is executed after the first,
the third statement is executed after the second, and so on.

Although this is true, but in some cases we want only


sclected statements to be executed. Such type of conditional
processing extends the usefulness of programs. It allows
the programmers to build programs that determine which
statements of the code should be executed and which
should be ignored.

C supports two types of decision control statements


that can alter the flow of a sequence of instructions. These
include conditional type branching and unconditional
type branching. Figure 10.1 shows the categorization of
decision control statements in C language.

CONDITIONAL BRANCHING
STATEMENTS

The conditional branching statements help to jump from


one part of the program to another depending on whether
@ particular condition is satisfied or not. These decision
control statements include

* ifstatement

* if-else statement

* if-else-if statement
* switch statement

10.2.1 if Statement

The if statement is the simplest form of decision control


ion-making,
$s shown in

statements that is frequently used in dec


The general form of a simple if statement
Figure 10.2

Decision Control and


¢ ‘Looping Statements

* Iterative statements
* For, while, do-while loops
* Nested loops
* Break, continue, and goto statements

Selection/Branching
statement
Conditional Unconditional
type type
if if-else if-else-if switeh

Figure 10.1 Decision control statements

The if block may include one statement or n statements


enclosed within curly brackets. First, the test expression is
evaluated. If the test expression is true, the statement of
if block (statement | to ) are executed otherwise these
statements will be skipped and the execution will jump to
statement x

The statement in an

i.
Lib ana f : any va
Properiindentthe ace statement and. the
Aebtoss tee eaprbatiss is any valid Cc
dependent on the : SEER
<. _ language expression that may
include logical operators. Note

SYNTAX OF IF STATEMENT Test FALSE


Expression

if (test expression)
TRUE

statement 1;

Statement Block |
statement n;

statement x;
Statement x

Figure 10.2 if statement construct

206 Computer Fundamentals and Programming in C

that there is no semicolon after the test expression. This is


because the condition and statement should be put together
48 a single statement

#include <stdio.h>
int main()

{
int x=10; // Initialize the value of x
if ( x20) // Test the value of x

xt+5 // Increment x if it is > 0


printf("\n x = Xd", x);
// Print the value of x
return 0;
}
Output
X= 11

In the above code, we take a variable x and initialize it


to 10, In the test expression we check if the value of x is
greater than 0, If the test expression evaluates to true then
the value of x is incremented and is printed on the screen.
The output of this program is

xell

Observe that the printf statement will be executed


even if the test expression is false

1. Write a program to determine whether a person is


cligible to vote or not

#include <stdio.h>

#include <conio.h>

int main()

{
int age;
printf("\n Enter the age: “);
scanf("Xd", &age);
if(age >= 18)
printf("\n You are eligible to vote");
getch();
return 0;

Output

Enter the age: 28


You are eligible to vote

In case the statement block contains only one statement,


putting curly brackets becomes optional. If there is more
than one statement in the statement block, putting curly
brackets becomes mandatory,
2. Write a program to determine the character entered by
the user.

#include <stdio.h>
#include <ctype.h>

#include <conio.h>
int main()
{
char ch;
printf("\n Press any key:
scanf("%e", &ch);
if(isalpha(ch)>0)
printf("\n The user has entered a
character");
if (isdigit(ch)>0)
printf("\n The user has entered a digit”);
if(isprint(ch)>0)
printf("\n The user has entered a
printable character");
if(ispunct(ch) 0)
printf("\n The user has entered a
punctuation mark");
if(isspace(ch)>0)
printf("\n The user has entered a white
space character");
getch();
return 0;

}
Output

Press any key: 3


The user has entered a digit

Now let us write a program to detect errors during data


input. But before doing this we must remember that when
the scanf() function completes its action, it returns the
number of items that are successfully read. We can use
this retumed value to test if any error has occurred during
data input. For example, consider the following function:

scanf("Xd Sf %c", &a, &b, &c);


If the user enters
11.2A

then the scanf() function will return 3, since three values


have been successfully read. But had the user entered,

l abc A

then the scanf() function will immediately terminate when


it encounters abe as it was expecting a floating point value
and will print an error message. So after understanding
this concept, let us write a program code to detect an error
in data input.
include <stdio.h>
main()
{
int num;
char ch;
printf("\n Enter an int and a char value:
"3
// Check the return value of scanf()
if(scanf ("Xd Xe", &num, &ch)==2)

printf("\n Data read successfully");


else
printf("\n Error in data input");
}
Output

Enter an int and a char value: 2A


Data read successfully

10.2.2 if-else Statement

We have studied that the if statement plays a vital role


in conditional branching. Its usage is very simple. The
test expression is evaluated. If the result is true, the

statement(s) followed by the expression is executed else if


the expression is false, the statement is skipped by the
compiler
But what if you want a

Programming Tip: Separate set of statements to


Align the matching be executed if the expression
if-else clauses returns a zero value? In such

vertically. cases, we use an if-else


statement rather than using
simple if statement. The general form of a simple if-
else statement is shown in Figure 10.3
In the syntax shown, we have written statement block
A statement block may include one or more statements.
According to the if-else construct, first the test expression
is evaluated. If the expression is true, statement block 1 is
executed and statement block 2 is skipped. Otherwise, if
the expression is false, statement block 2 is executed and
statement block | is ignored. Now in any case after the
statement block | or 2 gets executed, the control will pass
to statement x, Therefore, statement x is executed in every
Case.

3. Write a program to find whether the given number is


even or odd.

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

SYNTAX OF IF-ELSE STATEMENT

if (test expression) TRUE


{

statement block 1;
else
statement block 2;

statement x;

Decision Control and Looping Statements 207

int num;

clrser();

printf("\n Enter any number: “);

scanf( "Xd", &num) ;

if(num&2 == 0)

printf("\n %d is an even number", num) ;


else
printf("\n %d is an odd number", num);
return 0;

Output

Enter any number: 11


11 is an odd number

4. Write a program to enter any character. If the entered


character is in lower case then convert it into upper case
and if it is a lower case character then convert it into
upper case.

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

char ch;

elrser();

printf("\n Enter any character: ");


scanf("%c", &ch);

if(ch >e'A’ BB chew'Z')

printf("\n The entered character is in upper


case. In lower case it is: %c", (ch+32))
else

printf("\n The entered character is in lower


case. In upper case it is: %c", (ch-32));
return 0;

Output

Enter any character: a


The entered character is in lower case, In
upper case it is: A

Test FALSE

Statement Block 2

‘Statement x
Figure 10.3 if-else statement construct

208

Computer Fundamentals and Programming in C


§. Write a program to enter a character and then determine
whether it is a yowel or not

#include <stdio.h>
#include <conio.h>

int main()
{
char ch;
clrser();
printf("\n Enter any character: “);
scanf("%e", &ch);
if(ch ='a* ||ch =="e' [|ch=="i' ||ch=="o’

[|che=*u’ || chee'A’ |[che='E* || che«


||che="0" ||che=tu’ )
printf("\n %c is a vowel", ch);
else
printf("\n %c is not a vowel");
getch();
return 0;
}
Output

Enter any character: v


v is not a vowel

6. Write a program to find whether a given year is a leap


year or not
#include <stdio.h>
#include <conio.h>
int main()
{
int year;
clrser();
printf("\n Enter any year: );
scanf("%d", &year);
if(((year%4 == 0) && ((year%100 !=0)) ||
(year%400 == 0))
printf("\n Leap Year");
else
printf("\n Not a Leap Year");

SYNTAX OF IF-ELSE-IF STATEMENT


if ( test expression 1) TRUE
statement block 1; State Block 1
else if ( test expression 2)

statement block 2;
statement block x;
}

statement y;

Figure 10.4

return 0;

}
Output

Enter any year: 1996


Leap Year

Pitfall A very common pitfall while using if statements


is fo use assignment operator (=) instead of comparison
operator (==). For example, consider the statement

if(a = 10)
printf("xd", a);

Here, the statement does not test whether a is equal to


10 or not. Rather the value 10 is assigned to a and then the
value is returned to the if construct for testing. Since the
value of a is non-zero, the if construct returns a 1.

The compiler cannot detect

Programming Tip: such kinds of errors and


Do not use floating thus the programmer should
point numbers for carefully use the operators.
checking for equality The program code given
ina test expression. below shows the outcome of

mishandling the assignment


and the comparison operators,

#include <stdio.h>

main()
{
int x = 2, y = 3;
if(x = y)
printf("\n EQUAL");
else
printf("\n NOT EQUAL");
}
Output
EQUAL
#include <stdio.h>
main()
Test FALSE
Expression
Test FALSE
Expression 2
TRUE
‘Statement Block 2 ‘Statement Block x
‘Statement y

if-else-if statement construct

int x = 2, y = 3;
if(x == y)
printf("\n EQUAL");
else
print#("\n NOT EQUAL");
}

Output
NOT EQUAL

10.2.3 if-else-if Statement

C language supports if-else-if statements to test


additional conditions apart from the initial test expression.
The if-else-if construct works in the same way as a
normal if statement, if-else-if construct is also known
as nested if construct, Its construct is given in Figure 10.4
It is not necessary that
Programming Tip: every if statement should
Braces must be have an else block as C
placed on separate supports simple if statements.
lines sothatthe Block = After the first test expression
Of statements can be or the first if branch, the
easily identified. 2

programmer can have as many


else-if branches as he wants
depending on the expressions that have to be tested. For
example, the following code tests whether a number
dd by the user is negative,

7. Write a program to demonstrate the use of nested if


structure

ent

positive, or equal to zero.

#include <stdio.h>
int main()
{
int x, y;
printf("\n Enter two numbers: “);
scanf("%d Xd", &x, &y);
if(x == y)
printf("\n The two numbers are equal”);
else if(x > y)
printf("\n %d is greater than Xd", x, y);
else
printf("\n Xd is smaller than Xd", x, y);
return 0;
}
Output

Enter two numbers: 12 23


12 is smaller than 23

8. Write a program to test whether a number entered is


positive, negative, or equal to zero.

#include <stdio.h>
int main()
{
int num;
printf("\n Enter any number:

Decision Control and Looping Statements | (209

scanf("Xd", Sum);

Programming Tip: =
if (num==0)
Keep the logical printf("\n The number is
expressions simple equal to zero");
and short. For this, ‘
else if(num>0)
Vesr os beinebiare print#("\n The number is
statements. positive");
else
printf("\n The number is
negative");
return 0;
}
Output

Enter any number: 0


The number is equal to zero

In the above program to test whether a number is


positive or negative, if the first test expression evaluates
to a true value then rest of the statements in the code will
be ignored and after executing the printf statement which
displays “The number is equal to zero”, the control
will jump to return 0 statement

9. Acompany decides to give bonus to all its employees on


Diwali. A 5% bonus on salary is given to the male workers
and 10% bonus on salary to the female workers, Write a
program to enter the salary and sex of the employee. If
the salary of the employee is less than Rs 10,000 then the
employee gets an extra 2% bonus on salary, Calculate the
bonus that has to be given to the employee and display
the salary that the employee will get

include <stdio.h>
include <conio.h>
int main()
{
char ch;
float sal, bonus, amt_to_be paid;
printf("\n Enter the sex of the employee
(m or f): ")5
scanf("%c", Bch);
printf("\n Enter the salary of the
employee: “);
scanf("Xf", &sal);
if(ch = ‘m')
bonus = 0.05 * sal;
else
bonus = 0.10 * sal;
if (sal < 10000)
bonus += 0.20 * sal;
amt_to_be_paid = sal + bonus;
printf("\n Salary = xf", sal);
printf("\n Bonus = Xf", bonus);
printf("\n teeeeeeneeweres
printf("\n Amount to be paid: %f", amt_to_
be_paid);
getch();

seneeweeeny:
210 Computer Fundamentals and Programming in C

return 0;

}
Output

Enter the sex of the employee (m or f): f


Enter the salary of the employee: 12000
Salary = 12000

Bonus = 1200

Amount to be paid: 13200

Consider the following code which shows usage of the


if-else-if statement

‘The AND operand (&&) is used to form a compound relation


expression. In C, the following expression is invalid.

if (60 < marks < 75)


The correct way to write is as follows:

if ((marks 2 60) && (marks < 75))


10. Write a program to display the examination result

#include <stdio.h>
int main()
{
int marks;
printf("\n Enter the marks obtained: ");
scanf("Kd", &marks);
if ( marks >= 75)
printf("\n DISTINCTION");

else if ( marks >= 60 88


Programming Tip: marks <75)

Try to use the printf("\n FIRST


most probable DIVISION");
condition first so that else if ( marks >= SO 6&
unnecessary tests marks < 60)
are eliminated and printf(“\n SECOND
the efficiency of the DIVISION");
program is improved. else if ( marks >= 40 &&
marks < 50)
printf("\n THIRD DIVISION") ;
else
printf("\n FAIL");
return 0;
}
Output
Enter the marks obtained: 55
SECOND DIVISION

11. Write a program to calculate tax, given the following


conditions;

if income is less than 1,50,000 then no tax

* iftaxable income is in the range 1,50,001—300,000 then


charge 10% tax

* if taxable income is in the range 3,00,001-500,000 then

charge 20% tax

* iftaxable income is above 5,00,001 then charge 30% tax

®include <stdio.h>
include <conio.h>
Sdefine MIN1 150001
Sdefine MAX1 300000
Sdefine RATE1 0.10
define MIN2 300001
define MAX2 500000
define RATE2 0.20
define MIN3 500001
Sdefine RATE3 0.30
int main()
{
double income, taxable income, tax;
clrser();
printf("\n Enter the income: “);
scanf("R1#", &income) ;
taxable_income = income - 150000;
if(taxable_income <* 0)
printf("\n NO TAX");
else if(taxable_income >= MIN1 && taxable_
income < MAX1)
tax = (taxable income - MIN1) * RATE1;
else if(taxable_income >= MIN2 && taxable_
income < MAX2)
tax = (taxable_income - MIN2) * RATE2;
else
tax = (taxable income - MIN3) * RATE3;
printf("\n TAX = %1f", tax);
getch();
return 0;

}
Output

Enter the income: 900000


TAX = 74999.70

12. Write a program to find the greatest of three numbers.


#include <stdio.h>

include <conio.h>

int main()

{
int numl, num2, num3, bige0;
clrscr();
printf("\n Enter the first number: ");
scanf("X%d", &num1);
printf("\n Enter the second number: ");
scanf("Xa", &num2);
printf("\n Enter the third number: “);
scanf("X%d", &num3);
if (num1>num2)

if (numi>num3)
printf("\n Xd is greater than Xd and Xd",
numi, num2, num3);

else
printf("\n %d is greater than Xd and Xd",
num3, num1, num2);

}
else if(num2>num3)
printf("\n %d is greater than %d and Xa",
fnum2, uml, num3);
else
printf("\n Xd is greater than Xd and Xd",
num3, numi, mum2);

return 0;

Programming Tip: }

sented aT Osspat

indent the statements [ter the first umber: 12


inthe block by atleast Enter the second number:
three spaces to the 23

right of the braces. Enter the third number: 9

23 is greater than 12 and 9

13. Write a program to input three numbers and then find


largest of them using && operator

#include <stdio.h>
#include <conio.h>
int main()
{
int num1, num2, num3;
clrser();
printf("\n Enter the first number: “);
scanf("%d", &num1);
printf("\n Enter the second number: “);
scanf("%d", &num2);
printf("\n Enter the third number: “);
scanf("%d", &num3);
if(numl>num2 && numi>num3)
printf("\n Xd is the largest number”, num);
if(num2>num1 && num2>num3)
printf("\n Xd is the largest number”,
num2) ;
else
printf("\n Xd is the largest number™, num3);
getch();
return 0;
}
Output

Enter the first number: 12


Enter the second number: 23
Enter the third number: 9
23 is the largest number

14. Write a program to enter the marks of a student in


four subjects. Then calculate the total, aggregate, and
display the grades obtained by the student

#include <stdio.h>
#include <conio.h>

Decision Control and Looping Statements 21


int main()
{
int marksi, marks2, marks3, marks4,
total = 0;
float avg =0.0;
clrser();
printf("\n Enter the marks in
Mathematics: *);
scanf("Xd", &marks1);
printf("\n Enter the marks in Science: ");
scanf("%d", &marks2);
printf("\n Enter the marks in Social
Science: ");
scanf("Xd", &marks3);
printf("\n Enter the marks in Computer
Science: ");
scanf("%d", &marks4);
total = marksl + marks2 + marks3 + marks4;
avg = (float) total/4;
printf("\n TOTAL « Xd", total);
printf("\n AGGREGATE » %.2", avg);
if(avg >= 75)
printf("\n DISTINCTION");
else if(avg>=60 8& avg<75)
peintf("\n FIRST DIVISION");
else if(avg>=50 8& avg<60)
printf("\n SECOND DIVISION");
else if(avg>=40 && avg<50)
printf("\n THIRD DIVISION");
else
printf("\n FAIL");
return 0;
}

Output

Enter the marks in Mathematics: 90


Enter the marks in Science: 91

Enter the marks in Social Science: 92


Enter the marks in Computer Science: 93
TOTAL = 366

AGGREGATE = 91.00

DISTINCTION

15. Write a program to calculate the roots of a quadratic

equation.

#include <stdio.h>
#include <math.h>
#include <conio.h>
void main()

{
int a, b, cj

float D, deno, rootl, root2;

clrser();

printf("\n Enter the values of a, b,


and ¢ :");

scanf("%d %d Xd", Sa, &b, &c);

D=(b*b)- (4*a*c);

212 Computer Fundamentals and Programming in C

deno = 2 * a;

if(D > 0)

{
printf("\n REAL ROOTS");
rooti = (-b + sqrt(D)) / deno;
root2 = (-b - sqrt(D)) / deno;
printf("\n ROOT1 = Xf \t ROOT 2 = Xf",

rooti, root2);

}
else if(D == 0)

{
print#("\n EQUAL ROOTS”);
rootl « -b/deno;
printf("\n ROOT] = %f \t ROOT 2 = X#",
rootl, rootl);

else
printf("\n IMAGINARY ROOTS”);

getch();

Output

Enter the values of a, b, andc : 345


IMAGINARY ROOTS

Let us now summarize the rules for using if, if-else,


and if-else~if statements.

Rule 1: The expression must be enclosed in parentheses.

Rule 2: No semicolon is placed afler the if/if-else/


if-else-if statement. Semicolon is placed only at the end
of statements in the statement block.

Rule 3: A statement block begins and ends with a curly


brace. No semicolon is placed after the opening/closing
braces.

Dangling Else Problem

With nesting of if-else statements, we often encounter


a problem known as dangling

Programming Tip: else problem, This problem


While forming is created when there is no
the conditional matching else for every if
expression, try to use statement. In such cases, C
positive statements always pairs an else statement
rather than using to the most recent unpaired if
compound negative statement in the current block.
statements. Consider the following code
which shows such a scenario.
if(a > b)
if(a > c)
printf("\n a is greater than b and c”);
else

printf("\n a is not greater than b and c");


The problem is that both the outer if statement and
the inner if statement might conceivably own the else

clause. So the programmer must always see that every if


statement is paired with an appropriate else statement.

Comparing Floating Point Numbers

We should never use floating point numbers for testing


equality. This is because floating point numbers are just
approximations, so it is always better to use floating point
numbers for testing ‘approximately equal’ rather than
testing for exactly equal.

We can test for approximate equality by subtracting


the two floating point numbers (that are to be tested) and
comparing their absolute value of the difference against a
very small number, epsilon. For example, consider the code
given below which compares two floating point numbers.
Note that epsilon is chosen by the programmer to be small
enough so that the two numbers can be considered equal.

#include <stdio.h>
#include <math.h>
define EPSILON 1.0e-5
int main()
{
double numi = 10.0, num2 = 9.5;
double resi, res2;
resi = num2 / numl * numl;
res2 = num2;
/* fabs() is a € Library function that
returns the floating point absolute value */
if(fabs(res2 - resl) < EPSILON)
print# (“EQUAL”);
else
print#("NOT EQUAL");
return 0;

Also note that adding a very small floating point value


to 4 very large floating point value or subtracting floating
point numbers of widely differing magnitudes may not
have any effect. This is because adding/subtracting two
floating point numbers that differ in magnitude by more
than the precision of the data type used will not affect the
larger number.

10.2.4 switch case

A switch case statement is a multi-way decision statement

that is a simplified version of an if-else block that evaluates

only one variable. The general form of a switch statement


is shown in Figure 10.5,
Programming Tip: Table 10.1 compares
tis always general form of a switch
recommended to statement with that of an
usedefauttlabeling =i ¢e1se statement,

switch statement.

Here, statement blocks refer


to statement lists that may
contain zero or more statements, These statements in the
block are not enclosed within opening and closing braces.

Decision Control and Looping Statements 213

TRUE
Value |
Statement Block | FALSE
Syntax of Switch Statement = Value 2
switch ( variable ) FALSE
case valuel: Statement Block 2
Statement Block 1;
break; en
case value2: FALSE
Statement Block 2;
break; TRUE
ot a Value N
case value N:;
Statement Block N;
Statement Block N FALSE
Statement Block D;
break; Statement Block D
}
Statement x;
Statement X

Figure 10.5 The switch statement construct

eC Comparison between the switch


and if-else construct

Generalized switch statement | Generalized if-else statement

switeh(x) { iffexp1)
case 1: // do this {
case 2: // do this H do this,
case 3: // do this )
tae else iffexp2)
default: //do this {
} Wt do this

else iftexp3)

4 do this
1

The power of nested if-else statements lies in the fact


that it can evaluate more than one expression in a single
logical structure. Switch statements are mostly used in two
situations:

+ When there is only one variable to evaluate in the


expression
* When many conditions are being tested for

When there are many conditions to test, using the if


and else-if constructs becomes a bit complicated and
confusing. Therefore, switch case statements are often
used as an alternative to long if statements that compare
a variable to several integral values (integral values are
those values that can be expressed as an integer, such as
the value of a char). Switch statements are also used to
handle the input given by the user.

We have already seen the syntax of the switch


statement, The switch case statement compares the
value of the variable given in the switch statement with
the value of cach case statement that follows, When the
value of the switch and the case statement matches, the
statement block of that particular case is executed

Did you notice the keyword default in the syntax of


the switch case statement? default is also a case that is
executed when the value of the variable docs not match
with any of the values of the case statement, i.c., the
default case is executed when no match is found between
the values of switch and case statements and thus there
are no statements to be executed. Although the default
case is optional, it is always recommended to include it as

it handles any unexpected cases.


In the syntax of the switch

Programming Tip: case statement, we have used


C supports decision another keyword break, The
control statements break statement must be used at
that can alter the the end of each case because if
flow of a sequence it is not used, then the case that
ol instructions: matched and all the following
Asuitchscace cases will be executed. For
statement is'a example, if the value of switch
multi-way decision statement matched with that of
statement that is a case 2, then all the statements
simplified version in case 2 as well as rest of the
of an if-else block cases including default will be
that evaluates only executed. The break statement
one variable. tells the compiler to jump out

214 Computer Fundamentals and Programming in C


Of the switch case statement and execute the statement And if option was equal to 3 or any
other value then

following the switch case construct. Thus, the keyword break — only the default case would
have been executed, thereby

is used to break out of the case statements. It indicates the __ printing

end of a case and prevents the program from falling through

and executing the code in all the rest of the case stateme:
Consider the following example of switch statement. To summarize the switch case construct,
let us go

through the following rules:

In case default

S.

char grade = 'C'


+ The control expression that

switch(grade)
{ Programming Tip: follows the keyword switch
case ‘0’; cathe le must be of integral type
printf("\n Outstanding”); pearpeomebate te (Le., either an integer or any
break; 3 value that can be converted
case ‘A’: you may tise nested to an integer)
printf("\n Excellent"); a + Each case label should be
break; followed with a constant or
case ‘'B’: Programming Tip: @ constant expression
printf("\n Good"); Default is also a case + Every case label must
break; that is executed evaluate t0 a unique
case 'C': when the value of constant expression value
printf("\n Satisfactory"); the variable does * Case labels must end with a
breal not match with any colon,
case ‘F*: of the values of case * Two case labels may have
printf("\n Fail"); statements. the same set of actions

associated with them,

breal
defaul * The default label is optional and is executed only when
printf("\n Invalid Grade"); the value of the expression does not match with any
break; labelled constant expression. It is recommended to have
} a default case in every switch case stutement

* The default label can be placed anywhere in the switch


statement. But the most appropriate position of default
Satisfactory case is at the end of the switch case statement
* There can be only one default label in a switch statement
16. Write a program to demonstrate the use of switch * C permits nested switch statements,
ic, a switch
statement without a break. statement within another switch statement.

Output
17. Write a program to determine whether an entered

#include <stdio.h>

. maint) character is a vowel or not


int option = 1; #include <stdio.h>
switch(option) int main()
{{
case 1: printf(“\n In case 17); char ch;
case 2: printf("\n In case 2"); printf("\n Enter any character: “);
default: printf("\n In case default”); scanf("Xe", &ch);
} switch(ch)
return 0; {
} case ‘A’:
Output case, ‘8+
printf("\n % c is vowel”, ch);
In case 1 break;
In case 2 case 'E’:
In case default case ‘e':
printf("\n % c is vowel”, ch);
Had the value of option been 2, then the output would break;
have been dese: oY"
In case 2 case ‘i’:

In case default printf("\n % c is vowel”, ch);

break;
case ‘0
case 'o
printf("\n % c is vowel”, ch);
break;
case ‘U

case ‘u':
printf("\n % c is vowel", ch);
break;

default: printf("Kc is not a vowel”, ch);

return 0;
}
Output

Enter any character: E


E is vowel

Note that there is no break statement after case A, so if


the character ‘A’ is entered, then the control will execute
the statements given in case ‘a'

18. Write a program to enter a number from 1-7 and


display the corresponding day of the week using
switch case statement

#include <stdio.h>
#include <conio.h>
int main()
{
int day;
clrser();
printf("\n Enter any number from 1 to 7: “);
scanf("%d", &day) ;

switch(day)

{
case 1: printf(“\n SUNDAY");
break;
case 2: printf("\n MONDAY");
break;
case 3: printf("\n TUESDAY");
break;
case 4: printf("\n WEDNESDAY");
break;
case 5: printf("\n THURSDAY");
break;
case 6: printf("\n FRIDAY");
breakjw
case 7: printf("\n SATURDAY");
break;
default: printf("\n Wrong Number”);

}
return 0;

Output
Enter any number from 1 to 7: 5
THURSDAY

Decision Control and Looping Statements 215

19, Write a program that accepts a number from 1 to TO!


Print whether the number is even or odd using a switch
case construct

#include <stdio.h>
void main()
{
int num;
printf("\n Enter any number (1 to 10)
scanf("%", &num);
switch(num)

case 1
case 3:
case 5:
case 7:
case 9:
printf("\n 000");
break;
case 2:
case 4:
case 6:
case 8:
case 10:
printf("\n EVEN");
default
printf("\n INVALID INPUT");
break;

OR

#include <stdio.h>
void main()
{
int num, rem;
printf("\n Enter any number (1 to 10): ");
scanf("%", &num);
rem = num%2;
switch(rem)
{
case 0:
printf("\n EVEN");
break;
case 1:
printf("\n 000");
break;
}
}

Output
Enter any number from 1 to 10: 7
oop

Advantages of Using a switch case Statement

Switch case statement is preferred by programmers due


to the following reasons

216 Computer Fundamentals and Programming in C

* Easy to debug

Easy to read and understand

* Ease of maintenance as compared with its equivalent


if-else statements

* Like if-else statements, switch statements can also be


nested

+ Executes faster than its equivalent if-else construct

GUE) ITERATIVE STATEMENTS

Iterative statements are used to repeat the execution of a


list of statements, depending on the value of an integer
expression, C language supports three types of iterative
statements also known as looping statements. They are:

* while loop

* do-while loop

* for loop

In this section, we will discuss all these statements.

10.3.1 while Loop

The while loop provide:


statements while a particular condition is true. Figure 10.6
shows the syntax and general form of representation of a
while loop.

In the while loop, the condition is tested before any of


the statements in the statement block is executed, If the
condition is true, only then the statements will be executed
otherwise if the condition is false, the control will jump to
statement y, which is the immediate statement outside the
while loop block

amechanism to repeat one or more

From the flowchart, it is


false then the computer will

Programming Tip: .
run into an infinite loop which

crcteateroators is never desirable

nee nsec Yossi Awhile loop is also referred

Seater Sob to as a top-checking loop since

control condition is placed as


the first line of the code. If the control condition evaluates
to false, then the statements enclosed in the loop are never
executed.

For example, look at the following code which prints


first 10 numbers using a while loop.

include <stdio.h>
int main()
{
inti=1; //
while(ic=10) //

initialize loop variable


test the condition
{ // execute the loop statements
printf(" %d", i);
i=i+¢1; // condition updated
}
getch();
return 0;
}
Output

12345678910

Initially i * 1 and is less than 10, ic, the condition


is true, so in the while loop the value of 4 is printed and
the condition is updated so that with every execution of
the loop, the terminating condition becomes approachable.
Let us look at some more programming examples that
illustrate the use of while loop.

Programming Tip: clear that we need to constantly


Iterative statements update the condition of the 20. Write a program to calculate the sum of
first 10
are used to repeat while loop. It is this condition numbers.
the execution of a which determines when the #include <stdio.h>
list of statements, loop will end, The while loop int main()
depending on the will execute as long as the {
value of an integer condition is true. Note if the int i = 1, sum = 0;
expression, condition is never updated and while(ic#10)
the condition never becomes {
‘Statement x
Syntax of While Loop
statement x;
while (condition) Update the
{
statement block; condition expression Condition
statement y;
Statement Block us FALSE
Statement y

The while loop construct

sum = sum + i;
i=i+1; // condition updated
}
printf("\n SUM = Xd", sum);
return 0;
}
Output
SUM = 55

21, Write a program to print 20 horizontal asterisks (*)

#include <stdio.h>
int main()
{
int i=1;
while (ic=20)
{
printf("*");
ite;
}
return 0;

}
Output

Went wae eeneeenennee

22. Write a program to calculate the sum of numbers from


m ton

#include <stdio.h>

int main()

{
int n, m, sum =0;
clrser(
printf("\n Enter the value of =
scanf("Xd", &m);

“5

printf("\n Enter the value of n


scanf("%d", &n);
")3

while(me=n)
{
sum = sum + m;
meme;
}
printf("\n SUM = %d", sum);
return 0;
}
Output
Enter the value of m: 7
Enter the value of n: 11
SUM = 45

23. Write a program to display the largest of S numbers


using ternary operator

#include <stdio.h>
#include <conio.h>

Decision Control and Looping Statements | (217


int main()
{

int i=1, large = -32768, num;

clrser();
while(ic=5)

{
printf("\n Enter the number:
scanf("Xd" num) ;
large = num>large?num: large;
itt;

printf("\n The largest of five numbers

entered is: Xd", large);

return 0;

")

Output

24.

Enter the number : 29


Enter the number : 15
Enter the number : 17
Enter the number : 19
Enter the number : 25
The largest of five numbers entered is: 29

Write a program to read the numbers until <1 is


encountered. Also count the negative, positive, and
zeros entered by the user,

@include <stdio.h>

#include <conio.h>

int main()

{
int num;
int negativese0, positives=0, zeros=0
elrser();

printf("\n Enter -1 to exit.");


printf("\n\n Enter any number: “);
scanf("%d" ,&num) ;

while(num [= -2)
{
if (num>0)
positives++;
else if(num<0)
negatives++;
else
zeroest+;
printf("\n\n Enter any number: ");
scanf("%d" ,&num) ;
}
printf("\n Count of positive numbers entered
= Xd", positives);
printf("\n Count of negative numbers entered
= Xd", negatives);
printf("\n Count of zeros entered =
zeros);
getch();

xa",

218 Computer Fundamentals and Programming in C

return 0;

}
Output

Enter -1 to exit
Enter any number: -12

Enter any number: 108


Enter any number: -24

Enter any number: 99

Enter any number: -23

Enter any number: 101

Enter any number: -1

Count of positive numbers entered = 3


Count of negative numbers entered = 3
Count of zeros entered = 0

25. Write a program to calculate the average of numbers


entered by the user

#include <stdio.h>

int main()
{
int num, sum = 0, count = 0;
float avg;
printf("\n Enter any number. Enter -1 to
STOP: “);

scanf("%d", &num);
while(num t= -1)
Programming Tip: aks
ees sericolon sum = sun + num;
enrecnes print#("\n Enter any
bedak ree apie number. Enter -1 to
STOP; “);
culnonlprni scanf("%d", &num);
. However, }
A diaipenbehats avg = (float)sum/count;
on Stroe as printf("\n SUM = Xd", sum);
Sa ada print#("\n AVERAGE = %.2f",
the program. a
return 0;
}
Output

Enter -1 to exit

Enter any number. Enter -1 to STOP: 23


Enter any number. Enter -1 to STOP: 13
Enter any number. Enter -1 to STOP: 3
Enter any number. Enter -1 to STOP: 53
Enter any number. Enter -1 to STOP: 4
Enter any number. Enter -1 to STOP: 63
Enter any number. Enter -1 to STOP: -23
Enter any number. Enter -1 to STOP: -6
Enter any number. Enter -1 to STOP: -1
SUM = 130

AVERAGE = 16.25
Thus, we see that while loop is very useful for designing
interactive programs in which the number of times the

statements in the loop have to be executed is not known in


advance. The program will execute until the user wants to
stop by entering -1

Now look at the code given below which results in an


infinite loop. The code given below is supposed to calculate
the average of first 10 numbers, but since the condition
never becomes false, the output will not be generated and
the intended task will not be performed.

include <stdio.h>
int main()
{
int i = 0, sum #0;
float avg = 0.0;

while(ic<#10)
{
sum = sum + i;
}
avg = (float) sum/10;
printf("\n The sum of first 10 numbers = Xd",
sum);
printf("\n The average of first 10 numbers «
xf", avg);
return 0;
10.3.2 do-while Loop

The do-while loop is similar to the while loop. The only


difference is that in a do-while loop, the test condition is
evaluted at the end of the loop, Now that the test condition
is evaluted at the end, this clearly means that the body
of the loop gets executed at least one time (even if the
condition is false), Figure 10,7 shows the syntax and
general form of representation of a do-while loop,

Note that the test condition is enclosed in parentheses


and followed by a semicolon, The statements in the
statement block are enclosed within curly brackets, The
curly brackets are optional if there is only one statement in
the body of the do-while loop.

Like the while loop, the do-while loop continues to


execute whilst the condition is true. There is no choice
whether to enter the loop or not because the loop will be
executed at least once irrespective of whether the condition
is true or false. Henee, entry in the loop is automatic
There is only one choice: to continue or to exit. The do-
while loop will continue to execute while the condition
is true and when the condition becomes false, the control
will jump to statement following the do-while loop.

Similar to the while loop, the do-while is an indefinite


loop as the loop can execute until the user wants to stop.
The number of times the loop has to be executed can thus
be determined at the run time. However, unlike the while
loop, the do-while loop is a bottom-checking loop, since
the control expression is placed after the body of the loop,

The major disadvantage of using a do-while loop is


that it always executes at least once, even if the user enters

Syntax of do-while Loop

statement x;
do
{

statement block;
}while (condition);

statement y;

Decision Control and Looping Statements 219

‘Statement x

Statement block

Update the
condition expression
TRUE Condition

FALSE

Statement y

Figure 10.7 do-while construct

some invalid data, One complete execution of the loop


takes place before the first comparison is actually done
However, do-while loops are widely used to print a list of
options for a menu-driven programs, For example, look at
the following code

#include <stdio.h>
int main()
{
int i 1;
do
{
printf(“\n %d", i);
i-=141;
} while(ic10);
return 0;

}
What do you think will be the output? The code will
print numbers from 1 to 10.

26. Write a program to calculate the average of first n

numbers.
#includ tdio.h
Programming Tip: thay Ode,
Do not forget to place {
eainongalberbitha int n, i = 1, sum = 0;
end of the do-while float avg = 0.0;
statement.

printf("\n Enter the


value of n: “);

scanf("%d", &n);

do

sum = sum + i;
izsi+1;
} while(icen);

avg = (float) sum/n;


printf("\n The sum of first Xd numbers = Xd",
n, sum);

printf("\n The average of first Xd numbers «


%.2*", n, avg);

return 0;

Output

Enter the value of n: 18


The sum of first 18 numbers « 171
The average of first 18 numbers = 9.00

27. Write a program using a do-while loop to display the

square and cube of first 7 natural numbers.

#include <stdio.h>
#include <conio.h>
int main()
{
int i, n;
clrscr();
printf("\n Enter the value of n: “);
scanf("%d", &n);

printf("\n
i=1;
do
{
printf("\n | \t ¥d \t |
\t Xd \t | \t Mid \t |", i,
Pier Shy AIDS
while loop for oat
} while(i<en
implementi
pibapsscleah Lahey PRaNER C=
do-«hile loop for i
test loo; ?
post ps. }

220 Computer Fundamentals and Programming in C

Output

Enter the value of n: 5

28. Write a program to list all the leap years from 1900 to
1920.
#include <stdio.h>
#include <conio.h>
int main()

{
int m=1900, n=2100;
clrser();

do

if(((m%4 == 0) && (m%100!=0)))| | (m&400""0))


printf("\n Xd is a leap year",m);

m= ml;
Jwhile(mexn);
return 0;
}
eatyciseirdtyatn Output
you wai
body ofthe loopmust 1904 4s 2 leap year
get executed atleast 198 {5 2 leap year
‘once, then use the 1912 is a leap year
do-uhile loon. 1916 is a leap year
1920 is a leap year

29, Write a program to read a character until a * is


encountered. Also count the number of upper case,
lower case, and numbers entered.
#include <stdio.h>

#include <conio.h>

int main()

{
char ch;
int lowers = 0, uppers = 0, numbers = 0;
clrser();

printf("\n Enter any character: ");


scanf("%e, &ch);

do

if(ch >='A’ BB ch<='Z')


uppers++;

if(ch >='a' && che="z')


lowers++;

if(ch >="0' 8% ch<="9")

numbers++;

fflush(stdin);
/* The function is used to clear the
standard input file. */

printf("\n Enter another character. Enter *


to exit.");
scanf(“%c", &ch.
} while(ch I= '*

printf("\n Total count of lower case


characters entered = Xd", lowers);
printf("\n Total count of upper case
characters entered = Xd", uppers);
printf("\n Total count of numbers entered «
Xd", numbers);

return 0;

Output

Enter any character: 0


Enter another character. Enter * to exit.
Enter another character. Enter * to exit.
Enter another character. Enter * to exit.
Enter another character. Enter * to exit.
Enter another character, Enter * to exit.
Enter another character, Enter * to exit.

sazxonx

Total count of lower case characters entered


=3

Total count of upper case characters entered


=3

Total count of numbers entered = 0

30. Write a program to read the numbers until —1 is

encountered, Also calculate the sum and mean of all


positive numbers entered and the sum and mean of all
negative numbers entered separately

@include <stdio.h>

#include <conio.h>

int main()

{
int num;
int sum_negatives=0, sum_positives
int positives = 0, negatives = 0;
float mean_positives = 0.0, mean_negatives =
0.0;
clrser();

printf("\n Enter -1 to exit");


printf("\n\n Enter any number: “);
scanf("%d" num) ;

do
{

if (num>0)

{
sum_positives += num;
positives++;

else if(num<0)

{
sum_negatives += num;
negatives++;

printf("\n\n Enter any number: *);


scanf("%d",&num) ;
} while(num t= =1);

mean_positives « (float)sum_positives/
positives;

mean_negatives = (float) sum_negatives/


negatives;

printf("\n Sum of all positive numbers


entered = Xd", sum_positives);

printf("\n Mean of all positive numbers


entered = %.2*", mean_positives);

printf("\n Sum of all negative numbers


entered = Xd", sum_negatives);
printf("\n Mean of all negative numbers
entered = %.2#", mean_negatives);
return 0;

Syntax of for Loop

for (initialization; condition;


increment/decrement/update)
{
statement block;

statement y;

Figure 10.8

Decision Control and Looping Statements p21

Output

Enter -1 to exit

Enter any number: 9

Enter any number: 8

Enter any number: 7

Enter any number: -6

Enter any number: -5


Enter any number: -4

Enter any number: -1

Sum of all positive numbers entered = 24


Mean of all positive numbers entered = 8.00
Sum of all negative numbers entered = -15
Mean of all negative numbers entered = -5.00

10.3.3 for Loop

Like the while and do-while loops, the for loop provides
a mechanism to repeat a task until a particular condition is
truc. For loop is usually known as a determinate or definite
loop because the programmer knows exactly how many
times the loop will repeat. The number of times the loop
has to be executed can be determined mathematically by
checking the logic of the loop. The syntax and general
form of a for loop is given in Figure 10.8

When a for loop is used, the loop variable is initialized


only once. With every iteration of the loop, the value of the
loop variable is updated and the condition is checked, If
the condition is true, then the statement block of the loop
is executed, else the statements comprising the statement
block of the for loop are skipped and the control jumps
to the immediate statement following the for loop body.

Initialization
of loop variable
Controling FALSE
condition for
loop variable

TRUE

Statement block

Update the
loop variable

‘Statement y

for loop construct

222 Computer Fundamentals and Programming in C

In the syntax of the for loop, initialization of the


loop variable allows the programmer to give it a value.
Second, the condition specifies that while the conditional
expression is true the loop should continue to repeat
itself. With every iteration, the condition when the loop
would terminate should be approachable. So, with every
iteration, the loop variable must be updated. Updating the
loop variable may include incrementing the loop variable,
decrementing the loop variable or setting it to some other
value like, 4 +=2, where 4 is the loop variable.

Note that every section of the for loop is separated


from the other with a semicolon. It is possible that one
of the sections may be empty, though the semicolons still
have to be there. However, if the condition is empty, it is
evaluated as true and the loop will repeat until something
else stops it

The for loop is widely used to execute a single or a


group of statements a limited number of times. Another
point to consider is that in a for loop, condition is tested
before the statements contained in the body are executed.
So if the condition does not hold true, then the body of the
for loop is not executed

Look at the following code which prints the first 1


numbers using a for loop.

#include <stdio.h>

int main()

{
int i, nj
printf("\n Enter the value of n :");
scanf("%d", &n);

for(detjicenjit+)
printf(“\n Xd", 4);

return 0;
}

In the code, i is the


lane mnrnlng Tie loop variable. Initially, it
to ane the loop is initialized with valuc 1

ch le in the Suppose the user enters 10


ta iplial ek as the value for n. Then the
condition is checked, since the

renathcal odd condition is truc as i is less

than n, the statement in the


for loop is executed and the
value of i is printed. After every iteration, the value of i is
incremented. When i=n, the control jumps to the return
0 statement,

Points to Remember About for Loop

* Ina for loop, any or all the expressions can be omitted.


In case all the expressions are omitted, then there must
be two semicolons in the for statement

* There must be no semicolon after a for statement. If


you do that, then you are sure to get some unexpected
results, Consider the following code.
then the compiler will not generate any error me:
Rather it will treat the statement as a null statement,
Usually such type of null statement is used to generate
time delays. For example, the following code produces no
output and simply delays further processing,

* Multiple initializations must be separated with a

include <stdio.h>
int main()
{
int i;
for (i=0;i<10;i++);
print#(" xd", i);
return 0;

In this code, the loop initializes 1 to 0 and increments

its value. Since a semicolon is placed after the loop, it


means that loop does not contain any statement. So even
if the condition is truc, no statement is executed. The loop
continues till 4 becomes 10 and the moment i#10, the
statement following the for loop is executed and the value
of i (10) is printed on the screen.
When we place a semicolon after the for statement,
ge.

include <stdio.h>

int main()
{
int 4;
for(i=10000; 1>0;1-
printf(" Xd", 4);
return 0;
}

oOmma
operator as shown in the following code segment.

#include <stdio.h>
int main()
{
int i, sum;
for(i=0, sum=0;1<10;i++)
sum «= i;
printf(" Xd", sum);
return 0;

}
If there is no initialization to be done, then the
initialization statement can be skipped by giving only
a semicolon. This is shown in

Programming Tip: the following code.


erated #include <stdio.h>
nip int main()
reeaipeareybiy ft int i=0;
paaaatig talecead for(;i<10;i++)
oe oe fs printf("xd", i);
ashes dati return 0;

avoid it as mi as }

* Multiple conditions in the test expression can be tested


by using logical operators (88 or | |).

* If the loop controlling variable is updated within the


statement block, then the third part can be skipped. This
is shown in the code given below

#include <stdio.h>
int main()
{
int i=0;
for(;1<10;)
{
printf(" Xd", 4);
i\i+;
}

return 0;

* Multiple statements can be included in the third part


of the for statement by using the comma operator. For
example, the for statement given below is valid in C.

for(inO, jwl0j;icj; ist, j--)

* The controlling variable can also be incremented


decremented by values other than 1. This is shown in the
code below which prints all odd numbers from 1 to 10.

#include <stdio.h>
int main()
{
int 4;
for (il; i<@l10;ie=2)
printf(" Xd", 4);
return 0;
}
* If the for loop contains nothing but two semicolons,

that is no initialization, condition testing, and updating


of the loop control variable

Programming Tip: then the for loop may become


Although placing an an infinite loop if no stopping
arithmeticexpression = condition is specified in the
in initialization and body of the loop. For example,
updating section the following code will
of the for loop is infinitely print C Program-
permissible, try to ming on the computer screen
avoid them as they
may cause some #include <stdio.h>
round-off and/or int main()
truncation errors,
for(;5)
printf(" C Programming”);
return 0;
}

* Never use a floating point variable as the loop control


variable. This is because floating point values are just
approximations and therefore may result in imprecise
values and thus inaccurate test for termination. For
example, the following code will result in an infinite
loop because of inaccuracies of floating point numbers.

Decision Control and Looping Statements 223

#include <stdio.h>
int main()
{
float i;
for (i=100;i>=10;)
{
printf(" Xf", i);
i = (float)i/10;
}
return 0;

Selecting an appropriate loop Loops can be entry-


controlled (also known as pre-test) or exit-controlled (also
known as post-test), While in an entry-controlled loop,
condition is tested before the loop starts, an exit-controlled
loop, on the other hand, tests the condition after the loop
is executed, If the condition is not met in entry-controlled
loop, then the loop will never execute, However, in case of
post-test, the body of the loop is executed unconditionally
for the first time.

If your requirement is to have a pre-test loop, then


choose cither for loop or while loop, In case, you need to
have # post-test loop then choose a do-while loop.

Look at Table 10.2 which shows a comparison between


4 pre-test loop and a post-test loop.

[Table 10.2 } Comparison of pre-test and post-test loops


Feature Pre-test loop | Post-test loop
| Initialization 1 1
Number of tests Nel N
| Statements executed N N
Loop control variable N N
update

Minimum iterations 0 '

When we know in advance the number of times the


loop should be executed, we use a counter-controlled loop.
The counter is a variable that must be initialized, tested,
and updated for performing the loop operations. Such a
counter-controlled loop in which the counter is assigned
@ constant or a value is also known as a definite repetition
loop

When we do not know in advance the number of times


the loop will be executed, we use a sentinel-controlled
loop. In such a loop, a special value called the sentinel
value is used to change the loop control expression from
truc to false. For example, when data is read from the
user, the user may be notified that when they want the
execution to stop, they may enter -1. This value is called
a sentinel value. A sentinel-controlled loop is often useful
for indefinite repetition loops.

If your requirement is to have a counter-controlled


loop, then choose for loop, else if you need to have a
sentinel-controlled loop, then go for either a while loop
et Computer Fundamentals and Programming in C

“OF a do-while loop. Although a sentinel-controlled loop


can be implemented using for loop. while, and do-while
loops offer better option.

NESTED LOOPS

C allows its users to have nested loops, i.c., loops that can
be placed inside other loops. Although this feature will
work with any loop such as while, do-while, and for,
it is most commonly used with the for loop, because this
is easiest to control. A for loop can be used to control the
number of times that a particular set of statements will be
executed. Another outer loop could be used to control the
number of times that a whole loop is repeated.

In C, loops can be nested to any desired level. However,


loops should be properly indented so that a reader can
easily determine which statements are contained within
cach for statement. To sec the benefit of nesting loops,
we will see some programs that exhibit the use of nested
loops.

31. Write a program to print the following pattern.

Pass 1- 12345
Pass 2-12345
Pass 3- 12345
Pass 4- 12345
Pass 5-12345

tinclude <stdio.h>
int main()
{
int 4, J;
for(i=ljiceS; ive)
|
printf("\n Pass %d- “,1i);
for(j=1;j<55 j++)
printf(" %d", 3)5
}
return 0;

}
32. Write a program to print the following pattem.

ARE
eee
Pere eer eer
nae
kee thee

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

}
return 0;

}
33. Write a program to print the following pattern.

.
7
tee
tee
sewer

#include <stdio.h>
int main()
{
int i, Jj;
for(i=l;i<=S;it+)
{
printf("\n");
for(j=15j<=i; j++)
printf("*");
}
return 0;

34. Write a program to print the following pattern,

12
123
1234
12345

include <stdio.h>
int main()

int i, jj;
for(i=ljic#S;i++)
{
printf("\n");
for(j=1;j<wi;jr+)
printf("%d", 3)
}
return 0;

}
35. Write a program to print the following pattern,

22
333
coal
55555

#include <stdio.h>
int main()
{
int i, j;
for(i=1;ic=5;i++)
{
printf("\n");
for(j=1;j<=i; j++)

printf(*X%d", i);
}
return 0;

36, Write a program to print the following pattern


0
12
345
6789
#include <stdio.h>
int main()
{
int i, j, count=0;
for(iwl;ic=d; ive)
{
printf("\n");
for(jwljjcwizir+)
printf("Xd", counte+);
}
return 0;

37. Write a program to print the following pattem


A
AB
ABC
ABCD
ABCDE
ABCDEF

#include <stdio.h>
int main()
{
char i, j;
for(in65; ic#70; i++)
{
printf(“\n");
for(j=65;J<Wijje+)
printf("%e", 3);
}
return 0;

38. Write a program to print the following pattern.

#include <stdio.h>
tdefine N 5
int main()

{
int i, j, ki
for(i=l;i<=Njit+)

Decision Control and Looping Statements 225


{
for(k=N;k>=i;
printf(" “
for(j=1; j<=i; j++)

printf("xd", j);
printf("\n");
}
return 0;

39. Write a program to print the following pattern

1
121
$2321
1234321
2345432
#include <stdio.h>
Sdefine NS

int main()
{
int 4, J; K,. 23
for(islj;iceN;ir+)
{
for(keN;k>=i;k--)
printf(" “);
for (jel; jcwi; jer)
printf("%d", 3);
for(1=j-2;1>0;1--)
printf("%d", 1);
printf("\n");
}
return 0;

40. Write a program to print the following pattern,

#include <stdio.h>
define N 5
int main()
{
int i, j, k, counts5, c;
for(isl;ic=Njit+)
{
for(k=1;k<=count;k++)
printf(" “);
for(j=1;j<=i; j++)
printf("X2d", i);
printf("\n");
ons
}
return 0;

226 Computer Fundamentals and Programming in C


41. Write a program to print the multiplication table of n,
where n is entered by the user.
#include <stdio.h>
int main()

{
int n, i;
printf("\n Enter any number:
scanf("Xd", &n);

printf("\n Multiplication table of Xd”


Printh(“\n *eeeeecesercesececouses®);
for(in0;ic#20; i+)

printf("\n %d X Xd = Xd", n, i, (mn * 4));


return 0;

}
Output

Enter any number: 2


Multiplication table of 2
2X0#0
2X1"2
2X 20 = 40
42. Write a program using for loop to print all the numbers
from m to n, thereby classifying them as even or odd
#include <stdio.h>
#include <conio.h>
int main()
{
int i, m, n;
clrser();
printf("\n Enter the value of m: “);
scanf("%d", &m);
printf(“\n Enter the value n: “);
scanf("Xd", &n);
for(iwm;icwn; ire)

{
if(i%2 «= 0)
printf("\n Xd is even™,i);
else
printf("\n Xd is odd", i);
}
return 0;
}
Output

Enter the value of m: 5


Enter the value of n: 7
5 is odd

6 is even

7 is odd

43, Write a program using for loop to calculate the


average of first 1 natural numbers.
#include <stdio.h>
#include <conio.h>

int main()

{
int n, i, sum =0;
float avg = 0.0;
clrser();
printf("\n Enter the value of n: “);
scanf("Xd", &n);
for(isl;icen;ite)

sum = sum + i;

avg = (float) sum/n;


printf("\n The sum of first n natural numbers
= Xd", sum);
printf("\n The average of first n natural
numbers = %.2*", avg);
return 0;

Output

Enter the value of n: 10


The sum of first n natural numbers = 55
The average of first n natural numbers = 5.50
44, Write a program using for loop to calculate factorial
of a number,

#include <stdio.h>
include <conio.h>
int main()
{
int fact = 1, num;
clrser();
printf("\n Enter the number: “)
scanf("%d" ,&num) ;

if(mum == 0)
fact = 1;

else

for(int i=1; ic=num;it++)


fact = fact * i;
}
printf("\n Factorial of %d is: Xd", num,
fact);
return 0;

}
Output

Enter the number: 5


Factorial of 5 is: 120

45. Write a program to classify a given number as prime


or composite
#include <stdio.h>
@include <conio.h>
int main()
{
int flag = 0, i, num;
clrscr();
printf("\n Enter any number: “);

scanf("%d", &num);
for(i=2; icnum/2;i++)
{
if(numXi == 0)
{
flag =1;
break;

}
}
if(flag <= 1)
printf("\n %d is a composite number”, num);
else
printf("\n %d is a prime number", num);
return 0;
}
Output

Enter the number: 5


5 is a prime number

46. Write a program using do-while loop to read the


numbers until —1 is encountered. Also count the
number of prime numbers and composite numbers
entered by the user

#include <stdio.h>

#include <conio.h>

int main()

{
int num, 4;
int primes«O, composites#0, flag~O;
clrser();
printf("\n Enter -1 to exit");
printf("\n\n Enter any number:");
scanf("%d" ,&num);
do

for (1=2;i<=num/2; i++)


{
if (numXi==0)
{
flage1;
break;
}
}
if(flage=0)
primes++
else
composites++;

flage0;

printf("\n\n Enter any number: ");

scanf("%d", &num) ;

} while(num |= -1);

printf("\n Count of prime numbers entered =


%d", primes);

printf("\n Count of composite numbers entered


= Xd", composites);

Decision Control and Looping Statements 227

return 0;
}

Output

Enter -1 to exit

Enter any number: 5

Enter any number: 10

Enter any number: 7

Enter any number: -1

Count of prime numbers entered = 2


Count of composite numbers entered = 1

47. Write a program to calculate pow(xy1) ic., to calculate x"

#include <stdio.h>
#include <conio.h>
#include <math.h>
int main()
{
int i, num, n;
long int result 1;
clrser();
printf("\n Enter the number: ");
scanf("Xd", Snum);
printf("\n Till which power to
calculate: *);
scanf("Xd", &n);
for(iwl;icenjire)
result = result * num;
printf("\n pow(Xd, Xd) = %ld", num, n,
result);
return 0;

Output

Enter the number: 2


Till which power to calculate: 5

pow(2, 5) = 32

48. Write 4 program to print the reverse of a number,

#include <stdio.h>
#include <conio.h>

int main()
{
int num, temp;
clrser();

printf("\n Enter the number: ");


scanf("Xd", &num) ;

printf("\n The reversed number is: “);


while(num != 0)

temp = num&10;
printf ("%d", temp) ;
num = num/10;

return 0;

228 Computer Fundamentals and Programming in C

Output

Enter the number: 123


The reversed number is: 321
49, Write a program to enter a number and then calculate

the sum of its digits,

#include <stdio.h>

#include <conio.h>

int main()

{
int num, temp, sumofdigits «
clrscr();
printf("\n Enter the number: ");
scanf("%d", &num);

while(num |= 0)

temp = numX10;
sumofdigits += temp;
num = num/10;
}
printf("\n The sum of digits = %d",
sumofdigits);
return 0;
}
Output
Enter the number: 123
The sum of digits » 6

50. Write a program to enter a decimal number. Calculate

and display the binary equivalent of this number

#include <stdio.h>
#include <conio.h>
#include <math.h>

int main()

{
int decimal_num, remainder, binary_num = 0,
i= 0;
clrscr();
printf("\n Enter the decimal number:
scanf("%d", &decimal_num);
while(decimal_num != 0)

remainder = decimal_numX2;
binary_num += remainder*pow(10,i);
decimal_num = decimal_num/2;
itt;
}
printf("\n The binary equivalent = Xd",
binary_num);
return 0;

}
Output

Enter the decimal number: 7


The binary equivalent = 111

$1. Write a program to enter a decimal number. Calculate


and display the octal equivalent of this number

include <stdio.h>
#include <conio.h>
@include <math.h>

int main()
{
int decimal_num, remainder, octal_num = 0,
i= 0;
cleser();
printf("\n Enter the decimal number:
scanf("%d", &decimal_num);
while(decimal num |= 0)
{
remainder = decimal_num%8;
octal_num += remainder*pow(10,i);
decimal_num = decimal_num/8;
ie;
}
printf("\n The octal equivalent = Xd", octal_
num);
return 0;

}
Output

Enter the decimal number: 18


The octal equivalent = 22

$2. Write a program to enter a binary number, Calculate


and display the decimal equivalent of this number,

#include <stdio.h>
#include <conio.h>
#include <math.h>

int main()
{
int decimal _num = 0, remainder, binary_num,
i= 0;
clrser();
printf("\n Enter the binary number: ");
scanf("Xd", &binary_num);
while(binary_num |= 0)
{
remainder = binary_numX10;
decimal_num += remainder*pow(2,i);
binary_num = binary_num/10;
itt;
}
printf(“\n The decimal equivalent = Xd",
decimal_num);
return 0;

}
Output

Enter the binary number : 111


The decimal equivalent = 7

$3. Write a program to enter an octal number. Calculate


and display the decimal equivalent of this number.

#include <stdio.h>
#include <conio.h>
#include <math.h>

int main()
{
int decimal_num= 0, remainder, octal_num,
i 0;
clrser();
printf("\n Enter the octal number:
scanf("%d", &octal_num);
while(octal_num != 0)
{
remainder = octal_numX10;
decimal_num ¢= remainder*pow(8, i);
octal_num = octal_num/10;

ive
}

printf("\n The decimal equivalent = Xd",


decimal_num) ;

return 0;

}
Output

Enter the octal number; 22


The decimal equivalent = 18

$4, Write a program to enter a hexadecimal number. Calculate


and display the decimal equivalent of this number.

ttinclude <stdio.h>
#include <conio.h>
#include <math.h>

int main()
{
int decimal_num= 0, remainder, hex_num, i
20;
clrser();
printf("\n Enter the hexadecimal number:
scanf("%d", &hex_num);
while(hex_num != 0)
{

remainder = hex_num%10;
decimal_num += remainder*pow(16,i);
hex_num = hex_num/10;
int
}
printf("\n The decimal equivalent = Xd",
decimal_num);
return 0;
}
Output
Enter the hexadecimal number: 39
The decimal equivalent = 57

Decision Control and Looping Statements 229

$5. Write a program to calculate GCD of two numbers.


#include <stdio.h>
#include <conio.h>
int main()
{
int numl, num2, temp;
int dividend, divisor, remainder;
clrscr();

printf("\n Enter the first number: ");


scanf("X%d", &num1);

printf("\n Enter the second number: ");


scanf("Xd", &num2);

if (numi>num2)
{
dividend = num1;
divisor = num2;
}
else
{
dividend = num2;
divisor = numl;

while(divisor)
{
remainder = dividend%divisor;
dividend = divisor;
divisor = remainder;
F
printf("\n GCD of Xd and Xd is = Xd", numi,
num2, dividend) ;
return 0;

}
Output

Enter the first number: 64


Enter the second number: 14
GCD of 64 and 14 is = 2

I
56. Write a program to sum the series 1+ +2 +--+

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

{
int n, i;
float sum=0.0, a;
clrscr();
printf("\n Enter the value of n:
scanf("%d", &n);
for(i=l;ic=n;ir+)
{ a=(float)1/i;
sum = sum +3;
}
printf("\n The sum of series 1/1 + 1/2 + ....
+ 1/%d = %.2f",n,sum);

230 Computer Fundamentals and Programming in C

return 0; 127 3
} 59. Write a program to sum the series ~ + eel mates
Oui #include <stdio.h> l= 3
so #include <conio.h>
Enter the value of n: 5 include <math.h>
The sum of series 1/1 + 1/2+.... + 1/5 = int main()
2.28 {

int n, NUM, i;

float sum=0.0;

clrscr();

printf("\n Enter the value of n: ");

§7 Write a program to sum the series

#include <stdio.h>
#include ¢math b> scanf("%d", &n);
#include <conio.h> forfinasicanjdes)
int main() { - -
{ NUM = pow(i,i);

one Aad sum += (float)NUM/i;


float sume0.0, a; }
clrser(); m %
print#(*\n Enter the value of n: *); spss 1/1 + 4/2 + 27/3 + .... = %.2F",
scanf("%d", &n); rE A
for(iwl;icen;it+)
{ a = (float)1/pow(i,2); }
sum = sum +a; Output
} Enter the value of n:5
printf("\n The sum of series 1/17 + 1/ 2? + —. 1/1 + 4/2 + 27/3 + = 701.00
1/xd? = %.2#",n, sum);
return 0; 60. Write a program to calculate sum of cubes of first n
} numbers,
Output #include <stdio.h>
: Programming Tip: include <conio.h>
Enter the value of n: 5 Itis a logical error to SicAndaeanhhhy

The sum of series 1/1? + 1/ 2? + .. 1/5? = 1.46 skip the updating of


loop contro! variable int main()

‘5
$8, Write « program to sum the series 44 2...4— in the while/do- {
#include <stdio.h> ee peeeta eop ete int i, nj
; an update statement, int term, sum = 0;
#include <conio.h> thetoso wal lees ;
int main t loop will become elrser();
{ Oo an infinite loop. printf("\n Enter the
int n, value of n: ");
float sum=0.0, a; Sean &n);
clrser(); 2 for(iel;icenjire)
printf("\n Enter the value of n: “); ‘ ,
scanf("%d", &n); cate Se aeas
for(isl;icenj;it+) sum += term;
{ a= (float) i/(i+1); } m , ’ , -
sum = sum 4a; dub ig Vee Ve... = BA", sum);
) return 0;
printf("\n The sum of series 1/2 + 2/3 + }
seeeKd/Md = XF",n,n¢1, sum); Output
petury 0} Enter the value of n:5
} P+ 243+... = 225
oO 5
we 61. Write a program to calculate sum of squares of first 1
Enter the value of n :5 even numbers.
The sum of series 1/2 + 2/3 + ....5/6 = eases EGA KS
2. 6B14E s

#include <conio.h>

#include <math.h>
int main()
{
int i, nj;
int term, sum = 0;
clrser();
printf("\n Enter the value of n: ");
scanf("%d", &n);
for(iel;ic=n; i+)
{
if(ik2 == 0)
{ term = pow(i,2);
sum += term;
}
}
printf("\n 2? + 4? + 6? +... = Xd", sum);
return 0;

}
Output

Enter the value of n: 5


2+ 474 68+... = 20

62. Write a program to find whether the given number is


an Armstrong number or not

#include <stdio.h>
#include <conio.h>
#include <math.h>
int main()
{
int num, sum=0, r, nj
clrser();
printf("\n Enter the number: “);
scanf("%d", &num);
nenum;
while(n>0)
{
renkl0;
sum += pow(r,3);
nen/10;
}
if (sume=num)
printf("\n Xd is an Armstrong number", num);
else
printf("\n Xd is not an Armstrong number”,
num) 5
return 0;

}
Output
Enter the number : 432

432 is not an armstrong number

63. Write a program using for loop to calculate the value


of an investment, given the initial value of investment

Decision Control and Looping Statements 231

and the annual interest. Calculate the value Of


investment over a period of time.

#include <stdio.h>
int main()
{
double initVal, futureVal, ROI;
int yrs, i;
printf("\n Enter the investment value: “);
scanf("%1f", &initval);
printf("\n Enter the rate of interest: “);
scanf("%1f", &ROI);
print€("\n Enter the number of years for
which investment has to be done: “);
scanf("Xd", Syrs);
futureVal=initVal;
printf("\n YEAR \t\t VALUE");
printf("\n "5
for(iwl;iceyrs;ie+)
{
futureVal = futureVal * (1 + ROI/100.0);
printf("\n %d \t X1f", 4, futureVal);
}
return 0;

}
Output

Enter the investment value: 20000

Enter the rate of interest: 12

Enter the number of years for which investment


has to be done: 5

YEAR VALUE
22400.00
25088 .00
28098 .56
31470.38
35246.83

wawne

64. Write a program to generate calendar of a month given


the start day of the week and the number of days in that
month.

#include <stdio.h>
int main()
{
int i, j, startDay, num_of_days;
printf("\n Enter the starting day of the
week (1 to 7): ");
scanf("kd", &startOay);
printf("\n Enter the number of days in that
month: ");
scanf("%d", &num_of_days);
printf(" Sun Mon Tue Wed Thurs Fri Sat\n");
printf ("\n
for(i=0;icstartDay-

232 Computer Fundamentals and Programming in C


printf(" “);
for(j=1; j<=num_of_days;j++)
{
if(i>6)
{
printf("\n");
i=l;
}
else
i++;
print#("%2d
}
return 0;

}
Output

", 3)

Enter the starting day of the week (1 to 7): 5


Enter the number of days in that month : 31
Sun Mon Tue Wed Thurs Fri Sat

1234567

TED BREAK AND CONTINUE STATEMENTS


In this section, we discuss break and continue statements.

10.5.1 break Statement

In C, the break statement is used to terminate the execution


of the nearest enclosing loop in which it appears. We have
already seen its usage in the

Programming Tip: switch statement. The break


The break statement statement is widely used with
is used to terminate for loop, while loop, and
the execution of the do-while loop. When the
nearest enclosing compiler encounters a break
loop in which it statement, the control passes
appears, to the statement that follows

the loop in which the break


statement appears. Its syntax is quite simple, just type
keyword break followed with a semicolon.

break;

In switch statement if the break statement is missing


then every case from the matched case label till the end
of the switch, including the default, is executed. This
example given below shows the manner in which break
statement is used to terminate the statement in which it is
embedded.

#include <stdio.h>
int main()
{
int i = 1;
while(ic=10)
{
if (i==5)
break;

while(...) do
{{

if (condition) iF(condition)
break ; break ;

Jwhile¢ ..

Transfers control
out of the do-while

Transfers control out


of the loop while

loop
for(...) for(...)
{{
iF (condition)
break ;

Transfers control out


of the for loop

}
Transfers control out
of inner for loop

Figure 10.9 break statement

printf("\n Xd", 4);


i-i+1;
}

return 0;

Note that the code is meant to print first 10 numbers


using a while loop, but it will actually print only numbers
from | to 4. As soon as i becomes equal to 5, the break
statement is executed and the control jumps to the
statement following the while loop.

Hence, the break statement is used to exit a loop from


any point within its body, bypassing its normal termination
expression, When the break statement is encountered
inside a loop, the loop is immediately terminated, and
program control is passed to the next statement following
the loop. Figure 10,9 shows the transfer of control when
the break statement is encountered.

10.5.2 continue Statement

Like the break statement, the

Ueravenminegs continue statement is used


When the compiler in the body of a loop. When
ponctseardahionits: the compiler encounters a
oe ek continue statement then
joon are: nad tak the rest of the statements in

Fe mF the loop are yekease and the


control is unconditionally control is unconditionally
iteenbieskaainsg? transferred to the loop-
the cleonaha continuation portion of

the nearest enclosing loop.

lis syntax is quite simple, just type keyword continue


followed with a semicolon.

continue;

Again like the break statement, the continue statement


cannot be used without an enclosing for, while, ordo-while
statement, When the continue statement is encountered in
the while and do-while loops, the control is transferred
to the code that tests the controlling expression. However,
if placed within a for loop, the continue statement causes
a branch to the code that updates the loop variable. For
example, look at the following code.

include <stdio.h>

int main()

int i;

for(iwl; ic# 10; i++)

if (ie=5)
continue;
printf("\t Xd", 4);
}
return 0;
}

The code given here is meant to print numbers from 1 to


10. But as soon as i becomes

Programming Tip: equal to 5, the continue


As far as possible, statement is encountered,
try not to use so rest of the statements in
goto, break, and the for loop are skipped

continue statements = and the control passes to the


as they violate the expression that increments the
rules of structured value of 4. The output of this
programming. program would thus be

22RSHaA? FF

(Note that there is no $ in the series. It could not be printed,


as continue causes skipping of the statement that printed
the value of 4 on screen).

Figure 10.10 illustrates the use of continue statement


in loops.

Hence, we conclude that the continue statement is


somewhat the opposite of the break statement. It forees
the next iteration of the loop to take place, skipping
any code in between itself and the test condition of the
loop. The continue statement is usually used to restart
a statement sequence when an error occurs, Look at the
program code given below that demonstrates the use of
break and continue statements.

65, Write a program to calculate square root of a number.

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

int num;

Decision Control and Looping Statements 233

Transfers control
to the condition
expression of the
while loop

for(...)
{

if (condition)
continue ;

Transfers control
to the condition
expression of the
for loop

Figure 10.10

do
{

do

if (condition)
continue ;

}while( Pere
Transfers control
to the condition
expression of the
do-while loop

for(:
{

iF(condition)
continue;

Transfers control
to the condition
expression of the
inner for loop

continue statement

printf("\n Enter any number. Enter 999 to

stop: ");

scanf("Xd", Shum);
if(num == 999)

break; // quits the loop

if (num < 0)
{

printf(“\n Square root of negative numbers is

not defined");

continue; // skips the following statements

printf(“\n The square root of Xd is Xf", num,

sqrt(num));
Jwhile(1);
return 0;

}
goto STATEMENT

The goto statement is used to transfer control to a


specified label. However, the label must reside in the
same function and can appear only before one statement in
the same function. The syntax of goto statement is shown
in Figure 10.11

234 Computer Fundamentals and Programming in C

goto Label

goto Label
Backward jump

Figure 10.11 goto statement

Here, label is an identifier that specifics the place


where the branch is to be made, Label can be any valid
variable name that is followed by a colon (;). The label
is placed immediately before the statement where the
control has to be transferred.

The label can be placed anywhere in the program


cither before or after the goto statement. Whenever the
goto statement is encountered the control is immediately
transferred to the staterm following the label.
Therefore, goto statement breaks the normal sequential
execution of the program. If the Label is placed after the
goto statement, then it is called a forward jump and in
case it is located before the goto statement, it is said to be
a backward jump

The goto statement is often combined with the if


statement to cause a conditional transfer of control.

IF condition THEN goto Label

In this book, we will not use the goto statement because


computer scientists usually avoid this statement in favour
of the ‘structured programming’ paradigm. Some scientists
think that the goto statement should be abolished from
higher-level languages because they complicate the task
of analysing and verifying the correctness of programs
(particularly those involving loops).

Moreover, structured program theory proves that the


availability of the goto statement is not necessary to
write programs, as combination of sequence, selection,

and repetition constructs is

Programming Tip: sufficient to perform any


Follow proper computation, The code given
indentation for better below demonstrates the use of
clarity, readability, a goto statement. The program
and understanding of the sum of all
the loops. positive numbers entered by

the user.
#include <stdio.h>
int main()

int num, sum=0;

read: // label for goto statement

printf("\n Enter the number. Enter 999 to end:


or)

scanf(“Xd", &num);

if (num t= 999)

{
if(num < 0)
goto read; // jump to label- read
sum += num;
goto read; // jump to label- read
}

printf(“\n Sum of the numbers entered by the


user is = Xd", sum);
return 0;

Conclusion

* Itis not necessary to use goto statement as it can always

be eliminated by rearranging the code.

Using the goto statement violates the rules of structured

programming.

* It is a good programming practice to use break,


continue, and return statements in preference to goto
whenever possible.

* Goto statements make the program code complicated


and render the program unreadable

One must avoid the use of break, continue, and goto


statements as much as possible as they are techniques
used in unstructured programming.

In structured programming, you must prefer to use


if and if-else constructs to avoid such statements. For
example, look at the following code which calculates the
sum of numbers entered by the user. The first version u:
the break statement. The second version replaces break
by if-else construct

// Uses break statement


#include <stdio.h>

int main()
{
int num, sum=0;
while(1)
{
printf("\n Enter any number. Enter -1 to
stop: ");
scanf("%d", &num);
if (num==-1)
break; // quit the loop
sume=num;
}
printf("\n SUM = %d", sum);
return 0;

}
/* Same program without using break
statement */
#include <stdio.h>
int main()
{
int num, sum=0, flag=1;
// flag will be used to exit from the loop
while(flag-=1) // loop control variable
{
printf("\n Enter any number. Enter -1 to
stop: ");
scanf("Xd", &num);
if(num!=-1)
sum+enum;
else
flag-0; // to quit the loop
}
printf("\n SUM = Xd", sum);
return 0;

Now Iet us sce how we can climinate continue


statement from our programs. Let us first write a program
that calculates the average of all non-zero numbers entered
by the user using the continue statement. The second
program will do the same job but without using continue.

#include <stdio.h>

int main()

int num, sums0, flage1, count=0;


float avg;

// flag will be used to exit from the loop

while(flage*1)

printf("\n Enter any number. Enter -1 to


stop:

scanf("%d", &num);

if (nume=0)

continue; // skip the following statements


if (num! =-1)
{

POINTS TO REMEMBER

« C supports conditional type branching and


unconditional type branching. The conditional
branching statements help to jump from one part of
the program to another depending on whether a
particular condition is satisfied or not.

* With nesting of if-else statements, we often


encounter a problem known as dangling else problem.
This problem is created when there is no matching
else for every if statement. In such cases, C always

Decision Control and Looping Statements 235


Sum+=num;
count++;
}
else
flag=0;

// set loop control variable to jump out of


loop
}
printf("\n SUM = Xd", sum);
avg = (float) sum/count;
printf("\n Average = Xf", avg);
return 0;
}
// Same program without using continue
statement
#include <stdio.h>
int main()
{
int num, sum=0, flage1, count«0;
float avg;
// flag will be used to exit from the loop
while(flage=1)
{
printf("\n Enter any number. Enter -1 to stop:
")3
scanf(“X%d", &num);
if (num! #0)
{
if(num!=-1)
{
sum+«num;
count++
}
else
flag*0;
}
}
printf("\n SUM = Xd", sum);
avg = (float) sum/count;
printf("\n Average = Xf", avg);
return 0;

pairsan else statement with the most recent unpaired


if statement in the current block.

Switch case statements are often used as an


alternative to long if statements that compare a
variable to several integral values. Switch statements
are also used to handle the input given by a user,
Default is a case that is executed when the value of
the variable does not match with any of the values of
Case statements.

Computer Fundamentals and Programming in C


* Iterative statements are used to repeat the execution
of a list of statements, depending on the value of an
integer expression

The while/do-while/for loops provide a mechanism


to repeat one or more statements while a particular
condition is true. In the do-while loop, the test
condition is tested at the end of the loop while in case
of for and while loops the test condition is tested
before entering the loop.

GLOSSARY

Conditional branching Conditional branching statements


are used to jump from one part of the program to another de-
pending on whether a particular condition is satisfied or not.
Continue statement When the compiler encounters a
continue statement then the rest of the statements in
the loop are skipped and the control is unconditionally
transferred to the loop-continuation portion of the nearest
enclosing loop.

Dangling else problem Problem encountered with nesting


of if-else statements which is created when there is no
matching else for every if statement.

do-while loop A form of iterative statement in which the


test condition Is evaluated at the end of the loop.

for loop The mechanism used to repeat a task until a


particular condition is true. for loop is usually known as
a determinate or definite loop because the programmer
knows exactly how many times the loop will repeat.

Goto statement It is used to transfer control to a specified


label.

236

* The break statement is used to terminate the execution


of the nearest enclosing loop in which it appears.

* The continue statement is used to transfer control to


the loop-continuation part of the nearest enclosing
loop.

* The goto statement is used to transfer control to a


specified label. However, the label must reside in the
same function and can appear before only one
statement in the same function.

If statement Simplest form of decision control statement


that is frequently used in decision-making.

If-else-if statement Decision control statement that


works in the same way as a normal if statement. It is also
known as nested if construct

If-else statement Decision control statement in which


first the test expression is evaluated. If the expression
is true, if block is executed and else block is skipped.
Otherwise, if the expression is false, else block is executed
and if block is ignored.

Iterative statement Statement used to repeat the


execution of a list of statements, depending on the value
of an integer expression,

Nested loop Loops placed inside other loops.

Switch case statement A switch case statement Is a


multi-way decision statement that Is a simplified version
of an if-else block that evaluates only one variable.
while loop The mechanism used to repeat one or more
statements while a particular condition is true.

EXERCISES

Fill in the Blanks

1, Dangling else problem occurs when

2. The switch control expression must be of


type.

3. Ina do-while loop, if the body of the loop is executed n


times, the test condition is evaluated _ times.

4, The statement is used to skip statements


in a loop.
5. Aloop that always satisfies the test condition is known as
a loop.

6. In a counter-controlled loop, __
is used to count the number of times the loop will
execute.

7 statements help to jump from one part of


the program to another depending on whether a

particular condition is satisfied or not.

8 __ statements are used to repeat the

execution of a list of statements


9. In

is only a choice to continue it further or not.

_. variable

_ loop, the entry is automatic and there

10. When we do not know in advance the number of times


the loop will be executed, we use a loop.

11. The _ ___statement is used to transfer control


to a specified label

12. statement violates the rules of structured


programming,

Multiple-choice Questions

1. Which type of statement helps to jump from one part of


the program to another depending on whether a
particular condition is satisfied or not?
(a) Conditional branching (b) Loops
(c) Iterative (d) None of these

2, Astatement block consists of how many statements?


(a) 0 {b) 1
(c) n (d) None of these

3. Dangling else problem can arise in which of the following


statement(s)?
(a) Conditional branching (b) Loops
(c) Iterative {d) None of these

4. Which among the following is a multi-way decision


statement?

(a) if-else (b) if-else-if


(c) switch (d) do-while loop
5. Case labels must end with which token?

(a), (b)

(c) ; (d) /

6. The default label can be placed at which position in the


switch statement?

(a) Beginning {b) End


(c) Middle (d) Anywhere
7, The statements in the statement block are encapsulated
withina __?
(a) () (b) 0)
() 0) (d) >

8. Which statement is used to terminate the execution of


the nearest enclosing loop in which it appears?

(a) break (b) continue


(c) default (d) case

9, When the statement is encountered then the


rest of the statements in the loop are skipped.
(a) break (b) continue
(c) default ({d) case
State True or False
1, Decision control statements are used to repeat the
execution of a list of statements.
2. The expression in a selection statement can have no side
effects.
3. An expression in an if statement must be enclosed
within parentheses.

Decision Control and Looping Statements 237


No two case labels can have the same value.
5. The case labelled constant can be a constant or a
variable.
6, The if-else statement requires integral values in its
expressions.
7. There can be only one default case in the switch-case
statement
8. The do-while loop checks the test expression and then
executes the statements placed within its body.
9. In awhile loop, if the body is executed n times, then the
test expression Is executed (n + 1) times.
10. The number of times the loop control variable is updated
is equal to the number of times the loop iterates.
11. In the for loop, the value of the loop control variable
must be less than that of its ending value.
12. It is necessary to have initialization, testing, and updating
expressions within the for statement
13. In a pre-test loop, the test condition is checked after the
body of the loop.
14, Post-test loops get executed at least for one time.
15. in awhile loop, the loop control variable is initialized in
the body of the loop.
16. The loop control variable may be updated before or after
the loop iterates
17. Counter-controlled loop must be designed as pre-test
loops
18. The do-while loop Is a post-test loop,
19. The for loop and while loop are pre-test loops.
20. Every case label must evaluate to a unique constant
expression value
21. Two case labels may have the same set of actions
associated with them.
22. The default label can be placed anywhere in the switch
statement.
23. C does not permit nested switch statements.
24. When we place a semicolon after the for statement, the
compiler will generate an error message

Review Questions

1. What are decision control statements? Explain in detail

2. Compare the use of if-else construct with that of


conditional operator

3. Explain the importance of a switch case statement. In


which situations is a switch case desirable? Also give its
limitations.

4. How is comma operator useful in a for loop? Explain


with the help of relevant examples.

5. Write a short note on goto statement. As a programmer


would you prefer to use this statement? Justify your
answer.
6. With the help of an example explain the dangling if-
else problem.

7. Why floating point numbers should not be used for


equality in expressions?

238
8.

9.
10
11

12.

13.
14,

15

16.

17.

18.
19.

‘Computer Fundamentals and Programming in C

Explain the usefulness of default statement in switch


case statement.

Give the points of similarity and differences between a


while loop and a do-while loop.

Distinguish between the break and the continue


statements.

Write a short note on iterative statements that C


language supports.

Enter two integers as dividend and divisor. If the divisor


is greater than zero then divide the dividend by the
divisor, Assign their result to an integer variable rem and
their quotient to a floating point number quo.

When will you prefer to work with a switch statement?


What is a null statement? How can it be useful in our
programs?

In what situation will you prefer to use for, while, and


do while loops?

Can we use a for loop when the number of iterations is


not known in advance? If yes, give a program that
illustrates how this can be done.

Change the following for loop into a while loop. Also


convert the for loop into a do-while loop.

int
for (i10;1>0;i--)
printf("xd", 1);

Change the following do-while loop into a for loop. Also


rewrite the code by changing the do-while loop into a for
loop.

int num;

printf("\n Enter any number. Enter 999 to


stop : ");

scanf("Xd", &num);

do

printf("%d", x);

printf("\n Enter any number, Enter 999 to stop


")5
scanf("Xd", &num);

}while(num |» 999);

Change the following while loop into a do-while loop.


Also convert the while loop into a for loop

int num;

printf("\n Enter any number. Enter 999 to


ys i

scanf("%d", &num);

while(num |= 999)

printf("X%d", x);

printf("\n Enter any number. Enter 999 to stop


er

scanf("Xd", &num);

stop
20.

The following for loops are written to print numbers


from 1 to 10. Are these loops correct? Justify your
answer.

(a) int i;
for(i=0;i<10;i++)
printf("%d", i);
int i, num;
for(i=0; 1<10;i++)
{

num = iel;
printf("Xd", num);
}

int i;
for(i=1;i<=10;i++)
{
printf("xd",
ite

(b)
(c)

i);

Programming Exercises

Write a program to read a floating point number and an


integer. If the value of the floating point number is
greater than 3.14 then add 10 to the integer.

Write a program to print the prime factors of a number.

Write a program to test if a given number Is a power of 2

Hint: A number x is a power of 2 if x I= 0 and


x & (x 1)) 0

Write a program to print the Floyd's triangle.

Write a program to read two numbers. Then find out


whether the first number is a multiple of the second
number.

Write 3 program using switch case to display a menu


that offers 5 options: read three numbers, calculate
total, calculate average, display the smallest, and display
the largest value.

Write a program to display the sin(x) value where x


ranges from 0 to 360 in steps of 15.

Write a program to display the cos(x) and tan(x) values


where x ranges from 0 to 360 in steps of 15

Write a program to calculate electricity bill based on the


following information

Consumption unit Rate of charge


[o-1s0 Rs 3 per unit |
151-350 Rs 100 plus Rs 3.75 per unit

|_ exceeding 150 units


| 351-450 Rs 250 plus Rs 4 per unit
| |_exceeding 350 units |
451-600 Rs 300 plus Rs 4.25 per unit
| |_ exceeding 450 units
Above 600 Rs 400 plus Rs 5 per unit

exceeding 600 units

10.

ii,
12

13

15.

16.

17,

18

19,

20.

21
22.

Write a program to read an angle from the user and then


display its quadrant
Write a program that accepts the current date and the
date of birth of the user. Then calculate the age of
the user and display it on the screen, Note that the date
should be displayed in the format specified as dd/mm/
vy.

A class has SO students. Every student is supposed to


give three examinations. Write a program to read the
marks obtained by each student inall three examinations
Calculate and display the total marks and average of
each student in the class.

Write a program in which the control variable is updated


in the statements of the for loop.

Write a program which demonstrates the use of goto,


break, and continue statements.

Write a program that displays all the numbers from 1 to


100 that are not divisible by 2 as well as by 3.

Write a program to calculate parking charges of a vehicle.


Enter the type of vehicle as a character (like ¢ for car, b
for bus, etc.) and number of hours then calculate charges
as given below:

* Truck/Bus — 20 Rs per hour

* Car = 10 Rs per hour

* Scooter/ Cycle/ Motor cycle ~ 5 Rs per hour


Modify the above program to calculate the parking
charges. Read the hours and minutes when the vehicle
enters the parking lot. When the vehicle is leaving, enter
its leaving time. Calculate the difference between the
two timings to calculate the number of hours and
minutes for which the vehicle was parked. Finally
calculate the charges based on following rules and then
display the result on the screen.

Vehicle name | Rate till 3 hours | Rate after 3 hours

1
[Teuck/Bus | __-20 I 30
Car | 10 | 20
Cycle/ Motor 5 10

cycle/ Scooter |

Write a program to read month of the year as an integer


Then display the name of the month.

Write a program to print the sum of all odd numbers


from 1 to 100.

Write an interactive program to read an integer. If it is


positive then display the corresponding binary
representation of that number. The user must enter 999
to stop. In case the user enters a negative number then
ignore that input and ask the user to re-enter any
different number.

Write a program to print 20 asterisks.

Write a program that accepts any number and prints the


number of digits in that number.

23.

24.

25.

26.

27.

28

29.

30.

31
Decision Control and Looping Statements 239

Write a program to generate the following pattern;

Write a program to generate the following pattern:

Severe

“$ .
-$ .
i at |

ween

Write a program to generate the following pattern

Write programs to implement the following sequence of


numbers.

1, 8, 27, 64,

-5, -2, 0, 3, 6, 9%
-2, -4, -6, -8, -10,
35/4, 24°20;
Write a program that reads integers until the user wants
to stop. When the user stops entering numbers, display
the largest of all the numbers entered.

12,
12,

Write a program to print the sum of the following series.

-x¢ x= x? o xt +
1 + (1+2) + (14243) +
1-x + x*/2! - x/3! +

Write a program to print the following pattern.

Write a program to print the following pattern.

212

32123

Write a program to read a 5 digit number and then


display the number in the following format. For example
the user entered 12345, the result should be
12345 1

2345 12

345
4s 1234

s 12345

240 Computer Fundamentals and Programming in C

Find the output of the following codes.


1. include <stdio.h>
int main()
{
inta=2,b=3, c= 4;
if( cl= 100)
a = 10;
else
b = 10;
if(a +b > 10)
c = 12;
a = 20;
b = +c;
printf(" \n a= Xd \t b= Xd \t c= Xd",
c);
return 0;
}
2. #include <stdio.h>
int main()

{
intaes2,b#3,c#4
if(be=2)
a0;
else
#10;
printf("\n a = %d \t b = Xd \t c = Xd", a, b
c);
return 0;

3, #include <stdio.h>
int main()
{
inta=2,b=3,c=4;
if (a&&b)
#10;
else
=20;
printf(“\n a= %d \t b= Xd \t c= Xd", 2, b,
©);
return 0;
}
4, #include <stdio.h>
int main()
c=20;
printf("\n a = %d \t b = Xd \t c = Xd", a, BD
c);
return 0;
}
5. #include <stdio.h>
int main()

c);
return 0;
}
include <stdio.h>
int main()
{
int a= 2, b= 3, = 4;
if(a © || b >= « && « > 0)
if(a && b)
¢=10;
else
c#20;
printf(" \n a = Xd \t b = Xd \t c = Xd", a, b
°)5
return 0;
}
include <stdio.h>

int main()

{
int a= 2,b=3,c#4;

if( a= b)
cH

printf(" \n a = Xd \t b = Xd \t c = Xd", a, bd,


©);

return 0;

#include <stdio.h>

int main()

inta«2, b= 3, c = 4;

if(a = b< c)

++b;

printf(" \n a = Xd \t b = Md \t c = Xd", a, b
©)3

return 0;

switch(ch)
{

case ‘a

case ‘A’
printf("\n A");

case 'b':

case 'B"

printf("\n B");

10.

11

12

4.
15.

default:

printf("\n DEFAULT");

switch(ch)

case ‘a

case ‘A’:
printf("\n An);

case 'b’

case 'B
printf("\n B");
break;

default:
printf("\n DEFAULT");

switch(ch)

{
case ‘a

case ‘A’:
printf("\n a");
break;

case ‘b

case 'B
printf("\n B");
break;

default:
printf("\n DEFAULT");

#include <stdio.h>

void main()

int num = 10;

printf("\n Xd", a>200);

#include <stdio.h>
void main()

printf ("HELLO");

if (-1)
printf ("WORLD");

#include <stdio.h>

void main()

int a = 3;

if(a < 10)


printf("\n LESS");

if(a < 20)


printf("\n LESS");

if(a < 30)


printf("\n LESS");

#include <stdio.h>

void main()
{
int a=10, b=20, c=30, d=40)

19.

20.

Decision Control and Looping Statements 241

if( ¢ < d)

if (¢ <b)
printf("\n c");

else if(a < c)


printf("\n a");

if(a > b)
printf("\n b");

else
print€("\n d");

#include <stdio.h>
void main()

char ch = 'Y';

switch(ch)

default:
printf("\n YES OR NO");

case ‘Y’
print#("VES");
break;

case 'N’
print#("NO");
break;

#include <stdio.h>

int main()

{
int num«10;
for (num++num++nume+)
print#("Xd", num);
return 0;

#include <stdio.h>
int main()

int num=10;

for (;--num;)
printf(" Xd", num);
return 0;

include <stdio.h>
int main()

int num=10;

for(; !num;num++)
printf(" Xd", num);
return 0;
}

#include <stdio.h>
int main()

float PI = 3.14, area;

242

21

22

23

24

25.

‘Computer Fundamentals and Programming in C

int r = 7;
while(r>=0)
{

area = PI * rer;
printf("\n Area = Xf", area);
}

return 0;

#include <stdio.h>

void main()

if(n<10)

break;

nes5

printf("\n ieXd and n=Xd", i,n);


}

include <stdio.h>

void main()
{
int i#0;
do
{
printf("\n %d",i);
its;
}while(ice0);
printf("\n STOP");
}
#include <stdio.h>
void main()
{
int i, J;
for(iw0;i<#10;i++)

{
printf("\n");
for(j=0;j<=i0; j++)
printf(" ");
printf("\n %d", 3)5
}

#include <stdio.h>
void main()

int num = 10;


printf("\n Xd", a>10);
}

#include <stdio.h>
void main()
{
printf("HELLO") ;
if (11)

printf ("WORLD") ;

26.

27.

28.

29.

30.

#include <stdio.h>
void main()
{
int x=-1;
unsigned int y=1;
if(x < y)
printf("\n SMALL");
else

printf("\n LARGE");

#include <stdio.h>
void main()

{
char ch = -63;

int num = -36;

unsigned int unum = -18;


if(ch > num)

printf("A");
if(ch > unum)
printf("B");
else
printf("C");
}
else

{
print#("D");
if(num < unum)
printf("E");
else
printf("F");

#include <stdio.h>

int main()

int num=10;

for (;++num;num-=2)

printf(" Xd", num);

urn 0;

#include <stdio.h>
int main()

int num=10;
for(;5)
printf("HI!!");
return 0;

#include <stdio.h>
int main()

int num=10;

Decision Control and Looping Statements 24.

for(num++ num<=100; num=100) Find errors in the following codes.


printf ("%d", num); (a) #include <stdio.h>
return 0; void main()
}{
31, #include <stdio.h> int i=1;
int main() while(ic=10)
{{
while(1); isi;
printf("Hi"); print#("%d", i);
return 0; ite;
}}
32. #include <stdio.h>
int main() (b) include <stdio.h>
{ void main()
int i=0; {
char c ='0'; int i;
while(i<10) for(i=0,ic#10; i++)
{ printf("%d", i);
printf("%e", ¢ + 4);
itt; (c) #include <stdio.h>
} void main()
return 0; {
} int il;
33, #include <stdio.h> do
void main() {
{ printf("xd", i);
int i0; ive;
do }while(i#10)
{}
if(i>10) (d) #include <stdio.h>
continue; void main()
iets {
}while(i<20); int i,j;
printf("\n iexd", i); for(in1,j=O;i+jcu10; i++)
} printf("Xd", i);
34, Hinclude <stdio.h> jen2
void main() }
{
int ie; Give the functionality of the following loops.
for(j;i<#ljier) (a) int i=1, sum=0;
{ while(i!l=10)
printf("\n &d",4); {
printf("\n STOP"); sum ¢=i;
} i = ie2;
}}
35. #include <stdio.h> (b) int 4, sum=0;
void main () for (i=1;i<=10)
{ sum=
Ant 45,95 (c) int 4;
for(i=10;i>=0;i--) for ( pic=l0;ite)
q

‘ i--;

printé("\n*)
for(j=i;j>=0;j--)

(d) int i=10;

do
printf("%d", j)5 { printf(“%d", i);
} } while(i>0);

(e) int i=10;

244

(f
(g)

‘Computer Fundamentals and Programming in C

do

{ printf("xd", i);
} while(i<5);
int is1, n=10,
while(icen)

sum+=d; ti
ite

int i, sum=0;

for (i#1;;i++)

(h)

sum=0;

)
sum+=i;

int i=10;
while(i-->0)
printf("Xd", i);
int i;

for (i=10;i>5;i-=2)
printf("Xd", i);

int 4;
for (i=10;1>5;)
print#(“Xd", i);

Decision Control and Looping Statements 245

CASE STUDY 1: Chapters 9 and 10

We have learnt the basics of programming in C language and


concepts to write decision-making programs. bet us now apply
our learning to write some useful programs

ROMAN NUMERALS
Roman numerals are written as combinations of seven letters.
These letters include
If smaller numbers follow larger numbers, the numbers are
added, Otherwise, if a smaller number precedes a larger number
the smaller number is subtracted from the larger. For example, to
convert 1,100 in Roman numerals, you would write M for 1000
and then a C after it for 100, Therefore, 1100 = MC in Roman
numerals. Some more examples include
© Vil=$+2=7
* Xel0-1=9
* XL=50-10=40
* CX= 1004021
* MCMLXXXIV = 1000 + (1000 ~ 100) + 50 + 30 +(S~ l=

1984

eA
Wl
4 |v

xvii | 31 | xxxt_ | S00 | D

s|v [is]

6 | vi 19 |_XIX_| 40 XL 600 | be |
7 | Vil | 20 50 _700 | Dec |
rs | vin | 20 “60 “g00 | pece |
9 | 1x | 2 70 900 | cM |
io | x | 23 80 1000 | M

i XI | 24 0 1600 | MDC
12 | XM | 25 100 c 1700 | MDCC |

13 | XIN | 26 | XXVI} 101) Cl 1900 | MCM |

1, Write a program to show the Roman number representation


of a given number.
#include <stdio.h>
#include <conio.h>
main()
{
int number;
int ones, tens, hundreds, thousand;
clrser();
printf("\n Enter any number
(1-3000): ");

scanf(“Xd" , number);

if (number==0| |number>3000)
printf ("\n INVALID NUMBER");
thousand = number/1000;
hundreds = ((number/100)%10) ;
tens = ((number/10)%10) ;
ones = ((number/1)%10) ;

if (thousand ==1)
printf("M");
else if (thousand ==2)
printé("MM");

else if (thousand ==3)


printf("MaM");

if (hundreds == 1)
printf("c");

else if (hundreds «= 2)
printf("CC");

else if (hundreds «= 3)
print#("ccc");

else if (hundreds «= 4)
printf("CbD");

else if (hundreds ==5)


printf("0");

else if (hundreds «= 6)
printf("0C");

else if (hundreds == 7)
printf("DCC");

else if (hundreds ==8)


printf("OCCC”);

else if (hundreds == 9)
printf("CM");
if (tens =» 1)
printf("x");
else if (tens 2)
printf("xX");
else if (tens == 3)
printf ("Xxx");
else if (tens == 4)
printf("XL");
else if (tens ==5)
printf("L");
else if (tens == 6)
printf ("LX");
else if (tens == 7)
printf ("LXx");
else if (tens ==8)
printf ("Lx");
else if (tens == 9)
printf ("XC");

246

Computer Fundamentals and Programming in C

if (ones == 1)

Output
printf("I"); é

Bice i (ones <2) ee oe number (1-3000): 139

printf ("II");

lee 4* (ones o= 3) An algorithm to calculate the day of the week:

print#(*IIE"); 1. Centuries: Use the centuries table given below to calculate


else if (ones == 4) the century

printf("IVv"); 2. Years: We know that there are 365 days in a year, that is, 52
else if (ones ==5) weeks plus 1 day. Each year starts on the day of the week

printf("Vv"); after that starting the preceding year. Each leap year has one
else if (ones == 6) more day than a common year

printf("VI"); If we know on which day a century starts (from above), and


else if (ones == 7) we add the number of years elapsed since the start of the

printf(“VII"); century, plus the number of leap years that have elapsed since
else if (ones ==8) the start of the century, we get the day of the week on which

printf ("VIII"); the year starts. Where year is the last two digits of the year.

else if (ones == 9) 3. Months: Use the months table to find the day of the week a

print#("IXx");
month starts

getch();
) 4. Day of the month: Once we know on which day of the week
the month starts, we simply add the day of the month to find
the final result

Centuries table Months table Days table


1700-1799 | 4 January I (in leap year 6) Sunday 1
1800-1899 | 2 February _ | 4 (in leap year 2) Monday _|2
1900 ~ 1999 0 March 4 Tuesday 3
2000-2099 | 6 April Wednesday | 4

| May [Thursday [5
June 5 Friday 16
July 10 Saturday | 7
gust 3
pAsget _ |3__ A
2500 | 6
2600 — 2699 October t
November | 4
}+
December | 6
EXAMPLE I 2. Write a program to find out the day for a given date

Let us calculate the day of April 24, 1982.

1, Find the century value of 1900s from the centuries table: 0

2. Last two digits give the value of year: 82

3, Divide the 82 by 4: 82/4 = 20.5 and drop the fractional part


20
4. Find the value of April in the months table: 6

5. Add all numbers from steps 1-4 tw the day of the month (in
this case, 24): 0 + 82 +20 +6424 = 132

6, Divide the result of step 5 by 7 and find the remainder:


132/7 = 18 remainder 6

7, Look up the day's table for the remainder obtained

6 = Saturday

That the values in the century table, months table, and days table
are pre-determined. We will only be using them to calculate the
day of a particular date

#include <stdio.h>

#include <stdlib.h>

#include <conio.h>

main()

{
int dd,mm,yy,year,month,day,i,n;
elrscr();
printf("\n Enter the date:
scanf ("Xd Xd Xd", &dd, &mm, Byy) ;
if( dd>31 || mm>12)
{
printf(" INVALID INPUT ");
getch();
exit(0);

year = yy-1900;

Decision Control and Looping Statements 247

year = year/4; switch(day)


year = year+yy-1900; {
switch(mm) case 0:
{ // Since 7%7 = 0, case O means it's a
case 1: Saturday
case 10; printf("\n SATURDAY");
month = 1; break;
break; case 1:
case 2: printf("\n SUNDAY") ;
case 3: break;
case 11: case 2:
month = 4; printf("\n MONDAY") ;
break; break;
case 7: case 3:
case 4: printf("\n TUESDAY");
month = 0; break;
break; case 4:
case 5: printf("\n WEDNESDAY");
month = 2; break;
break; case 5:
case 6: printf("\n THURSDAY");
month = 5; break;
break; case 6:
case 8: printf("\n FRIDAY");
month = 3; break;
break; }
case 9: getch();
case 12: return 0;
month = 6; }
} breaks Output
year = year+month; Enter the date: 29 10 1981
year = yearedd; THURSDAY

day = year%7;

You might also like