KEMBAR78
POP-Module2 (1) Updated | PDF | Control Flow | Integer (Computer Science)
0% found this document useful (0 votes)
19 views84 pages

POP-Module2 (1) Updated

Uploaded by

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

POP-Module2 (1) Updated

Uploaded by

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

RV Institute of Technology & Management®

Module – 2

2.1.Datatypes
In computer science and computer programming, a data type or simply type is an attribute of data
whichtells the compiler or interpreter how the programmer intends to use the data. Most programming languages
support common data types of real, integer and boolean.

In the C programming language, data types are declarations for memory locations or variables that determine the
characteristics of the data that may be stored and the methods (operations) of processing that are permitted
involving them. Data types in C are shown in Fig 1.1.

MEMORY FORMA
DATA TYPE (BYTES) RANGE T
SPECIFIER
short int 2 -32,768 to 32,767 %hd
Dept of CSEu/nIsSigE
ne,dRshort int 2 0 to 65,535 %hu
unsigned int 4 0 to 4,294,967,295 %u
int 4 -2,147,483,648 to %d
2,147,483,647
long int 4 -2,147,483,648 to %ld
2,147,483,647
unsigned long int 4 0 to 4,294,967,295 %lu
long long int 8 -(2^63) to (2^63)-1 %lld
unsigned long 0 to
8 %llu
long int 18,446,744,073,709,551,615
signed char 1 -128 to 127 %c
unsigned char 1 0 to 255 %c
float 4 %f
double 8 %lf
I & II-Selomnegstdeoru, bPleroblem Solving Th1r2ough Pro gramming(21PSP13/23) P a g e%1L|f54

Table 2.1: Datatypes supported in C Language


RV Institute of Technology & Management®

2.1.1 C tokens
It is the basic building block of a C-Program. A C program consists of various tokens and a tokenis either
a keyword, an identifier, a constant, a variable.

2.1.2.Keywords and Identifiers

Keywords – it a word which has pre-defined meaning. The following list shows the reserved wordsin C.
These reserved words may not be used as constant or variable or any other identifier names.
auto else long switch
break enum register typedef
case extern return union

Dept of CSE/ISE, char


const
continue
default
float
for
goto
if
short
signed
sizeof
static
unsigned
void
volatile
while

RVITM do
double
int struct _Packed

2.1.2. Identifiers - A C identifier is a name used to identify a variable, function, or any other user-
defined item. An identifier starts with a letter A to Z or a to z or an underscore _ followed by zeroor more
letters, underscores, and digits (0 to 9).
C does not allow punctuation characters such as @, $, and % within identifiers. C is a case
sensitive programming language. Thus, Manpower and manpower are two different identifiers in
A. Here are some examples of acceptable identifiers:

I & II Semester, Principles of Programming using C (BPOPS103/203)


RV Institute of Technology & Management®

mohd zara abc move_name a_123


myname50 _temp j a23b9 retVal

2.1.3. Data types in C Language


⮚ Primary data types: These are fundamental data types in C namely integer( int ), floatingpoint(
float ), character( char ) and void .

⮚ Derived data types: Derived data types are nothing but primary data-types but a little twisted or

Dept of CSE/ISE,
grouped together like array, structure, union and pointer.

RVITM

Fig 2.1: Different Data types in C

2.2 Operators and Expressions in C language

An operator is a symbol that specifies the mathematical, logical or relational operation to be

I & II Semester, Principles of Programming using C (BPOPS103/203)


RV Institute of Technology & Management®

performed. An expression is any computation that yields a value.

C supports a rich set of operators. Operators are used in programs to manipulate data and
variables. Operators can be classified into a number of categories. They are:
● Arithmetic operators
● Relational operators
● Logical operators
● Assignment operators
● Increment and Decrement operators
● Conditional operators

Dept of CSE ●


Bit wise operators
Special operators

Arithmetic operators
C provides all the basic arithmetic operators. The operators R +,V
- ,*IaTnM
d / all work the same way as they
do in other languages. These can operate on any built-in data type allowed in C. The unary minus
operator, in effect, multiplies its single operand by -1. Therefore, a number preceded by a
minus sign changes its sign.

Operator Meaning
+ Addition or Unary plus
- Subtraction or Unary minus
* Multiplication
/ Division

% Modulo division

Table 2.1: Arithmetic Operators

I & II Semester, Principles of Programming using C (BPOPS103/203)


RV Institute of Technology & Management®

Integer division truncates any fractional part. The Modulo division operator produces the
remainder of an integer division. Examples or use of arithmetic operators are:
a-b a+b

a*b a/b
a%b -a*b

Here a and b are variables and are known as operands. The modulo divison operator % cannot be
used on floating point data.

Relational operators
We often compare two quantities and depending on their relation, to take certain decisions. For

Dept of CSE
Example, we may compare the age of two persons, or the price of two items, and so on. These
comparisons can be done with the help of relational operators. The value of relational expression is
either one or zero. It is one if the specified relation is true and zero if the relation is false.
For example,
10 < 20 is true

20 < 10 is false
C supports six relational operators in all.
Table 2.2: Relational Operators

RVITM Operator Meaning


<

<=
Less Than

Less than or equal to

I & II Semester, Principles of Programming using C (BPOPS103/203)


RV Institute of Technology & Management®

> Greater than


>= Greater than or equal to
== Equal to
!= Not equal to
Given below are some examples of simple relational expressions and their
values: 4.5<= 10 TRUE
4.5<10 FALSE

-35>= 0 FALSE

10<7+5 TRUE

a+b == c+d TRUE only if the sum of values of a and b is equal to the
sum of values of c and d.

When arithmetic expressions are used on either side of a relational operator, the arithmetic
expressions will be evaluated first and then the results compared. That is, arithmetic operators havea
higher priority over relational operators.

Relational expressions are used in decision statements such as, if and while to decide the course of
action of a running program.

Logical operators

&&(AND), ||(OR), ^(EX-OR) and !(NOT) are different logical operators shown in Table 1.6.
Table 2.3: Logical Operators

Operato r pM
t eoafniC
ng
SE,
De
&& Logical AND
|| Logical OR
! Logical NOT

I & II Semester, Principles of Programming using C (BPOPS103/203)


RV Institute of Technology & Management®

^ Logical XOR

RVIT
The logical operators && and || are used when we want to test more than one condition and make
decisions.

For example,

a > b && x == 10

This is true only if a > b is true and x == 10 is true. If either of them false, the expression is false.

Table 2.4 to 2.7 shows the truth tables of &&(AND), ||(OR), !(NOT) and ^(EX-OR)
respectively
. Table 2.4: Truth table for AND (&&) Table 2.5 : Truth table for OR (||)

A B A && B A B A || B
0 0 0 0 0 0
0 1 0 0 1 1
1 0 0 1 0 1
1 1 1 1 1 1

for NOT (!)


Table 2A.6 : Tru th table!A Table 2A.7: Truth tab
Ble for XORA(^^)B

0 1 0 0 0

