Professional Documents
Culture Documents
PIC - Module 2 - Part 1
PIC - Module 2 - Part 1
Syllabus
Fundamentals of C programming:
Flow of control is normally sequential. That is, when one statement is finished
executing, control passes to the next statement in the program. When we want the flow
of control to be nonsequential, we use control statements, special statements that
transfer control to a statement other than the one that physically comes next.
Structured high-level languages, such as C contain statements that can also alter
the flow of a sequence of instructions. These statements are called as control
statements. C provides two types of control statements.
1. Selection
2. Iteration
SELECTION STATEMENTS
if statement
The command says “if this condition is true” then perform the following
instructions. If the condition is false, the computer skips the instruction that is
part of the if command, and moves on to the next instruction in the program. The
statement part of the structure will be executed if and only if the expression is true. If
the expression is false, then the statement part of the structure will be ignored.
if (a >b ) a=a + 2;
b=a+2;
This if statement specifies that when the expression a > b is true, then execute
the statement a=a+2 and the statement b =a+2, otherwise, the control of program
should goto the statement immediately following it, that is b=a+2;
This statement causes the message to be printed only when the variable weight
has a value greater than 1000. C does allow you to take advantage of the fact that the
expression is evaluated as a number. If the expression evaluates to 0, it is false, and if
non-zero, the expression is evaluated as true.
Example: The expression that follows is a common statement in C but is not usually
found in other languages.
First, the expression calls the function getchar(), then the result is assigned to ch.
Finally, the value of ch is examined to see if it is equal to a newline character. The
parentheses are required because == has a higher precedence than = and you want the
assignment operator to take effect before the relational operator.
The message “FIRST CLASS” is written out if average greater than or equal to 60
or if the grade represents the character ‘A’ ( or if both conditions are true).
Program: Write a program to find the largest of two numbers.
#include<stdio.h>
main()
{
int a,b,big;
printf("Enter two numbers");
scanf("%d%d",&a,&b);
big=a;
if(big<b)
big=b;
printf("Largest of %d and %d is %d",a,b,big);
}
Program: In a readymade showroom 20 % discount will be given if the clothes worth Rs.
5000 is purchased, otherwise no discount is given. Write a C program to calculate the
net-amount and discount.
#include <stdio.h>
main()
{
float amount,discount,netamount;
printf("Enter sales amount");
scanf("%f",&amount);
discount=0; /* Initialize discount valueto zero */
if (amount >= 5000) discount=0.2;
discount = amount * discount;
netamount=amount - discount;
printf("\nAmount =%.2f",amount);
printf("\nDiscount= %.2f",discount);
printf("\nNet amount=%.2f",netamount);
}
Program: Write a C program to input principal amount and time. If time is more than 10
years, calculate the simple interest at the rate of 8%, otherwise calculate it at the rate of
12% per annum.
#include <stdio.h>
main()
{
int principal,time,rate;
float simple_interest;
printf("Enter the principal");
scanf("%d",&principal);
printf("Enter the time ");
scanf("%d",&time);
rate=12;
if(time>10) rate=8;
simple_interest =(long) principal * time*rate/100.0;
printf("SIfor%dyears=%.2f",time,simple_interest);
}
if-else statement
All the examples of if we have seen so far allow you to execute a set of
statements if a condition or expression evaluates to true. What if there is another course
of action to be followed if the expression evaluates to false. There is another form of if
that allows for this kind of either or condition by providing an else clause.
The general form of the if-else is
if (expression )
Format II Statement-1;
else
Statement-2;
If the expression is evaluated as true, i.e., a nonzero value, then Statement-1 is executed,
otherwise Statement-2 is executed. Notice that one statement or the other is always
executed, not both. Both the statements Statement- 1 and Statement-2 can be simple or
compound.
Example: Suppose you want to find the largest of two numbers use the following if
statement.
if (a>b)
printf("Largest number is %d",a);
else
printf("Largest number is %d",b);
Program: A program to check whether a number is even or odd.
#include<stdio.h>
main()
{
int num;
printf(“ Enter a number“);
scanf("%d",&num);
if(num % 2 == 0)
printf("Number is even");
else
printf("Number is odd");
}
Program: Write a C program to input choice(1 or 2). If choice is 1, print the area of a circle
otherwise print the circumference of circle. Accept the radius of circle from user.
#include <stdio.h>
#define PI 3.14157
main()
{
int choice;
float r,area,circumference;
printf("Circle problem Menu\n");
printf("1. Area of the circle\n");
printf("2. Circumference of the circle\n");
printf("Enter your choice ");
scanf("%d",&choice);
printf("Enter the radius of the circle ");
scanf("%f",&r);
if(choice==1)
{
area = PI * r *r;
printf("\nArea of the circle = %.2f",area);
}
else
{
circumference=2 * PI * r;
printf("Circumference of circle =%.2f",circumference);
}
}
Nested if statement
A if statement may itself contain another if statement inside it, then it is known
as nested if statement. One of the nested if statement is given below:
big=c;
else
else
if (b>c)
big=b;
else
big=c;
printf("Largest of %d,%d and %d = %d",a,b,c,big);
}
Program: Program to find the largest, second largest and smallest of three numbers.
#include<stdio.h> main()
{
int a,b,c,lar,small,seclar;
printf("Enter three numbers ");
scanf("%d %d %d",&a,&b,&c);
if (a > b)
{
lar=a;
small=b;
}
else
{
lar=b;
small=a;
}
if ( lar < c)
lar= c;
else
if (small > c) small=c;
printf("\n Largest number = %d’,lar);
printf("\n Smallest number =%d’,small);
seclar=(a+b+c) - (lar+small);
printf("\nSecond largest =%d",seclar);
}
else-if ladder
This construct is an extension of if-else structure. A general else-if ladder
selection construct is of the form:
#include<stdio.h>
main()
{
int marks;
printf("\nEnter marks");
scanf("%d",&marks);
if((marks<=100) && (marks>=70))printf("\nDistinction"); else
if(marks>=60) printf("\nFirstclass");
else if(marks>=50) printf("\nSecond class");
else if(marks >=40) printf("Pass class");
else printf("Fails");
}
#include <ctype.h>
The above program receives a character typed from the keyboard and tests
whether it is a letter or digit and prints out accordingly. These tests are done with the
help of character type functions.
The break statement at the end of each block signals the end of a particular case
and causes an exit from the switch statement, transferring the control to the statement
that follows the switch construct. The action of the switch can be represented
schematically as shown in below figure.
Example: Consider the above program where a student's grade is based on the value
of a test score using nested if statements. The preceding code could be rewritten using
a switch as :
int n;
n=marks/10; /* divide marks by 10 */
switch(n)
{
case 10 :
case 9 :
case 8 :
case 7 : printf("Distinction");
break;
if ( expression-1 )
Statements-1;
else
Statements-2;
1 is assigned to even if number is divisible by 2, and 0 otherwise. This can also be written
using ternary operator ( ? ) in any one of the following form
1. even=(number % 2==0) ? 1 : 0;
Where label is a user defined identifier and can appear either before or after goto. This
statement provides an unconditional jump to the statement indicated by the label. No
declaration is required for the label. The syntax of the label requires a colon (:) after the
label.
LOOPS
One of the methods with which it is possible for us to achieve high
performance using a computer is by repeating the execution of identical tasks on
different data. For example we may write a program to add two numbers. The program
would be more useful if it was able to perform the operation more than once. For
performing an operation just once it would be better to use a calculator or even pencil
and paper. However when we will have to perform the operation again and again many
times, the effort of using a calculator or pencil and paper would be tedious. A program
would save us many tedious calculations.
A loop is a program construct that causes a statement to be executed again and
again. The process of repeating the execution of a certain set of statements again and
again is termed as looping. C has several such statements that can be used to form loops
they are
i. while statement
ii. do-while statement
iii. for statement
The first two types of loops i.e., the while and do-while loops, are used in
situations when the programmer does not know exactly the number of executions. Thus,
the execution will be repeated until some condition is satisfied. for loop is normally used
when the number of repetitions is known in advance.
while statement
This structure is also called as the “pre-tested” looping statement. For this
statement two different things must be specified, the statements to be repeated and
the condition. In this structure the checking of a condition is done at the beginning. The
condition must be satisfied before the execution of the statements i.e., the set of
statements in the structure(block) is executed again and again until the test condition is
true. If the test condition becomes false control is transferred out of the
structure(block).
The general form of the while statement in C programming language is as follows
:
Syntax : Statement 1;
Statement 2;
……..
Statement n+1;
Example: count = 1;
while (count <= 5 )
{
printf ("%d\t", count);
count ++;
}
In this example count is initialsed to 1, the while loop is executed as long as
count is less than or equal to 5. The output is the value of count at the beginning of each
execution of the while loop : 1,2,3,4 and 5. The loop is executed five times.
Example: sum = 0;
count = 1;
while (count <= 10)
{
sum = sum + count;
count ++;
}
printf ("Total sum = %d ", sum);
The program first initializes the value of the variable sum to zero and the value
of the variable count to one. The statements inside the structure find the sum of all
numbers from 1 to 10. The calculated sum is stored in a variable, which is finally
displayed.
#include <stdio.h>
main()
{
long rev,n,num;
int digit;
printf("\nEnteranumber");
scanf("%ld",&num);
rev=0;
n=num;
while ( num != 0)
{
digit=num%10;
num=num/10;
rev = rev * 10 + digit;
}
printf("\nThe number is%ld",n);
printf("\nThe reverse is %ld",rev);
}
Program : Program to find the sum of the squares of following ten terms.
2, 5, 10, 17, 26, 37, 50, 65, 82, 101
#include <stdio.h>
main()
{
int sum,num,term;
sum =0;
num=1; /* Firstnumber */
while(num<= 10)
{
term=num*num+1;
sum=sum+term*term;
num=num+1; /* Nextnumber */
}
printf("Sum =%d \n ", sum);
}
OUTPUT
Sum = 26113
Program: Program to input the age of 100 employees and tell how many belong to the
age groups of :
a. 25 – 35
b. 36 – 50
c. > 50
#include <stdio.h>
main()
{
int count,age, fc=0, sc=0, tc=0; count=1;
while( count <=100)
{
printf("\nEnter the age of employee %d", count);
scanf(“%d”,&age);
if((age >=25) && (age <=35))
++fc; /* Incrementfirst category */
elseif((age>=36)&&(age<=50))
++sc; /* Increment second category */
else
++tc; /* Incrementthirdcategory */
++count; /* Nextemployee */
}
printf("\nNumberofemployeesbetween25–35is=%d",fc);
printf("\nNumberofemployeesbetween36–50is=%d",sc);
printf("\nNumberofemployeesgreaterthan50yearsis=%d",tc);
do-while statement
This structure is also called as the “post-tested” looping statement. For this
statement two different things must be specified, the statements to be repeated and
the condition. In this structure the checking of a condition is done at the end. The
condition must be satisfied for the execution of the statements after the first instance
i.e., the set of statements in the structure is executed again and again until the test
condition is true. If the test condition becomes false control is transferred out of the
structure.
The general form of the do-while statement in C programming language is as
follows:
do
Statements 1;
Statements 2;
……..
} while (test condition);
Statements n+1;
Example: prod = 1;
count = 1;
do
{
prod = prod * count;
count ++;
} while (count < = 100)
printf ("Total product = %d \n", prod);
The program first initializes the value of the variable prod to one and the value
of the variable count to one. The statements inside the structure find the product of all
numbers from 1 to 100. The calculated product is stored in a variable, which is finally
displayed.
Program: Program to generate the multiplication table for a number in a proper format.
#include <stdio.h>
main()
{
int result, num, count;
printf("\nEnter a number");
scanf("%d",&num);
printf(" \nThe table is");
count = 1;
do
{
result = num * count;
printf("\n%d *%d =%d",num,count,result);
++count ;
}while(count <= 10);
}
The number for which the table is generated is inputted. The count is set to
1. The result of the multiplication of the number and the count is then found. The output
is then displayed in a proper format. The process is then repeated ten times for
incremented values of count.
do
{
amt = amt * (1 + rate / 100);
++ year;
}while(year <=time);
CI=amt–prin;
printf("\n Interest earned =%.2f ",CI);
}
The principal amount, rate of interest and the time period is inputted to the
variables prin, rate and time. The year is set to 1 and the principal amount is copied to
the variable amt. The Interest for the first year is then calculated and added to the
amount. The process is then repeated for the given time period. Finally the compound
interest is calculated by subtracting the principal amount (prin) from the total amount
(amt) and the output is displayed.
for statement can be either used as the increment looping statement or the
decrement looping statement. The general form of the for statement in a programming
language is as follows:
for ( Expression 1; Expression 2; Expression 3 )
{
Statements 1;
Statements 2;
……..
}
statements n+1;
Where
1. Expression 1 represents the initialization expression.
2. Expression 2 represents the expression for the final condition.
3. Expression 3 represents the increment or decrement expression.
Example: The statement uses a for loop to print the numbers 1 through 10 down the
screen.
When the program first encounters the loop, it sets the value of repeatto 1. It
then checks the condition to see if the value of repeat is less than or equal to 10. Since
the condition is true, it will perform the instruction that is associated with the loop,
displaying the value of the variable.
Example: You can use a for loop without any instructions to place a timed pause in a
program:
Even though there is no instruction, the loop is repeated 1000 times, as the
variable named delay is incremented and then checked against the condition. This
repetition pauses the program before executing the next instruction.
Example: You can use for loop without any start value.
s=0;
for( ; s<=10 ; s++)
printf(“%d\n”,s);
s variable set to 0 before the looping statement, there’s no need to initialize it.
#include <stdio.h>
main()
{
int i,n;
printf("Enter the upper limit");
scanf("%d",&n);
for(i=1;i<=n;i++)
printf("%d\t",i);
}
Program: Program to calculate and print the sums of even and odd integers of
the first N natural numbers.
#include <stdio.h>
main()
{
int i,n, sum_even, sum_odd;
printf("Enter the upper limit");
scanf("%d",&n);
sum_even=0;
sum_odd =0;
for(i=1;i<=n;i++)
if( i % 2==0)
sum_even=sum_even + i;
else
sum_odd =sum_odd +i;
printf("\nThe sum of even integers=%d",sum_even);
printf("\nThe sumof odd integers=%d",sum_odd);
}
*
**
***
****
#include <stdio.h>
main()
{
int row,col;
for(row=1;row<=4;row++) /* outerloop */
{
for(col=1;col<=row;col++) /* innerloop */
printf(“*”);
printf(“\n”);
}
}
ii Infinite loops : If we do not use any expressions in a for statement then the loop
will run for an infinite amount of time. Such loops, which do not terminate are called as
infinite loops.
Example: for( ; ;)
printf(“ C programming”);
The loop will print the statement “ C programming “ forever (infinite loop).
1
2 3
4 5 6
7 8 9 10
#include <stdio.h>
main()
{
int row,col, k=1;
for(row =1;row<=4;row++) /* outerloop */
{
for(col=1;col<=row;col++) /* innerloop */
printf(“%d\t”,k++);
printf(“\n”);
}
}
Program: Program to generate the following output.
1 2 3 4 5
5 1 2 3 4
4 5 1 2 3
3 4 5 1 2
2 3 4 5 1
#include <stdio.h>
main()
{
int row,col;
long num=12345;
for(row = 1; row <=5 ; row++)
{
printf("%ld",num);
num=(num%10)*10000+ (num/10);
printf(“\n”);
}
}
Comma operator
By using the comma operator in an expression of a loop, we will be able to
combine two statements that are in the body of the loop into a single expression, which
then becomes the action of the loop. This leaves the body of the loop empty, allowing
us to use null statement as its body.
break statement
The break statement is used to terminate loops. It can be used within a while,
do-while or for statement. When break is encountered inside any loop, control
automatically passes to the first statement after the loop. This provides a convenient
way to terminate the loop if an error or other irregular condition is encountered. The
break statement is simply written as :
break;
continue statement
In some programming situations we want to take the control back to the
beginning of the loop, bypassing the statements inside the loop, which have not yet been
executed. When the keyword continue is encountered inside any loop, control
automatically passes to the beginning of the loop. The continue statement is simply
written as:
continue;
Program: Program to display all numbers from 1 to n, which are not divisible by 5.
exit() function
exit() is a standard library function that comes ready-made with the C compiler.
Its purpose is to terminate the execution of the program. break statement terminates
the execution of loop in which it is written, where as exit() terminates the execution of
the program itself. Let us consider the following program:
The above program accepts a number and tests whether it is prime or not. If the number is
divisible by any number from 2 to half of the number, the program displays a message that
the "number is not a prime" and exits from the program by exit() function. The exit() has
been defined under the header file stdlib.h which must be included in a program that uses
exit() function.