7.
Loops & Control
Constructs
1
Loops
Loop with “if” using goto and label
Example : Demonstrates use of if for iteration
#include <stdio.h>
int main()
{
int sum=0, i=1; /*declaration and
initialization combined*/
Step3: /*label- loop starts here*/
if (i<=10)
R. Subburaj, “Programming in C” © Vikas Publshing House Pvt. Ltd, New Delhi 2
Loops (Contd.)
{
sum= sum+i;
i=i+1;
goto step3;
}
printf(“sum of first 10 natural numbers=%d\n”,
sum);
}
Result:
sum of first 10 natural numbers=55
R. Subburaj, “Programming in C” © Vikas Publshing House Pvt. Ltd, New Delhi 3
for statement
for (exp1; exp2; exp3)
{statements; }
Note the keyword, the parentheses and
semicolons. No semicolon after exp3.
exp1, exp2 and exp3 are expressions.
exp1 – contains the initial value of an index
or a variable.
exp3 – contains the alteration to the index
after each iteration of the body of the for
statement.
R. Subburaj, “Programming in C” © Vikas Publshing House Pvt. Ltd, New Delhi 4
for statement (Contd.)
The body of the statement is either a single
statement or group of statements enclosed
within braces.
If a single statement has to be executed then
braces are not required.
exp2 – condition that must be satisfied if the
body of statements are to be executed.
An example of a for loop is given below:
for (i=0; i<5; i++)
printf(“%d”, i);
R. Subburaj, “Programming in C” © Vikas Publshing House Pvt. Ltd, New Delhi 5
Finding sum of first 10
natural numbers
int main()
{
int sum=0, i=0; /*declaration and initialization
combined*/
for (i=1; i<=10; i++) /*loop starts here*/
{
sum=sum+i;
}
printf(“sum of the first 10 natural
numbers=%d\n”, sum);
}
Result: sum of first 10 natural numbers=55
R. Subburaj, “Programming in C” © Vikas Publshing House Pvt. Ltd, New Delhi 6
Exercise
What change will you make if we want to
add 100 numbers and 1000 numbers ?
R. Subburaj, “Programming in C” © Vikas Publshing House Pvt. Ltd, New Delhi 7
Three Components of for
exp1 and exp3 are assignments or function calls.
exp2 is a relational expression. The three
expressions may not always be present.
However, even if an expression is not present,
the associated semicolon should be present.
For instance,
for (;exp2;)
{s1}
R. Subburaj, “Programming in C” © Vikas Publshing House Pvt. Ltd, New Delhi 8
Finding all even numbers
int main ()
{
int i=2;
for (; i<50; i+=2) /*loop starts here*/
{
printf(“%i is an even number\n”, i);
}
}
R. Subburaj, “Programming in C” © Vikas Publshing House Pvt. Ltd, New Delhi 9
Symbolic Constants
# define name constant
Not variables and hence they are not defined as
part of the declarations of variables.
Specified on top of the program before the
main()
Wherever the symbolic constant names appear
in the program, the compiler will replace them
with the corresponding replacement constants.
R. Subburaj, “Programming in C” © Vikas Publshing House Pvt. Ltd, New Delhi 10
Symbolic Constants (Contd)
#define LOW 100
#define UPPER 150
#define STEP 1
int main()
{
int num;
for (num=LOW; num<UPPER; num+=STEP)
/*loop starts here*/
{
if(num%3 == 0)
printf(“%i is evenly divisible by 3\n”, num);
}
}
R. Subburaj, “Programming in C” © Vikas Publshing House Pvt. Ltd, New Delhi 11
Nested for Loop
Example
for (i=1;i<=10; i++)
{
for (j=1; j<=5; j++)
{
for (k=1; k<=2; k++)
{
s1
}
}
}
R. Subburaj, “Programming in C” © Vikas Publshing House Pvt. Ltd, New Delhi 12
while loop
Subset of for loop
{
exp1;
while (exp2)
{
statements
exp3;
}}
R. Subburaj, “Programming in C” © Vikas Publshing House Pvt. Ltd, New Delhi 13
Generation of Multiplication Table
int main()
{ int a,b,product;
a=1;
b=0;
product=0;
printf(“Enter which table you want”);
scanf(“%d”, &b)’
while (a <=10)
{ product = a*b;
printf(“%2d X %d=
%3d\n”,a,b,product);
a++; }
}
R. Subburaj, “Programming in C” © Vikas Publshing House Pvt. Ltd, New Delhi 14
Reversing a number
#include <stdio.h>
int main()
{ long unsigned n, reverse;
printf(“enter the number to be
reversed\n”);
scanf(“%lu”, &n);
reverse=0;
while (n>0)
{ reverse=reverse*10+ (n%10);
n=n/10; }
printf(“Reversed number=%lu”, reverse);
}
R. Subburaj, “Programming in C” © Vikas Publshing House Pvt. Ltd, New Delhi 15
Structure of while
TRUE While FALSE
condition
STATEMENTS
STATEMENTS
R. Subburaj, “Programming in C” © Vikas Publshing House Pvt. Ltd, New Delhi 16
do…. while
DO
STATEMENTS
TRUE
While
condition
FALSE
R. Subburaj, “Programming in C” © Vikas Publshing House Pvt. Ltd, New Delhi 17
Example of do….while
#include <stdio.h>
#include<conio.h>
main()
{ int alpha=0;
do
{ printf (“\nenter upper case alphabet- enter 1 to
quit\n”);
if (alpha >=‘A’ && alpha<=‘Z’)
{ alpha=(alpha+32);
putch(alpha);
}
R. Subburaj, “Programming in C” © Vikas Publshing House Pvt. Ltd, New Delhi 18
Example of do….while
else
{ if(alpha==‘1’)
printf(“End of Session”);
else
printf(“\ninvalid entry; retry”);
}
}while(alpha!=‘1’);
}
R. Subburaj, “Programming in C” © Vikas Publshing House Pvt. Ltd, New Delhi 19
Linear Search
Algorithm
Declaration
array ia of size n, i = 0
item to be searched = x
found = false
do
if (ia[i] == x) then
found = true
else
i=i+1
while (i<= n – 1 && not found)
R. Subburaj, “Programming in C” © Vikas Publshing House Pvt. Ltd, New Delhi 20
Switch
• Enables multi-way decision making
• More powerful than if .. else
• Syntax of switch statement is given below.
switch (expression)
{
case constant or expression : statements
case constant or expression : statements
..
Default : statements }
Constant expressions following case should be
unique.
R. Subburaj, “Programming in C” © Vikas Publshing House Pvt. Ltd, New Delhi 21
Example of Switch
int main()
{ int a;
char ch = ‘c’;
while (ch==‘c’)
{ printf(“\nEnter a digit 0 to 9\n”);
scanf(“%d”,&a);
switch(a)
{ case 0:printf(“Zero\n”);
break;
R. Subburaj, “Programming in C” © Vikas Publshing House Pvt. Ltd, New Delhi 22
Example of Switch (contd.)
case 1:printf(“One\n”);
break;
case 2:printf(“Two\n”);
break;
case 3:printf(“Three\n”);
break;
case 4:printf(“Four\n”);
break;
case 5:printf(“Five\n”);
break;
case 6:printf(“Six\n”);
break;
R. Subburaj, “Programming in C” © Vikas Publshing House Pvt. Ltd, New Delhi 23
Example of Switch (contd.)
case 7:printf(“Seven\n”);
break;
case 8:printf(“Eight\n”);
break;
case 9:printf(“Nine\n”);
break;
default:printf(“Illegal character\n”); }
printf(“enter ‘c’ if you want to continue\n”);
printf(“or any other character to end\n”);
ch=getche();
if(ch!=‘c’)
printf(“End of Session”); } }
R. Subburaj, “Programming in C” © Vikas Publshing House Pvt. Ltd, New Delhi 24
Switch with char
char m;
switch(m)
{
case ‘a’ : s1;
break;
case ‘b’ : s2;
break ;
}
R. Subburaj, “Programming in C” © Vikas Publshing House Pvt. Ltd, New Delhi 25
SWITCH with char (contd.)
int op;
switch(op)
{
case ‘+’ : s1;
break;
case ‘/’ : s2;
break ;
}
R. Subburaj, “Programming in C” © Vikas Publshing House Pvt. Ltd, New Delhi 26
Break, Continue, Return
• Break causes the program to break from the loop that
encloses it and proceed to the next stage of the
program
• Continue causes resuming next iteration of the loop.
• Return may appear anywhere in the program
int main()
{ int a;
do
{ printf(“enter a number-enter 0 to end session\n”);
scanf(“%d”, &a);
if(a>20000)
{ printf(“you entered a high value-going out
of range\n”); break; }
R. Subburaj, “Programming in C” © Vikas Publshing House Pvt. Ltd, New Delhi 27
Break, Continue, Return (contd)
else
if(a>0)
printf(“you entered %d\n”, a);
if (a<0)
{ printf(“you entered a negative
number\n”);
continue;
}
}
while(a!=0);
printf(“End of session\n”);
R. Subburaj, “Programming in C” © Vikas Publshing House Pvt. Ltd, New Delhi 28
Result of program
Enter a number-enter 0 to end session
33
You entered 33
Enter a number-enter 0 to end session
-60
You entered a negative number
Enter a number-enter 0 to end session
45
You entered 45
Enter a number-enter 0 to end session
25000
You entered a high value-going out of range
End of session
* exit() function
R. Subburaj, “Programming in C” © Vikas Publshing House Pvt. Ltd, New Delhi 29
8. Arrays
30
Arrays
• User defined data type
• Contains data of the same type
• Array of integers, array of double etc.
A = {2,4,6,8}
A[0]=2
A[1]=4
A[2]=6
A[3]=8
R. Subburaj, “Programming in C” © Vikas Publshing House Pvt. Ltd, New Delhi 31
Array Declaration
Eg. double emp_age [100];
• allots memory size of 100 doubles
contiguously.
• If emp_age[0] is stored in location 1000 then
emp_age[n] will be stored in 1000 + n * 8 (size
of variable).
[100] is called subscript.
Initialization
Double emp_age[5] = {30.1, 31.1, 35.1, 36.1, 37.1];
Double emp_age[] = {30.1, ….. 37.1};
R. Subburaj, “Programming in C” © Vikas Publshing House Pvt. Ltd, New Delhi 32
Getting, storing and printing
ten integers
{ int s1[10];
int i;
printf(“Enter 10 integers \n”);
for (i=0; i<=9; i++)
{ scanf(“%d”, &s1[i]);
}
printf(“you have entered:\n”);
for (i=0; i<=9; i++)
{ printf(“%d\n”, sl[i]); }}
R. Subburaj, “Programming in C” © Vikas Publshing House Pvt. Ltd, New Delhi 33
Finding greatest number
and position in a Array
int main()
{ int a[5]={1,5,2,6,3};
int max=0, i, ind=0;
for(i=0; i<=4; i++)
{ if (a[i] > max)
{ max =a[i];
ind=i+1; }
}
printf(“maximum number=%d location=
%d\n”, max,ind);
}
R. Subburaj, “Programming in C” © Vikas Publshing House Pvt. Ltd, New Delhi 34
Strings
• String is an array of characters
• char name{25};
• scanf(“%s”, name);
• The syntax for gets is: gets(name);
puts(name);
puts (“Enter the word”);
• printf canbe used to print more than one variable and scanf to get
more than one variable at a time, in a single statement. However,
puts can output only one variable and gets can input only one
variable in one statement. In order to input or output more than
one variable, separate statements have to be written for each
variable. gets and puts are unformatted I/O functions
• Use <string.h> to use string related library functions
Eg. strlen(str) returns length of str.
R. Subburaj, “Programming in C” © Vikas Publshing House Pvt. Ltd, New Delhi 35
Palindrome
#define FALSE 0
int main()
{ int flag=1;
int right, left, n;
char w[50]; /* maximum width of string
50*/
puts(“Enter string to be checked for
palindrome”);
gets(w);
n=strlen(w)-1;
for ((left=0, right=n); left<=n/2; ++left,
--right)
{ if (w[left] !=w[right])
{ flag=FALSE; break; } }
R. Subburaj, “Programming in C” © Vikas Publshing House Pvt. Ltd, New Delhi 36
Palindrome
if (flag)
{ puts(w);
puts(“is a palindrome”);
}
else
printf(“%s is NOT a palidrome”);
}
R. Subburaj, “Programming in C” © Vikas Publshing House Pvt. Ltd, New Delhi 37
Multi-Dimensional Arrays
• Multi-dimensional Arrays are stored row by row
continuously.
int main()
{ int i,j;
int z[2][2];
int x[2][2] = {1,2,3,4};
int y[2][2] = {5,6,7,8};
for (i=0; i<=1; i++)
{ for (j=0; j<=1; j++)
{ z[i][j]=x [i][j] * y[i][j];
printf(“z[%d][%d]=%d\n”, i, j, z[i][j]);}
}
}
R. Subburaj, “Programming in C” © Vikas Publshing House Pvt. Ltd, New Delhi 38
Binary Search
Pre-condition : Data already sorted.
Algorithm for Binary Search
int a[n];
left = 0
right = n-1
found = false;
while (left<right)
{mid = (left+right)/2;
if (a (mid) = =x) found = true;
else
if (a(mid) < x) left = mid + 1;
else right = mid;}
if (found) print (“found”);
else print (“Not found”);
R. Subburaj, “Programming in C” © Vikas Publshing House Pvt. Ltd, New Delhi 39
9. Functions
40
Modular Programming Concept
MAIN
f1 f2 f3 f4
f11 f12 f21 f31
R. Subburaj, “Programming in C” © Vikas Publshing House Pvt. Ltd, New Delhi 41
Structured programming – Code
of good programming practices
Write only one statement per line
Coin meaningful names for constants, variables and functions
Use capitals for names of constants
Divide programs into functions
Each function performs one task
Each function must have atleast one comment statement
Skip a line between functions
Skip a line after declaration statements in the main function
as well as each function
R. Subburaj, “Programming in C” © Vikas Publshing House Pvt. Ltd, New Delhi 42
Structured programming – Code
of good programming practices
Bring clarity by skipping lines wherever required
Put only one brace on each line
Align all opening braces and closing braces
Indent as much as possible to bring out logical structure of
the program
Some of the program statements that could be indented are
body of function, body of loop, body of if..else statements
Indent each case in switch statement
Indent an item within a structure declaration.
R. Subburaj, “Programming in C” © Vikas Publshing House Pvt. Ltd, New Delhi 43
Three Parts of Function
A function consists of three parts :
a) Function Declaration
b) Function Definition
c) Function Call
R. Subburaj, “Programming in C” © Vikas Publshing House Pvt. Ltd, New Delhi 44
Function Declaration
return data – type function name
(formal argument 1, argument 2,…. ) ;
Example
float f1 (float arg 1, int arg 2);
void fun2 (float arg1, int arg2); /*void
means nothing*/
char fun3(float arg1, int arg2);
char fun4();
Also called function prototype.
R. Subburaj, “Programming in C” © Vikas Publshing House Pvt. Ltd, New Delhi 45
Function Call
• Function can be called directly or indirectly.
• Eg. Fun1(25);
sum = fin1(25);
• Function call made by passing actual
arguments.
• Function call must be in conformity with
function proto.
• Return type not to be specified.
R. Subburaj, “Programming in C” © Vikas Publshing House Pvt. Ltd, New Delhi 46
Function Definition
• Can be located anywhere.
• Consists of 2 parts –
• Function declarator or header
• Conforms to proto, no semicolon
• Function body
• Consists of local variables &
statements
R. Subburaj, “Programming in C” © Vikas Publshing House Pvt. Ltd, New Delhi 47
Algorithm for function add
main function
Step 1 define function add
Step 2 get 2 integers
Step 3 call add & pass the 2 values
Step 4 get the sum
Step 5 Print the value
Function Add
Step 1 get the values
Step 2 add them
Step 3 return the value to main function
R. Subburaj, “Programming in C” © Vikas Publshing House Pvt. Ltd, New Delhi 48
Program for adding
int main()
{ int a=0, b=0, sum=0;
int add(int x, int y); /*function declaration*/
printf(“enter 2 integers\n”);
scanf(“%d%d”, &a, &b);
sum=add(a,b); /*functon call*/
printf(“sum of %d and %d=%d”, a,b,sum); }
/* function definition*/
Int add (int c, int d) /* function declarator*/
{ int e;
e=c+d;
return e; }
R. Subburaj, “Programming in C” © Vikas Publshing House Pvt. Ltd, New Delhi 49
Function - Important Points
• Function declarator is a replica of the function
declaration
• The only difference is that the declaration in the calling
function will end with a semicolon and the declarator in
the called function will not end with a semicolon.
• The declarator must agree totally with the declaration
in the called function i.e.the return data type, the
function name, the argument type should all appear in
the same order.
• When the function encounters the closing brace }, it
returns control the calling program and returns to the
same place at which the function was called.
R. Subburaj, “Programming in C” © Vikas Publshing House Pvt. Ltd, New Delhi 50
A Function called many times
{ float a,b,c,d, sum1, sum2, sum3;
float add(float a, float b); /* function declaration*/
printf(“enter 2 float numbers\n”);
scanf(“%f%f”, &a, &b);
sum1 = add(a,b); /*function call*/
printf(“enter 2 more float numbers\n”);
scanf(“%f%f”, &c, &d);
sum2 = add(c,d); /* function call*/
sum3=add(sum1,sum2);
printf(“sum of %f and %f=%f\n”, a,b,sum1);
printf(“sum of %f and %f=%f\n”, c,d,sum2);
printf(“sum of %f and %f=%f\n”, sum1,sum2,sum3); }
/*function definition*/
float add (float c, float d) /* function declarator*/
{ float e;
e=c+d;
return e; }
R. Subburaj, “Programming in C” © Vikas Publshing House Pvt. Ltd, New Delhi 51
Calling multiple functions
Step 1 : get the number
Step 2 : if number is odd call the Reverse function
Step 3 : else multiply the number by 2
Step 4 : if number is evenly divisible by 3 call ADD-digits
Reverse Function
Step 1 : reverse = 0
Step 2 : while (number > 0)
reverse = reverse * 10 + (number % 10)
number = number/10
Step 3 : return (reverse)
R. Subburaj, “Programming in C” © Vikas Publshing House Pvt. Ltd, New Delhi 52
Calling multiple functions (Contd.)
ADD-digits function
Step 1 : sum = 0
Step 2 : while number > 0
sum = sum + (number % 10)
number = number / 10
Step 3 : return (sum)
Look at Example 44 in page 146.
R. Subburaj, “Programming in C” © Vikas Publshing House Pvt. Ltd, New Delhi 53
Scope rules for functions
Scope of the variable is local to the function,
unless it is global
Look at Example 45 in page 149.
To find the greatest number in an array,
look at Example 46 in page 151.
To reverse a string, look at Example 47 in
page 152.
R. Subburaj, “Programming in C” © Vikas Publshing House Pvt. Ltd, New Delhi 54
Return values
return (sum);
return v1;
return “true”;
return `Z’;
return 0;
return 4.0 + 3.0; etc.
return;
R. Subburaj, “Programming in C” © Vikas Publshing House Pvt. Ltd, New Delhi 55