De /ISE0, 1 1
1 0
pt of CSE 1 0 1
1 1 0

Assignment operators

RVITM
I & II Semester, Principles of Programming using C (BPOPS103/203)
RV Institute of Technology & Management®

Assignment operators are used to assign the result of an expression to a variable.

The form is v
=exp;
where v is a variable, exp is an expression. For example,
x=10; x=x+3; x=x+a*b;

Operator Meaning
= Assignment

Short hand assignment operators:

In addition to the usual assignment operator ‘=’ C has a set of assignment operators called
shorthand operators.
Some of the shorthand operators are listed below:

=, +=, -=,*=,/=,%=,>>=,<<=,&=, ^=, !=


for example,
x=x+3 this statement is equivalent to x+=3; when this statement is executed, 3 is added to x.

Increment (++) and Decrement (--) operators

Increment operator ++

The operator ++ adds 1 to the operand. Two types of increment operators are:
Prefix Increment operator(++op)

This first adds 1 to the operand and then the result is assigned to the variable on left.
For example,
m=5;
++m;
This statement increases the value of m by 1. that is m is 6.
Postfix Increment operator (op++)

Postfix operator first assigns the value to the variable on left and then increments the operand.
For example,
I & II Semester, Principles of Programming using C (BPOPS103/203)
RV Institute of Technology & Management®

m=5;
m++;
This statement increases the value of m by 1. That is m is 6.
While ++m and m++ mean the same thing when they form statements independently. They behave
differently when they are used in expressions on the right hand side of assignment statements.
For example,
m=5;
Y=++m;
RVITM
In this case, the value of y and m would be 6. Suppose, if we rewrite the above statements as
m=5;
y=m++;
here, the value of y would be 5 and m would be 6.

Conditional operator (? :)
This is also called as a ternary operator. The general form is:

exp1 ? exp2 : exp3;

where exp1, exp2 and exp3 are expressions.

Here, exp1 is evaluated first. If it is nonzero (true), then the expression exp2 is evaluated and
becomes the values of the expression. If exp1 is false, exp3 is evaluated and its value becomes the

values of the expression. Note that only one of the expressions either exp2 or exp3 is evaluated.
For example,
a=10;
b=34;
max=(a > b) ? a: b;

In this example, max will be assigned the value of b because the condition is false. So, exp3 (b)
is evaluated and its value is assigned to max.

Bitwise operators
These operators are used for testing the bits, or shifting them left or right. These Operators may not be
applied to float or double. Bitwise operators are shown in Table 2.7
I & II Semester, Principles of Programming using C (BPOPS103/203)
RV Institute of Technology & Management®

Meaning
& bitwise AND
bitwise OR
^ bitwise XOR
<< shift left
>> shift right

Table 2.7: Bitwise operators


Bitwise AND
The result of bitwise AND operator is 1 if both the bits have a value of 1; otherwise it is 0.
Example :
if x=13 and y=25 then z= x & y;
if we execute this statement,

x=0000 0000 0000 1101


y=0000 0000 0001 1001
the result would be:
z=0000 0000 000 1001

Bitwise OR

The result of bitwise OR operator is 1 if atleast one of the bits has a value of 1; otherwise it is 0.
For example,
if x=13 and y=25 then
z= x | y;
if we execute this statement,
x=0000 0000 0000 1101
y=0000 0000 0001 1001
the result would be:
z=0000 0000 001 1101

I & II Semester, Principles of Programming using C (BPOPS103/203)


RV Institute of Technology & Management®

Bitwise XOR (Exclusive OR)

Dept of CSE/ISE,
The result of bitwise XOR operator is 1 if only one of the bits is 1; otherwise it is 0. For
example,
if x=13 and y=25 then
z= x ^y;

RVITM
if we execute this statement,
x=0000 0000 0000 1101
y=0000 0000 0001 1001
the result would be:
z=0000 0000 000 0100

Bitwise shift operators

The shift operators are used to move bit patterns either to the left or to the right. The shift
operators are represented by the symbols << and >>.
Left shift
op << n

op is an integer expression that is to be shifted and n is the number of bit positions to be


shifted. The left shift operation shifts all the bits in the operand op to be shifted to the left
by n positions. The leftmost n bits in the original bit pattern will be lost and rightmost n
bits that are vacated will be filled with 0s.
For example,

x is an unsigned integer that has the value 11. Then bit pattern
of x is: 0000 1011

Dept of CSE/ISE,
x << 1 is,
0001 0110 that is 22.
This is equal to the value of x will be multiplied by 2.
Right shift

I & II Semester, Principles of Programming using C (BPOPS103/203)


RV Institute of Technology & Management®

op >> n
The right shift operation shifts all the bits in the operand op to be shifted to the right by n positions. The rightmost n bits
in the original bit pattern will be lost and leftmost n bitsthatare vacated will be filled with 0s if the op is an unsigned integer. If
the variable to beshiftedis signed, then the operation is machine dependent.
For example,
x is an unsigned integer that has the value 11. Then bit pattern of x is: 0000 1011 x
>> 1 is,
0000 0101 that is 5.
This is equal to the value of x will be divided by 2.

Bitwise complement operator (~)


The operator ‘~’ inverts all the bits represented by its operand. That is, 0s become 1sand
1s become 0.
For example,
x=10;
binary representation of x is=0000 1010
~x =1111 0101

Special Operators

sizeof operator

The sizeof is a compile time operator and when used with an operand, it returns the number of
bytes the operand occupies. The operand may be a variable, a constant or a data type qualifier.

For example,
int n;
m=sizeof(n);

I & II Semester, Principles of Programming using C (BPOPS103/203)


RV Institute of Technology & Management®

Will return 2. That is m is assigned a value 2, because int occupies 2 bytes.


m=sizeof(34.76);

Dept of CSE,
Will return 4. That is m is assigned a value 4, because int occupies 4 bytes.

Comma Operator

C has some special operators. The comma operator is one among them. This operator can be usedto

RVITM
link the related expressions together. A comma-linked list of expressions are evaluated left to right
and the value of right-most expression is the value of the combined expression.
For example, the statement

Value = (a=2, b=6 ,a+b);

First assigns the value 2 to a, then assigns 6 to b, and finally assigns 8(i.e 2+6) to value. The comma
operator has the lowest precedence of all operators,hence the parentheses are necessary.
Some examples are given below:
In for loops: for(a=1, b=10;a<=b; a++, b++)In
while loops: while(c=getchar(), C!=’10’)
Exchanging values: t=x, x=y, y=t;

2.3. Type conversion


In C programming, we can convert the value of one data type (int, float, double, etc.) to another. This process is
known as type conversion.
Example :

int number=34.78;
printf(“%d”,number);

Here, we are assigning the double value 34.78 to the integer variable number. In this case, the double value is
automatically converted to integer value 34.

I & II Semester, Principles of Programming using C (BPOPS103/203)


RV Institute of Technology & Management®

This type of conversion is known as implicit type conversion. In C, there are two types of type conversion:
1. Implicit Conversion
2. Explicit Conversion

