Unit III
Unit III
UNIT-III
Iteration Statements or Loop: It is a process of repeating the same set of statements again and again until the
specified condition holds true.
Computers execute the same set of statements again and again by putting them in a loop.
The C language provides three iteration statements.
1. for loop
2. while loop
3. do-while loop
In general, loops are classified as:
1. Counter-controlled loops
2. Sentinel-controlled loops
1. Counter-controlled loops the number of iterations to be performed is known in advance. The counter-controlled
loop starts with the initial value of the loop counter and terminates when the final value of the loop counter is reached.
They are also known as definite repetition loops.
Syntax:
Initialization Expression;
do
{
Body of the loop
Updation Expression;
} while ( Test Condition);
Example 1: Write a program in C to calculate factorial of a given number use while loop.
#include < stdio.h>
#include<conio.h>
void main()
{
int n, fact, i;
clrscr() ;
printf(“Input an integer\n”);
scanf(“%d”, &n);
fact=1;
i=1;
{
fact=fact*i;
++i;
} while (i <= n);
printf(“Factorial = %d\n”, fact);
getch();
}
Example 2: Program to check whether the given number is prime or not.
# include<stdio.h>
# include<conio.h>
void main( )
{
int n, i=2,c=2; Output:
printf("Enter the number for testing (prime or not: "); Enter the number for testing (Prime or not): 5
scanf("%d", &n); 5 is prime.
do
{
if(n%i==0)
{
c++;
break;
}
i++;
} while (i<n);
if(c==2)
printf("%d is Prime Number",n);
else
printf("%d is not Prime number",n);
getch();
}
Example 3: Program to add numbers until user enters zero
#include <stdio.h>
#include <conio.h>
void main()
{
double number, sum = 0;
do
{
printf("Enter a number: ");
scanf("%lf", &number);
sum += number;
} while(number != 0.0);
printf("Sum = %.2lf",sum);
}
Jumping Statements
goto Statement
• A goto statement in C programming language provides an unconditional jump from the goto to a labelled
statement in the same function.
• In this syntax, label is an identifier. When, the control of program reaches to goto statement, the control of
the program will jump to the label: and executes the code below it.
This program calculates the average of numbers To calculate square root of a given number.
entered by user
#include<stdio.h
# include <stdio.h> #include<conio.h>
int main(){ #include<math.h>
float num,average,sum; void main()
int i,n; {
printf("Maximum no. of inputs: "); int x,y;
scanf("%d",&n); clrscr();
for(i=1;i<=n;++i) read:
{ printf(“Enter the number”);
printf("Enter n%d: ",i); scanf(“%d”,&x);
scanf("%f",&num); if(x<0)
if(num<0.0) goto read;
goto jump; y=sqrt(x);
sum=sum+num; printf(“Square root of number is %f”,y);
} getch();
jump: }
average=sum/(i-1);
printf("Average: %.2f",average);
return 0;
}
break Statement
• The break command allows you to terminate and exit a loop (that is, do, for, and while) or switch command
from any point other than the logical end.
• You can place a break command only in the body of a looping command or in the body of a switch command.
• The break keyword must be lowercase and cannot be abbreviated.
• In a looping statement, the break command ends the loop and moves control to the next command outside
the loop. Within nested statements, the break command ends only the smallest enclosing do, for, switch, or
while commands.
• In a switch body, the break command ends the execution of the switch body and gives control to the next
Syntax:
for(initialize ; test condition ; updation) /* outer loop */
{
for(initialize ; test condition ; updation) /* inner loop */
{
Pattern:
Examples: Write a program to display the stars as shown below
* 1 A
** 12 AB
*** 123 ABC
**** 1234 ABCD
***** 12345 ABCDE
*****
* ****
** ***
*** **
**** *
***** #include<stdio.h>
#include<stdio.h> #include<conio.h>
#include<conio.h> void main ()
void main () {
{ int row, column,space;
int row, column,space; for(row=5; row>=1; row--)
for(row=1; row<=5; row++) {
{ for(space=5;space>row-1;space--)
for(space=4;space>row-1;space--) {
{ printf(" ");
printf(" "); }
} for(column=1;column<=row; column++)
for(column=1;column<=row; column++) {
{ printf("*");
printf("*"); }
} printf( "\n");
printf( "\n"); }
} getch( );
getch( ); }
}
Write a program to display the pattern as below
* *******
*** *****
***** ***
******* *
#include<stdio.h>
#include<stdio.h> #include<conio.h>
#include<conio.h> void main ()
void main () {
{ int row, column,space;
int row, column,space; for(row=5; row>=1; row--)
for(row=1; row<=5; row++) {
{ for(space=5;space>row-1;space--)
for(space=5;space>row-1;space--) {
{ printf(" ");
printf(" "); }
} for(column=1;column<=row*2-1; column++)
for(column=1;column<=row*2-1; column++) {
{ printf("*");
printf("*"); }
} printf( "\n");
printf( "\n"); }
} getch( );
getch( ); }
}
FUNCTIONS
• Functions are subprograms which are used to compute a value or perform a task.
• They cannot be run independently and are always called by the main ( ) function or by some other function.
1. Library or built-in functions are used to perform standard operations eg: squareroot of a number sqrt(x), absolute
value fabs(x), scanf( ), printf( ), and so on. These functions are available along with the compiler and are used along
with the required header files such as math.h, stdio. h, string.h and so on at the beginning of the program.
2. User defined functions are self–contained blocks of statements which are written by the user to compute a value
or to perform a task. They can be called by the main() function repeatedly as per the requirement.
USES OF FUNCTIONS:
• Functions are very much useful when a block of statements has to be written/executed again and again.
• Functions are useful when the program size is too large or complex. Functions are called to perform each task
sequentially from the main program. It is like a top-down modular programming technique to solve a problem
• Functions are also used to reduce the difficulties during debugging a program
USER DEFINED FUNCTIONS:
• In C language, functions are declared to compute and return the value of specific data type to the calling
program.
• Functions can also be written to perform a task. It may return many values indirectly to the calling program
and these are referred to as void functions.
There are three steps for using a function
(a) Declaration or Prototype-: It is used to tell the compiler that a user defined functions is being used in the program.
Generally, it is done before the main function. The basic syntax of declaration or prototype is
Syntax:
return type Func_name (parameter list);
Example: 1
int add(int x, int y);
Example: 2
float square(float x);
(b) Definition-: It is used to code the function or implement the function. The actual code is written in this step.
Syntax
return_type function_name( parameter list )
{
body of the function
}
Function definition in C programming language consists of a function header and a function body. Here are all the parts
of a function:
Return Type: A function may return a value. The return type is the data type of the value the function returns. Some
functions perform the desired operations without returning a value. In this case, the return_type is the keyword void.
Function Name: This is the actual name of the function. The function name and the parameter list together constitute
the function signature.
Parameters: A parameter is like a placeholder. When a function is invoked, you pass a value to the parameter. This
value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the
parameters of a function. Parameters are optional; that is, a function may contain no parameters.
Function Body: The function body contains a collection of statements that define what the function does.
else
result = num2;
return result;
}
Function main():
• main() is the starting function for any C program. Execution commences from the first statement in the main
() function
• It returns nothing when we use void for return.
• It uses no parameter. But it may use two specific parameters
• Recursive call is allowed for main () function also
• The program execution ends when the closing brace of the in main is reached.
Calling-: Whenever we want to use a function, we have to call that function in the program. The syntax for calling of
a function are as follows
Function-name(parameter list);
Example
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
a=10; b=20;
add(a,b);
}
Complete Example are as follows
#include<stdio.h>
#include<conio.h>
int add(int x, int y);
void main()
{
int a,b;
a=10; b=20;
add(a,b);
}
int add(int x, int y)
{
int c;
c=x + y;
printf(“answer is %d”, c);
return c;
}
There are two ways that a C function can be called from a program. They are,
• Call by value
• Call by reference
Call by value:
• In call by value method, the value of the variable is passed to the function as parameter.
• The value of the actual parameter cannot be modified by formal parameter.
• Different Memory is allocated for both actual and formal parameters. Because, value of actual parameter is
copied to formal parameter.
Note:
• Actual parameter – This is the argument which is used in function call.
• Formal parameter – This is the argument which is used in function definition
Example 1: Find the larger value from two integer numbers using function.
#include< stdio.h>
#include< conio.h>
temp = *a;
*a = *b;
*b = temp;
}
Recursion:
A function that calls itself is known as recursive function and this technique is known as recursion in C programming.
Use of recursion function:
• Recursion functions are written less number of statements.
• Recursion is effective where terms are generated successively to compute value.
• Recursion is useful for branching process. Recursion helps to create short code that would otherwise be
impossible.
Following are the Example of the recursion where the program is used to compute the factorial of a given number.
Example 1: Write a program in C to find factorial of a number using recursion.
#include<stdio.h>
#include<conio.h>
int fact(int x)
{
int y;
if(x==0)
return 1;
y=x*fact(x-1);
return y;
}
void main()
{
int m,n,;
clrscr();
printf(“\nEnter the integer“);
scanf(“%d”,&m);
n=fact(m);
printf(“\nThe facorial is:-%d”,n);
getch();
}
Some Important Problem Solved
1. Write a C program to find sum of digits of positive number.
#include<stdio.h>
#include<conio.h>
void main ()
{
int i,n,digit,sum=0;
printf("\nEnter number");
scanf("%d",&n);
while(n>0)
{
digit=n%10;
sum=sum+digit;
n=n/10;
}
printf("\nSum of digit is %d",sum);
getch( );
}
2. Write a C program to find reverse of a given positive number.
#include<stdio.h>
#include<conio.h>
PRAMOD KUMAR (ASST. PROF.), CSE DEPT., HCST Page | 12
Ver 2.0
void main ()
{
int i,n,digit,rev=0;
printf("\nEnter number");
scanf("%d",&n);
while(n>0)
{
digit=n%10;
rev=rev*10+digit;
n=n/10;
}
printf("\nReverse of a number is %d",rev);
getch( );
}
3. Write a C program to find sum of natural number. (Hint 1,2,3, 4……n)
#include<stdio.h>
#include<conio.h>
void main ()
{
int i,n,sum=0;
printf("\nEnter number of terms of series");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
sum=sum+i;
}
printf("\nsum of natural number is %d",sum);
getch( );
}
4. Write a C program to find the given number is palindrome or not. (Hint. Reverse of number is same like 121,141,565
etc.)
#include<stdio.h>
#include<conio.h>
void main ()
{
int i,n,n1,digit,palin=0;
printf("\nEnter number of terms of series");
scanf("%d",&n);
n1=n;
while(n!=0)
{
digit=n%10;
palin=palin*10+digit;
n=n/10;
}
if(palin==n1)
{
printf("\nNumber is palindrome");
}
else
{
printf("\nNumber is not palindrome");
}
getch( );
PRAMOD KUMAR (ASST. PROF.), CSE DEPT., HCST Page | 13
Ver 2.0