Implicit Type Conversion In C

In implicit type conversion, the value of one type is automatically converted to the value of another type.
Example 1:

double value=4150.12;
printf(“Double value :%.21f\n”,value);

// convert double value to integer


int number = value;

printf("Integer Value: %d", number);

The above example has a double variable with a value 4150.12. Notice that we have assigned the double value to an
integer variable.

int number = value;

Here, the C compiler automatically converts the double value 4150.12 to integer value 4150.
Since the conversion is happening automatically, this type of conversion is called implicit type conversion.

Example2:

// character variable
char alphabet = 'a';
printf("Character Value: %c\n", alphabet);

I & II Semester, Principles of Programming using C (BPOPS103/203)


RV Institute of Technology & Management®

// assign character value to integer variable


int number = alphabet;
printf("Integer Value: %d", number);

The code above has created a character variable alphabet with the value 'a'. Notice that we are assigning alphabet to
an integer variable.

int number = alphabet;

Here, the C compiler automatically converts the character 'a' to integer 97. This is because, in C programming,
characters are internally stored as integer values known as ASCII Values.

ASCII defines a set of characters for encoding text in computers. In ASCII code, the character 'a' has integer
value 97, that's why the character 'a' is automatically converted to integer 97.

Explicit Type Conversion In C

In explicit type conversion, we manually convert values of one data type to another type.
Example1:
int number = 35;
printf("Integer Value: %d\n", number);

// explicit type conversion


double value = (double) number;

I & II Semester, Principles of Programming using C (BPOPS103/203)


RV Institute of Technology & Management®

printf("Double Value: %.2lf", value);

We have created an integer variable named number with the value 35 in the above program. Notice the code,

// explicit type conversion


double value = (double) number;

 (double) - represents the data type to which number is to be converted


 number - value that is to be converted to double type

Example2:

int number = 97;


printf("Integer Value: %d\n", number);

// (char) converts number to character


char alphabet = (char) number;
printf("Character Value: %c", alphabet);

We have created a variable number with the value 97 in the code above. Notice that we are converting this integer to
character.

char alphabet = (char) number;

 (char) - explicitly converts number into character


 number - value that is to be converted to char type

I & II Semester, Principles of Programming using C (BPOPS103/203)


RV Institute of Technology & Management®

2.3.1. Data Loss In Type Conversion

In our earlier examples, when we converted a double type value to an integer type, the data after decimal was lost.

Example1:

double value = 4150.12;


printf("Double Value: %.2lf\n", value);

// convert double value to integer


int number = value;

printf("Integer Value: %d", number);

Here, the data 4150.12 is converted to 4150. In this conversion, data after the decimal, .12 is lost.

This is because double is a larger data type (8 bytes) than int (4 bytes), and when we convert data from larger type
to smaller, there will be data loss.

Similarly, there is a hierarchy of data types in C programming. Based on the hierarchy, if a higher data type is
converted to lower type, data is lost, and if lower data type is converted to higher type, no data is lost.

I & II Semester, Principles of Programming using C (BPOPS103/203)


RV Institute of Technology & Management®

Here,
 data loss - if long double type is converted to double type
 no data loss - if char is converted to int

2.3 Type casting

Typecasting allows us to convert one data type into other. In C language, we use cast operator for typecasting which
is denoted by (type).

Syntax:

(type)value;

I & II Semester, Principles of Programming using C (BPOPS103/203)


RV Institute of Technology & Management®

Without Type Casting:

Example1:
1. int f= 9/4;

2. printf("f : %d\n", f );
output is 2.
With Type Casting:

Example1:
1. float f=(float) 9/4;
2. printf("f : %f\n", f );
output is 2.250000

I & II Semester, Principles of Programming using C (BPOPS103/203)


RV Institute of Technology & Management®

2.4 Decision Control and Looping Statements

2.4 Introduction to Decision control


Decision making is about deciding the order of execution of statements based on certain conditions
or repeat a group of statements until certain specified conditions are met. C language handles
decision-making by supporting the following statements,

 if statement
 switch statement
 conditional operator statement (? : operator)
 goto statement

2.5 Conditional branching Statements:

 Decision making with if statement


The if statement may be implemented in different forms depending on the complexity of conditions
to be tested. The different forms are,

 Simple if statement
 if... else statement
 Nested if. .. else statement
 Using else if statement

 Simple if statement
The general form of a simple if statement is,
if(expression)
{
statement inside;

I & II Semester, Principles of Programming using C (BPOPS103/203)


RV Institute of Technology & Management®

}
statement outside;
If the expression returns true, then the statement-inside will be executed, otherwise statement-
inside is skipped and only the statement-outside is executed.

Example:

#include <stdio.h>
void main( )
{
int x =15, y=13;

if (x > y )
{
printf("x is greater than y");
}
}
x is greater than y

 if...else statement
The general form of a simple if...else statement is,
if(expression)
{
statement block1;
}
else
{
statement block2;
}

If the expression is true, the statement-block1 is executed, else statement-block1 is skipped

I & II Semester, Principles of Programming using C (BPOPS103/203)


RV Institute of Technology & Management®

and statement-block2 is executed. Flow chart of if else ish shown in Fig 2.2.

I & II Semester, Principles of Programming using C (BPOPS103/203)


RV Institute of Technology & Management®

Fig 2.2: Flowchart: if...else statement

Example:

#include <stdio.h>
void main( )

{
int x, y;
x = 15;
y = 18;
if (x > y )
{
printf("x is greater than y");
}
else
{
printf("y is greater than x");
}
}
y is greater than x

 Nested if... else statement

The general form of a nested if. else statement is,

if( expression )
{
if( expression1 )
{

v
I & II Semester, Principles of Programming using C (BPOPS103/203)
RV Institute of Technology & Management®

statement block1;
}
else
{
statement block2;
}
}
else
{
statement block3;
}
if expression is false then statement-block3 will be executed, otherwise the execution continues
and enters inside the first if to perform the check for the next if block, where if expression 1 is true
the statement-block1 is executed otherwise statement-block2 is executed. Flow chart of nested if
else is shown in Fig 2.2.

if(a > c)
{
printf("a is the greatest");
}
else
{
printf("c is the greatest");
}
}
else
{
if(b > c)
v

I & II Semester, Principles of Programming using C (BPOPS103/203)


RV Institute of Technology & Management®

{
printf("b is the greatest");

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

 else if ladder
The general form of else-if ladder is,
if(expression1)
{
statement block1;
}
else if(expression2)
{
statement block2;
}
else if(expression3 )
{
statement block3;
}
else
default statement;

I & II Semester, Principles of Programming using C (BPOPS103/203)


RV Institute of Technology & Management®

The expression is tested from the top(of the ladder) downwards. As soon as a true condition is

found, the statement associated with it is executed. Flow chart of else if ladder is shown in Fig 2.3.

Fig 2.4: Flowchart: Else if ...Ladder

Example :

#include <stdio.h>
void main( )
{
int a;
printf("Enter a number...");

I & II Semester, Principles of Programming using C (BPOPS103/203)


RV Institute of Technology & Management®

scanf("%d", &a);
if(a%5 == 0 && a%8 == 0)
{
printf("Divisible by both 5 and 8");
}
else if(a%8 == 0)
{
printf("Divisible by 8");
}
else if(a%5 == 0)
{
printf("Divisible by 5");
}

else
{
printf("Divisible by none");
}
}

 Points to Remember

1. In if statement, a single statement can be included without enclosing it into curly braces { ... }

int a = 5;
if(a > 4)
printf("success");
No curly braces are required in the above case, but if we have more than one statement inside if
condition, then we must enclose them inside curly braces.

I & II Semester, Principles of Programming using C (BPOPS103/203)


RV Institute of Technology & Management®

2. = = must be used for comparison in the expression of if condition, if you use = the expression will
always return true, because it performs assignment not comparison.
3. Other than 0(zero), all other values are considered as true.

if (27)
printf("hello");

In above example, hello will be printed.

 Switch statement in C

When you want to solve multiple option type problems, for example: Menu like program, where
one value is associated with each option and you need to choose only one at a time, then, switch
statement is used.

Switch statement is a control statement that allows us to choose only one choice among the many
given choices. The expression in switch evaluates to return an integral value, which is then compared
to the values present in different cases. It executes that block of code which matches the case value.
If there is no match, then default block is executed (if present). The general formof switch
statement is,
switch(expression)
{
case 1:
block 1;
break;
case 2:
block 2;
break;
case 3:
block 3;
break;

I & II Semester, Principles of Programming using C (BPOPS103/203)


RV Institute of Technology & Management®

case 4:
block 4;
break;
default:
default block;
break;
}

 Rules for using switch statement

1. The expression (after switch keyword) must yield an integer value i.e the expression should be
an integer or a variable or an expression that evaluates to an integer.
2. The case label values must be unique.
3. The case label must end with a colon(:)
4. The next line, after the case statement, can be any valid C statement.

 Points to Remember
1. We don't use those expressions to evaluate switch case, which may return floating point values
or strings or characters.
2. break statements are used to exit the switch block. It isn't necessary to use break after each
block, but if you do not use it, then all the consecutive blocks of code will get executed after the
matching block.

int i = 1;
switch(i)
{
case 1:

I & II Semester, Principles of Programming using C (BPOPS103/203)


RV Institute of Technology & Management®

printf("A"); // No break
case 2:
printf("B"); // No break
case 3:
printf("C");
break;
}

The Output of this program is: A B C

The output was supposed to be only A because only the first case matches, but as there is
no break statement after that block, the next blocks are executed too, until it a break statement in
encountered or the execution reaches the end of the switch block.

3. default case is executed when none of the mentioned case matches the switch expression. The
default case can be placed anywhere in the switch case. Even if we don't include the default case,
switch statement works.
4. Nesting of switch statements are allowed, which means you can have switch statements inside
another switch block. However, nested switch statements should be avoided as it makes the program
more complex and less readable.

Example of switch statement


#include<stdio.h>
void main( )
{
int a, b, c, choice;
while(choice != 3)
{

I & II Semester, Principles of Programming using C (BPOPS103/203)


RV Institute of Technology & Management®

/* Printing the available options */


printf("\n 1. Press 1 for addition");
printf("\n 2. Press 2 for subtraction");
printf("\n Enter your choice");
scanf("%d", &choice); /* Taking users input */
switch(choice)

{
case 1:
printf("Enter 2 numbers");
scanf("%d%d", &a, &b);
c = a + b;
printf("%d", c);
break;
case 2:
printf("Enter 2 numbers");
scanf("%d%d", &a, &b);
c = a - b;
printf("%d", c);
break;
default:
printf("you have passed a wrong key");
printf("\n press any key to continue");
}
}
}

Difference between switch and if

 if statements can evaluate float conditions. switch statements cannot evaluate float conditions.

I & II Semester, Principles of Programming using C (BPOPS103/203)


RV Institute of Technology & Management®

 if statement can evaluate relational operators. switch statement cannot evaluate relational
operators i.e they are not allowed in switch statement.

2.6 Iterative Statements

 Loops in ‘C’ Language

You may encounter situations, when a block of code needs to be executed several numbers of times.
In general, statements are executed sequentially: The first statement in a function is executed first,
followed by the second, and so on. Fig 2.4 shows the flow chart of general loop.

Programming languages provide various control structures that allow for more complicated execution
paths. A loop statement allows us to execute a statement or group of statements multiple times. Given
below is the general form of a loop statement in most of the programming languages −

Sl.No. Loop Type & Description

while loop: Repeats a statement or group of statements while a given condition


1
is true. It tests the condition before executing the loop body.

for loop: Executes a sequence of statements multiple times and abbreviates the
2
code that manages the loop variable.

do...while loop: It is more like a while statement, except that it tests the
3
condition at the end of the loop body.

nested loops: You can use one or more loops inside any other while, for, or
4
do..while loop.

I & II Semester, Principles of Programming using C (BPOPS103/203)


 for Loop

The syntax of for loop is:

for (Initialization Statement; Test Expression; Update Statement)


{
// codes

}
Fig 2.5 shows the flow chart of for loop.

 How for loop works?

1. The initialization statement is executed only once.

2. Then, the test expression is evaluated.


 If the test expression is false (0), for loop is terminated.

I & II Semester, Principles of Programming using C (BPOPS103/203)


RV Institute of Technology & Management®

 But if the test expression is true (nonzero), codes inside the body of for loop is executed and
the update expression is updated.

3. This process repeats until the test expression is false.

4. The for loop is commonly used when the number of iterations is known.

 For-loop Flowchart

Fig 2.5: Flowchart: for loop

Example: for loop


// Program to calculate the sum of first n natural numbers
// Positive integers 1,2,3...n are known as natural numbers

I & II Semester, Principles of Programming using C (BPOPS103/203)


RV Institute of Technology & Management®

#include <stdio.h>
int main()
{
int num, count, sum = 0;
printf("Enter a positive integer: ");
scanf("%d", &num);
// for loop terminates when n is less than count
for(count = 1; count <= num; ++count)
{
sum += count;
}
printf("Sum = %d", sum);
return 0;
}

Output

Enter a positive integer: 10

Sum = 55

 The value entered by the user is stored in variable num, suppose, the user entered 10.

 The count is initialized to 1 and the test expression is evaluated. Since, the test expression
count <= num (1 less than or equal to 10) is true, the body of for loop is executed andthe value of
sum will equal to 1.

 Then, the update statement ++count is executed and count will equal to 2. Again, the test

I & II Semester, Principles of Programming using C (BPOPS103/203)


RV Institute of Technology & Management®

expression is evaluated. Since, 2 is also less than 10, the test expression is evaluated to true and the
body of for loop is executed. Now, the sum will equal 3.

 This process goes on and the sum is calculated until the count reaches 11.

I & II Semester, Principles of Programming using C (BPOPS103/203)


RV Institute of Technology & Management®

 When the count is 11, the test expression is evaluated to 0 (false) as 11 is not less than or equal
to 10. Therefore, the loop terminates and next, the total sum is printed.

Example: Factorial of a Number


#include <stdio.h>
int main()
{
int n, i;
unsigned long long factorial = 1;
printf("Enter an integer: ");
scanf("%d",&n);
// show error if the user enters a negative integer
if (n < 0)
printf("Error! Factorial of a negative number doesn't exist.");
else
{
for(i=1; i<=n; ++i)
{
factorial *= i; // factorial = factorial*i;
}
printf("Factorial of %d = %llu", n, factorial);
}
return 0;
}

I & II Semester, Principles of Programming using C (BPOPS103/203)


RV Institute of Technology & Management®

Output

Enter an integer: 10

Factorial of 10 = 3628800

Example #1: GCD Using for loop and if Statement

#include <stdio.h>
int main()
{
int n1, n2, i, gcd;
printf("Enter two integers: ");
scanf("%d %d", &n1, &n2);
for(i=1; i <= n1 && i <= n2; ++i)
{
// Checks if i is factor of both integers
if(n1%i==0 && n2%i==0)
gcd = i;
}
printf("G.C.D of %d and %d is %d", n1, n2, gcd);
return 0;
}

 In this program, two integers entered by the user are stored in variable n1 and n2.Then, for loop
is iterated until (i) is less than n1 and n2.
 In each iteration, if both n1 and n2 are exactly divisible by (i), the value of (i) is assigned to gcd.
 When the for loop is completed, the greatest common divisor of two numbers is stored in

I & II Semester, Principles of Programming using C (BPOPS103/203)


RV Institute of Technology & Management®

variable gcd.

While loop
While loop can be addressed as an entry control loop. It is completed in 3 steps.
 Variable initialization.(e.g int x = 0;)

Condition (e.g while(x <= 10))


Variable increment or decrement ( x++ or x-- or x = x + 2 )

Syntax:
variable initialization;
while(condition)

statements;
variable increment or decrement;

Fig 2.6 shows the flowchart of while loop.

Fig 2.6: Flowchart of while loop

Example: Program to print first 10 natural numbers

#include<stdio.h>
void main( )

I & II Semester, Principles of Programming using C (BPOPS103/203)


RV Institute of Technology & Management®

{
int x;
x = 1;
while(x <= 10)

{
printf("%d\t", x);
/* below statement means, do x = x+1, increment x by 1*/
x++;
}
}
Program Output: 1 2 3 4 5 6 7 8 9 10

I & II Semester, Principles of Programming using C (BPOPS103/203)


RV Institute of Technology & Management®

Example 1: while loop


// Program to find factorial of a number
// For a positive integer n, factorial = 1*2*3...n
#include <stdio.h>
int main()
{
int number;
long long factorial;
printf("Enter an integer: ");
scanf("%d",&number);
factorial = 1;
// loop terminates when number is less than or equal to 0
while (number > 0)
{
factorial *= number; // factorial = factorial*number;
--number;
}
printf("Factorial= %lld", factorial);
return 0;
}

I & II Semester, Principles of Programming using C (BPOPS103/203)


RV Institute of Technology & Management®

do while loop
In some situations it is necessary to execute body of the loop before testing the condition. Such
situations can be handled with the help of do-while loop. do statement evaluates the body of the
loop first and at the end, the condition is checked using while statement. It means that the body of the
loop will be executed at least once, even though the starting condition inside while is initialized to be
false. General syntax is,

do
{
.....
.....
}
while(condition)

Fig 2.7 shows the flowchart of do while loop.

I & II Semester, Principles of Programming using C (BPOPS103/203)


RV Institute of Technology & Management®

Example: Program to print first 10 multiples of 5.

#include<stdio.h>

void main()
{
int a =5, i=1;
do
{
printf("%d\t", a*i);
i++;
}
while(i <= 10);
}

The output of the Program: 5 10 15 20 25 30 35 40 45 50

2.7 Nested loops

C supports nesting of loops in C. Nesting of loops is the feature in C that allows the looping of statements
inside another loop.

Any number of loops can be defined inside another loop, i.e., there is no restriction for defining any number of
loops. The nesting level can be defined at n times. You can define any type of loop inside another loop; for example,
you can define 'while' loop inside a 'for' loop.

Syntax of Nested loop:

Outer_loop

I & II Semester, Principles of Programming using C (BPOPS103/203)


RV Institute of Technology & Management®

{
Inner_loop
{
// inner loop statements.
}
// outer loop statements.
}
Outer_loop and Inner_loop are the valid loops that can be a 'for' loop, 'while' loop or 'do-while' loop.

Nested for loop


The nested for loop means any type of loop which is defined inside the 'for' loop.
for (initialization; condition; update)
{
for(initialization; condition; update)
{
// inner loop statements.
}
// outer loop statements.
}

Example of nested for loop

for(int i=1;i<=n;i++) // outer loop


{
for(int j=1;j<=10;j++) // inner loop
{
printf("%d\t",(i*j)); // printing the value.
}
Explanation of the above code

I & II Semester, Principles of Programming using C (BPOPS103/203)


v

RV Institute of Technology & Management®

o First, the 'i' variable is initialized to 1 and then program control passes to the i<=n.
o The program control checks whether the condition 'i<=n' is true or not.
o If the condition is true, then the program control passes to the inner loop.
o The inner loop will get executed until the condition is true.
o After the execution of the inner loop, the control moves back to the update of the outer loop, i.e., i++.
o After incrementing the value of the loop counter, the condition is checked again, i.e., i<=n.
o If the condition is true, then the inner loop will be executed again.
o This process will continue until the condition of the outer loop is true

Nested while loop


The nested while loop means any type of loop which is defined inside the 'while' loop.

while(condition)
{
while(condition)
{
// inner loop statements.
}
// outer loop statements.
}
Example of nested while loop

int a[rows][columns]; //2d array declaration


int i=1;
while(i<=rows) // outer loop
{
int j=1;
while(j<=columns) // inner loop
{
printf("%d\t",k); // printing the value of k.

I & II Semester, Principles of Programming using C (BPOPS103/203)


v

RV Institute of Technology & Management®

k++; // increment counter


j++;
}
i++;
printf("\n");
}
}

Explanation of the above code.


o We have created the 2d array, i.e., int a[rows][columns].
o The program initializes the 'i' variable by 1.
o Now, control moves to the while loop, and this loop checks whether the condition is true, then the program
control moves to the inner loop.
o After the execution of the inner loop, the control moves to the update of the outer loop, i.e., i++.
o After incrementing the value of 'i', the condition (i<=rows) is checked.
o If the condition is true, the control then again moves to the inner loop.
o This process continues until the condition of the outer loop is true.

Nested do..while loop

The nested do..while loop means any type of loop which is defined inside the 'do..while' loop.

do
{
do
{
// inner loop statements.
}while(condition);
// outer loop statements.
}while(condition);

I & II Semester, Principles of Programming using C (BPOPS103/203)


v

RV Institute of Technology & Management®

Example of nested do..while loop.

int i=1;
do // outer loop
{
int j=1;
do // inner loop
{
printf("*");
j++;
}while(j<=8);
printf("\n");
i++;
}while(i<=4);
}

Explanation of the above code.

o First, we initialize the outer loop counter variable, i.e., 'i' by 1.


o As we know that the do..while loop executes once without checking the condition, so the inner loop is
executed without checking the condition in the outer loop.
o After the execution of the inner loop, the control moves to the update of the i++.
o When the loop counter value is incremented, the condition is checked. If the condition in the outer loop is
true, then the inner loop is executed.
o This process will continue until the condition in the outer loop is true.

2.8 C Program - Roots of a Quadratic Equation

#include <stdio.h>

I & II Semester, Principles of Programming using C (BPOPS103/203)


RV Institute of Technology & Management®

#include<conio.h>
#include<math.h>
void main()
{
float a, b, c, root1, root2, r_part, i_part, disc;
clrscr ();
printf ("Enter the 3 non-zero coefficients\n");
scanf ("%f%f%f",&a,&b,&c);
disc=(b*b)-(4*a*c);
if(disc==0)
{
printf("Roots are equal\n");
root1=-b/(2*a);
root2=root1;
printf("root1=root2=%f",root1);
}
else if(disc>0)

{
printf("Roots are real and distinct\n");
root1=(-b+sqrt(disc))/(2*a);
root2=(-b-sqrt(disc))/(2*a);
printf("root1 = %f \t root2 = %f\n",root1,root2);
}
else
{
printf("Roots are complex\n");
r_part=-b/(2*a);
i_part=(sqrt(-disc))/(2*a);
printf("root1 = %f+i%f \n root2 = %f-i%f\n",r_part,i_part,r_part,i_part);

I & II Semester, Principles of Programming using C (BPOPS103/203)


RV Institute of Technology & Management®

}
getch();
}

2.9 C Program - Print Pascal's Triangle


#include <stdio.h>
int main()
{
int rows, coef = 1, space, i, j;
printf("Enter number of rows: ");
scanf("%d",&rows);
for(i=0; i<rows; i++)
{
for(space=1; space <= rows-i; space++)
printf(" ");
for(j=0; j <= i; j++)
{
if (j==0 || i==0)
coef = 1;

I & II Semester, Principles of Programming using C (BPOPS103/203)


RV Institute of Technology & Management®

else
coef = coef*(i-j+1)/j;
printf("%4d", coef);
}
printf("\n");
}
return 0;
}

1
11
121
1331

2.10 C Program - Computation of Binomial Coefficients

#include<stdio.h>
#define MAX 10
int main()
{
int n, a, bi_nom;
print ("Mx ");
for (n=0; n<=10; ++n)
printf("%d ", n);
printf("\n \n");
n=0;
do

I & II Semester, Principles of Programming using C (BPOPS103/203)


RV Institute of Technology & Management®

a = 0, bi_nom = 1;
printf("%2d", n);
while(a<=n)
{
if(n==0 || a==0)
printf("%4d", bi_nom);

I & II Semester, Principles of Programming using C (BPOPS103/203)


RV Institute of Technology & Management®

else
{
bi_nom=bi_nom* (n-a+1)/a;
printf("%4d", bi_nom);
}
a=a+1;
}
printf("\n");
n=n+1;
}while(n<=MAX);
printf(" ");
}
Pictorial Presentation:

Table 2.1 : Binomial Cofficient

Programming Examples:
Example 1

A program to evaluate the equation

y = xn
when n is a non-negative integer, is given in Example 1

The variable y is initialized to 1 and then multiplied by x, n times using the while loop. The loop

control variable, count is initialized outside the loop and incremented inside the loop. When the

I & II Semester, Principles of Programming using C (BPOPS103/203)


RV Institute of Technology & Management®

value of count becomes greater than n, the control exists the loop.

I & II Semester, Principles of Programming using C (BPOPS103/203)


RV Institute of Technology & Management®

Program

main()
{
int count, n; float x, y;
printf("Enter the values of x and n : ");
scanf("%f %d", &x, &n);
y = 1.0;
count = 1; /* Initialisation */
/* LOOP BEGINs */
while ( count <= n) /* Testing */
{
y = y*x;
count++; /* Incrementing */
}
/* END OF LOOP */
printf("\nx = %f; n = %d; x to power n = %f\n",x,n,y);
}

Output

Enter the values of x and n : 2.5 4

x = 2.500000; n = 4; x to power n = 39.062500

Enter the values of x and n : 0.5 4

x = 0.500000; n = 4; x to power n = 0.062500

I & II Semester, Principles of Programming using C (BPOPS103/203)


RV Institute of Technology & Management®

Example 2

A program to print the multiplication table from 1 x 1 to 12 x 10 as shown below is given in


Example 2.

This program contains two do.... while loops in nested form. The outer loop is controlled by the
variable row and executed 12 times. The inner loop is controlled by the variable column and is
executed 10 times, each time the outer loop is executed. That is, the inner loop is executed a total
of 120 times, each time printing a value in the table.

I & II Semester, Principles of Programming using C (BPOPS103/203)


RV Institute of Technology & Management®

1 2 3 4 … 10
2 4 6 8 … 20

12 24 36 48 … 120

Program:

#define COLMAX 10

#define ROWMAX 12
main()
{

int row,column, y;
row = 1;
printf(" MULTIPLICATION TABLE \n");

printf(" \n");

do /*......OUTER LOOP BEGINS. */

column = 1;

do /* ...... INNER LOOP BEGINS. */

y = row * column;

I & II Semester, Principles of Programming using C (BPOPS103/203)


RV Institute of Technology & Management®

printf("%4d", y);
column = column + 1;

I & II Semester, Principles of Programming using C (BPOPS103/203)


RV Institute of Technology & Management®

while (column <= COLMAX); /*... INNER LOOP ENDS ...*/


printf("\n");
row = row + 1;

}while (row <= ROWMAX); /*..... OUTER LOOP ENDS */

printf(" \n");

Output

MULTIPLICATION TABLE

1 2 3 4 … 10
2 4 6 8 … 20

12 24 36 48 … 120

Example 3

The program in Example 3 uses a for loop to print the "Powers of 2" table for the power 0 to
20, both positive and negative.

The program evaluates the value


p=2n

I & II Semester, Principles of Programming using C (BPOPS103/203)


RV Institute of Technology & Management®

successively by multiplying 2 by itself n times.

1
q = 2-n = ----
p

Note that we have declared p as a long int and q as a double.

2.11 Break and continue statements


Loop control statements change execution from its normal sequence. When execution leaves a scope,
all automatic objects that were created in that scope are destroyed.

C supports the following control statements.

Sr.No. Control Statement & Description

1 break statement
Terminates the loop or switch statement and transfers execution to the
statement immediately following the loop or switch.

2 continue statement
Causes the loop to skip the remainder of its body and immediately retest
its condition prior to reiterating.

3 goto statement
Transfers control to the labeled statement.

Break Statement
In any loop break is used to jump out of loop skipping the code below it without caring about the test condition.

I & II Semester, Principles of Programming using C (BPOPS103/203)


RV Institute of Technology & Management®

It interrupts the flow of the program by breaking the loop and continues the execution of code which is outside the
loop.
The common use of break statement is in switch case where it is used to skip remaining part of the code.

Structure of Break statement

In while loop

while (test_condition)
{
statement1;
if (condition )
break;
statement2;
}

I & II Semester, Principles of Programming using C (BPOPS103/203)


RV Institute of Technology & Management®

In do…while loop

do
{
statement1;
if (condition)
break;
statement2;
}while (test_condition);

In for loop

for (int-exp; test-exp; update-exp)


{
statement1;
if (condition)
break;
statement2;
}

Now in above structure, if test_condition is true then the statement1 will be executed and again if the condition
is true then the program will encounter break statement which will cause the flow of execution to jump out of
loop and statement2 below if statement will be skipped.

Example: C program to take input from the user until he/she enters zero.

#include <stdio.h>
int main ()

I & II Semester, Principles of Programming using C (BPOPS103/203)


RV Institute of Technology & Management®

{
int a;
while (1)
{
printf("enter the number:");
scanf("%d", &a);
if ( a == 0 )
break;
}
return 0;
}

Explanation
In above program, while is an infinite loop which will be repeated forever and there is no exit from the loop.
So the program will ask for input repeatedly until the user will input 0.
When the user enters zero, the if condition will be true and the compiler will encounter the break statement
which will cause the flow of execution to jump out of the loop.

continue statement in C
Like a break statement, continue statement is also used with if condition inside the loop to alter the flow of
control.
When used in while, for or do...while loop, it skips the remaining statements in the body of that loop and
performs the next iteration of the loop.
Unlike break statement, continue statement when encountered doesn’t terminate the loop, rather interrupts a
particular iteration

I & II Semester, Principles of Programming using C (BPOPS103/203)


RV Institute of Technology & Management®

In while loop
while (test_condition)
{
statement1;
if (condition )
continue;
statement2;
}

In do…while loop
do
{
statement1;
if (condition)
continue;
statement2;
}while (test_condition);

In for loop

I & II Semester, Principles of Programming using C (BPOPS103/203)


RV Institute of Technology & Management®

for (int-exp; test-exp; update-exp)


{
statement1;
if (condition)
continue;
statement2;
}

Explanation
In above structures, if test_condition is true then the continue statement will interrupt the flow of control and
block of statement2 will be skipped, however, iteration of the loop will be continued.

Example: C program to print sum of odd numbers between 0 and 10

#include <stdio.h>
int main ()
{
int a,sum = 0;
for (a = 0; a < 10; a++)
{

if ( a % 2 == 0 )
continue;
sum = sum + a;
}
printf("sum = %d",sum);
return 0;
}

I & II Semester, Principles of Programming using C (BPOPS103/203)


RV Institute of Technology & Management®

goto statements:

The goto statement is known as jump statement in C. As the name suggests, goto is used to transfer the program
control to a predefined label. The goto statment can be used to repeat some part of the code for a particular
condition. It can also be used to break the multiple loops which can't be done by using a single break statement.
However, using goto is avoided these days since it makes the program less readable and complicated.

Syntax:
label:
//some part of the code;
goto label;

goto example
Let's see a simple example to use goto statement in C language.
#include <stdio.h>
int main()
{
int num,i=1;
printf("Enter the number whose table you want to print?");
scanf("%d",&num);

printf("%d x %d = %d\n",num,i,num*i);
i++;
if(i<=10)
goto table;
}

I & II Semester, Principles of Programming using C (BPOPS103/203)


RV Institute of Technology & Management®

The Infinite Loop


A loop becomes an infinite loop if a condition never becomes false. The for loop is traditionally used
for this purpose. Since none of the three expressions that form the 'for' loop are required, you can
make an endless loop by leaving the conditional expression empty.

#include <stdio.h>

int main () {

for( ; ; ) {

printf("This loop will run forever.\n");

return 0;

When the conditional expression is absent, it is assumed to be true. You may have an initialization
and increment expression, but C programmers more commonly use the for(;;) construct to signify
an infinite loop.
NOTE − You can terminate an infinite loop by pressing Ctrl + C keys

Additional Features of for Loop

The for loop in C has several capabilities that are not found in other loop constructs. For
example, more than one variable can be initialized at a time in the for statement.
The statements
p = 1;
for (n=0; n<17; ++n)

can be rewritten as

I & II Semester, Principles of Programming using C (BPOPS103/203)


RV Institute of Technology & Management®

for (p=1, n=0; n<17; ++n)


Program:
main()
{
long int p; intn; double q;
printf(" \n");
printf(" 2 to power n n 2 to power -n\n");
printf(" \n");
p = 1;
for (n = 0; n < 21 ; ++n) /* LOOP BEGINS */
{
if (n == 0)
p = 1;
else
p = p * 2;
q = 1.0/(double)p ;

printf("%10ld %10d %20.12lf\n", p, n, q);


} /* LOOP ENDS */
printf(" \n");
}

Output -----------------------

2 to power n n 2 to power -n

1 0 1.000000000000
2 1 0.500000000000
4 2 0.250000000000
8 3 0.125000000000
16 4 0.062500000000
32 5 0.031250000000

I & II Semester, Principles of Programming using C (BPOPS103/203)


RV Institute of Technology & Management®

64 6 0.015625000000

I & II Semester, Principles of Programming using C (BPOPS103/203)


RV Institute of Technology & Management®

128 7 0.007812500000
256 8 0.003906250000
512 9 0.001953125000
1024 10 0.000976562500
2048 11 0.000488281250
4096 12 0.000244140625
8192 13 0.000122070313
16384 14 0.000061035156
32768 15 0.000030517578
65536 16 0.000015258789
131072 17 0.000007629395
262144 18 0.000003814697
524288 19 0.000001907349
1048576 20 0.000000953674

Example 4

A class of n students take an annual examination in m subjects. A program to read the marks
obtained by each student in various subjects and to compute and print the total marks obtained
by each of them is given in Example 4.

The program uses two for loops, one for controlling the number of students and the other for
controlling the number of subjects. Since both the number of students and the number ofsubjects
are requested by the program, the program may be used for a class of any size and any number of
subjects.

The outer loop includes three parts:

2.10.1 reading of roll-numbers of students, one after another,

I & II Semester, Principles of Programming using C (BPOPS103/203)


RV Institute of Technology & Management®

2.10.2 inner loop, where the marks are read and totaled for each student, and

2.10.3 printing of total marks and declaration of grades.

Program:

#define FIRST 360

#define SECOND 240


main()
{

int n, m, i, j,

I & II Semester, Principles of Programming using C (BPOPS103/203)


RV Institute of Technology & Management®

roll_number, marks, total;

printf("Enter number of students and subjects\n");


scanf("%d %d", &n, &m);
printf("\n");

for (i = 1; i <= n ; ++i)

printf("Enter roll_number : ");


scanf("%d", &roll_number);
total = 0 ;

printf("\nEnter marks of %d subjects for ROLL NO %d\n", m,roll_number);


for (j = 1; j <= m; j++)

scanf("%d", &marks);
total = total + marks;
}

printf("TOTAL MARKS = %d ", total);


if (total >= FIRST)
printf("( First Division )\n\n");
else if (total >= SECOND)
printf("( Second Division )\n\n");
else
printf("( *** F A I L *** )\n\n");

Output

I & II Semester, Principles of Programming using C (BPOPS103/203)


RV Institute of Technology & Management®

E 3 6
n Enter roll_number : 8701
t
e
r
n
u
m
b
e
r
o
f
s
t
u
d
e
n
t
s
a
n
d
s
u
b
j
e
c
t

I & II Semester, Principles of Programming using C (BPOPS103/203)


RV Institute of Technology & Management®

Enter marks of 6 subjects for ROLL NO 8701


81 75 83 45 61 59

TOTAL MARKS = 404 ( First Division )

Enter roll_number : 8702

Enter marks of 6 subjects for ROLL NO 8702


51 49 55 47 65 41

TOTAL MARKS = 308 ( Second Division )

Enter roll_number : 8704

Enter marks of 6 subjects for ROLL NO 8704


40 19 31 47 39 25

TOTAL MARKS = 201 ( *** F A I L *** )

Example 5

The program in Example 5 illustrates the use of the break statement in a C program.

The program reads a list of positive values and calculates their average. The for loop is written
to read 1000 values. However, if we want the program to calculate the average of any set of values
less than 1000, then we must enter a 'negative' number after the last value in the list, to mark the
end of input.

Program

I & II Semester, Principles of Programming using C (BPOPS103/203)


RV Institute of Technology & Management®

main()

int m;

float x, sum, average;

printf("This program computes the average of a


set of numbers\n");

I & II Semester, Principles of Programming using C (BPOPS103/203)


RV Institute of Technology & Management®

printf("Enter values one after another\n");


printf("Enter a NEGATIVE number at the end.\n\n");
sum = 0;

for (m = 1 ; m <= 1000 ; ++m)

scanf("%f", &x);
if (x < 0)

break;

sum += x ;

average = sum/(float)(m-1);
printf("\n");

printf("Number of values = %d\n", m-1);


printf("Sum = %f\n", sum);
printf("Average = %f\n", average);

Output

This program computes the average of a set of numbers


Enter values one after another

Enter a NEGATIVE number at the end.


21 23 24 22 26 22 -1

Number of values = 6

I & II Semester, Principles of Programming using C (BPOPS103/203)


RV Institute of Technology & Management®

Sum = 138.000000

Average = 23.000000

Example 6

A program to evaluate the series


1

I & II Semester, Principles of Programming using C (BPOPS103/203)


RV Institute of Technology & Management®

------ = 1 + x + x2 + x3 + ........ + xn
1-x

for -1 < x < 1 with 0.01 per cent accuracy is given in Example 6. The goto statement is used
to exit the loop on achieving the desired accuracy.

We have used the for statement to perform the repeated addition of each of the terms in the series.
Since it is an infinite series, the evaluation of the function is terminated when the term x n reaches
the desired accuracy. The value of n that decides the number of loop operations is not known and
therefore we have decided arbitrarily a value of 100, which may or may not result in the desired
level of accuracy.

Program

#define LOOP 100

#define ACCURACY 0.0001

main()

int n;

float x, term, sum;

printf("Input value of x : ");


scanf("%f", &x);

sum = 0 ;

for (term = 1, n = 1 ; n <= LOOP ; ++n)

I & II Semester, Principles of Programming using C (BPOPS103/203)


RV Institute of Technology & Management®

sum += term ;

if (term <= ACCURACY)

goto output; /* EXIT FROM THE LOOP */


term *= x ;
}

printf("\nFINAL VALUE OF N IS NOT SUFFICIENT\n");


printf("TO ACHIEVE DESIRED ACCURACY\n");

I & II Semester, Principles of Programming using C (BPOPS103/203)


RV Institute of Technology & Management®

goto end;

output:

printf("\nEXIT FROM LOOP\n");

printf("Sum = %f; No.of terms = %d\n", sum, n);


end:
; /* Null Statement */

Output

Input value of x : .21


EXIT FROM LOOP
Sum = 1.265800; No.of terms = 7
Input value of x : .75
EXIT FROM LOOP

Sum = 3.999774; No.of terms = 34


Input value of x : .99
FINAL VALUE OF N IS NOT SUFFICIENT
TO ACHIEVE DESIRED ACCURACY

Example 7

I & II Semester, Principles of Programming using C (BPOPS103/203)


RV Institute of Technology & Management®

The program in Example 7 illustrates the use of continue statement.

The program evaluates the square root of a series of numbers and prints the results. The
process stops when the number 9999 is typed in.
In case, the series contains any negative numbers, the process of evaluation of square root should
be bypassed for such numbers because the square root of a negative number is not defined. The
continue statement is used to achieve this. The program also prints a message saying that the

I & II Semester, Principles of Programming using C (BPOPS103/203)


RV Institute of Technology & Management®

number is negative and keeps an account of negative numbers.

The final output includes the number of positive values evaluated and the number of negative
items encountered.

Program:
#include <math.h>
main()
{
int count, negative;
double number, sqroot;
printf("Enter 9999 to STOP\n");
count = 0 ;negative = 0 ;
while (count <= 100)
{
printf("Enter a number : ");
scanf("%lf", &number);
if (number == 9999)
break; /* EXIT FROM THE LOOP */

if (number < 0)
{
printf("Number is negative\n\n"); negative++ ;
continue; /* SKIP REST OF THE LOOP */
}
sqroot = sqrt(number);
printf("Number = %lf\n Square root = %lf\n\n", number, sqroot);
count++ ;
}
printf("Number of items done = %d\n", count);

I & II Semester, Principles of Programming using C (BPOPS103/203)


RV Institute of Technology & Management®

printf("\n\nNegative items = %d\n", negative);


printf("END OF DATA\n");
}

Output

Enter 9999 to STOP


Enter a number : 25.0
Number = 25.000000
Square root = 5.000000

I & II Semester, Principles of Programming using C (BPOPS103/203)


RV Institute of Technology & Management®

Enter a number : 40.5


Number = 40.500000
Square root = 6.363961
Enter a number : -9
Number is negative
Enter a number : 16
Number = 16.000000
Square root = 4.000000
Enter a number : -14.75
Number is negative
Enter a number : 80
Number = 80.000000
Square root = 8.944272
Enter a number : 9999
Number of items done = 4
Negative items =2
END OF DATA

END OF MODULE 2

I & II Semester, Principles of Programming using C (BPOPS103/203)


I & II Semester, Principles of Programming using C (BPOPS103/203)

You might also like