0% found this document useful (0 votes)
0 views135 pages

POP Unit 2

This document covers Unit 2 of a programming course focused on decision control and looping statements in C. It includes explanations and examples of conditional branching statements (if, if-else, switch) and iterative statements (while, do-while, for), along with nested loops and break/continue statements. Additionally, it provides various programming exercises to reinforce the concepts discussed.

Uploaded by

chethanaaaa13
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)
0 views135 pages

POP Unit 2

This document covers Unit 2 of a programming course focused on decision control and looping statements in C. It includes explanations and examples of conditional branching statements (if, if-else, switch) and iterative statements (while, do-while, for), along with nested loops and break/continue statements. Additionally, it provides various programming exercises to reinforce the concepts discussed.

Uploaded by

chethanaaaa13
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/ 135

PRINCIPLES OF

PROGRAMMING IN C
22CS2ESPOP - UNIT 2
Prof. SNEHA S BAGALKOT
Assistant Professor, Dept. of CSE
UNIT – 2: Decision Control and Looping Statements
▪Introduction to Decision Control Statements

▪Conditional Branching Statements (if, if-else, if-else-if, switch)

▪Iterative Statements (while, do-while, for)

▪Nested Loops

▪Break and Continue Statements

▪Example Programs
Introduction to Decision Control Statements
• Programs seen till now were sequential in nature.
• In cases where we need to run only a selected set of statements
conditional processing helps.
• Helps to specify what statements to run what to skip.
• C supports two type of decision control statements:
▪Conditional type branching
▪Unconditional type branching
Conditional Branching Statements (if, if-else,
if-else-if, switch)
• Conditional branching statements help to jump from one part of the
program to another based on whether or not a condition is satisfied
or not.
▪if statement
▪if-else statement
▪if-else-if statement
▪switch statement
Branching Statements
Conditional branching statements
▪ if statement

▪ if-else statement

▪ if-else-if statement

▪ switch statement
if statement
• Simplest form of decision control statement
• Syntax:
#include<stdio.h>

int main()

int x=0;

if(x>0)

x++;

printf(“\n x=%d”, x);

}
#include<stdio.h>
void main()
{
int x = 20;
int y = 18;
if (x > y)
{
printf("x is greater than y");
}
}
O/p: x is greater than y
Eg: Check if a person is eligible to vote
#include<stdio.h>
void main()
{
int age;
printf("Enter the age\n");
scanf("%d",&age);
if(age>18)
printf("You are eligible\n");
}
Cascade-if
#include<stdio.h>
#include<conio.h>
void main()
{
char ch;
printf("Enter any key\n");
scanf("%c", &ch);
if(isalpha(ch)>0)
printf("User has entered a character\n");
if(isdigit(ch)>0)
printf("User has entered a digit\n");
if(ispunct(ch)>0)
printf("User has entered a punctuation mark \n");
if(isspace(ch)>0)
printf("User has entered a white space character\n");
}
if- else statement
• In case of if statement if the expression is true, a certain set of statements
are executed.
• If the expression of the if statement returns false, then we can guide the
compiler to execute a different set of statements using else.
• The expression is evaluated. If true, control is transferred to statement 1.
• If expression evaluates to false, control is transferred to statement 2.
• Either statement 1 or statement 2 will be executed but not both.
If-else statement
•Syntax:
• Example: to find largest of two numbers
#include<stdio.h>
main()
{
int a, b, large;
printf(“\n Enter the values of a and b:”);
scanf(“%d %d”, &a, &b);
if(a>b)
large=a;
else
large=b;
printf(“\n Large=%d”, large);
}
Eg: Check whether number is odd or even
#include<stdio.h>
void main()
{
int num;
printf("Enter the number\n");
scanf("%d", &num);
if(num%2==0)
printf("The number is even");
else
printf("The number is odd");
}
Eg: WAP to accept a character. If character is in
lower case, convert it to upper case and vice versa
#include<stdio.h>
void main(){
char ch;
printf("Enter any Alphabet\n");
scanf("%c",&ch);
if(ch>='A'&&ch<='Z'){
printf("The entered character is in upper case\n");
printf("In lower case it is %c", (ch+32));
}
else{
printf("The entered character is in lower case\n");
printf("In upper case it is %c", (ch-32));
}
}
Ref : Table of ASCII values
Ex: WAP to check if the entered
character is a vowel
#include<stdio.h>
void main(){
char ch;
printf("Enter a character\n");
scanf("%c", &ch);
if(ch=='a'||ch=='e'|| ch=='i'|| ch=='o'|| ch=='u'||ch=='A'||ch=='E'||
ch=='I'|| ch=='O'|| ch=='U')
printf("%c is a vowel\n", ch);
else
printf("%c is not a vowel\n",ch);
}
Eg: Profit or Loss
Eg: Pre-Increment, Post-Increment,
Pre-Decrement, Post-Decrement
Dangling Else Problem
• With nesting of if-else statements, we often encounter a problem known as
dangling else problem.
• This problem is created when there is no matching else for every if statement. In
such cases, C always pairs an else to the most recent unpaired if statement in the
current block.
Example:
if(a > b)
if(a > c)
printf(“a is greater than b and c\”);
else
printf(“a is not greater than b and c\n”);
Nested if… else statement
if( test condition 1)
{
if(test condition 2)
{
Statement 1;
}
else
{
Statement 2;
}
}
else
{
Statement 3;
}
Statement X;
C program to find largest of 3 numbers using nested if..else
void main()
{
int a=15,b=24,c=38;
if(a>b)
{
if(a>c)
{
printf("A is largest");
}
else
{
printf("C is largest");
}
}
else
{
if(b>c)
{
printf("B is largest");
}
else {
printf("C largest");
}
}
}
if-else-if statement
• Syntax:
if(test expression 1)
{
statement block 1;
}
else if(test expression 2)
{
statement block 2;
}

{
statement block x;
}
statement y;
Example: to test whether a number entered is positive, negative or equal to zero
#include<stdio.h>
main()
{
int num;
printf(“\nEnter any number:”);
scanf(“%d”,&num);
if(num==0)
printf(“the value is equal to zero”);
else if(num>0)
printf(“\n the number is positive”);
else
printf(“\n the number is negative”);
}
#include<stdio.h>
void main(){
int x, y;
printf("Enter two numbers\n");
scanf("%d%d", &x,&y);
if(x==y)
printf("The numbers are equal\n");
else if(x>y)
printf("%d is greater than %d", x, y);
else
printf("%d is lesser than %d", x, y);
}
Eg: Increment/Decrement Operator
Programs
▪ Write a C program to read an integer, check if its positive, if so increment
and print it.
▪ Write a C program to check if a given number is even or odd.
▪ Write a C program to read a character and check if it is a vowel or
consonant.
▪ Read 2 integers and check if they are equal or not.
▪ Check if given number is positive, negative or Zero.
▪ Find the largest of three integers.
Write a C program to read a character and
check if it is a vowel or consonant.
Read 2 integers and check if they are equal or not.

OUTPUT 1: OUTPUT 2:
Enter two numbers: 5 5 Enter two numbers: 2 8
5 and 5 are equal 2 and 8 are not equal
Write a C program to display the Grade as per the given table:
else if(marks>60 && marks<=70)
#include<stdio.h>
printf(“\n Grade is C”);
void main()
else if(marks>50 && marks<=60)
{
Marks Grade printf(“\n Grade is D”);
int marks;
> 90 O else if(marks>40 && marks<=50)
printf(“\n Enter the marks:”);
> 80 A printf(“\n Grade is E”);
scanf(“%d”, &marks);
> 70 B else
> 60 C
if(marks>90)
printf(“\n Grade is F”);
> 50 D printf(“\n Grade is O”);
}
> 40 E else if(marks>80 && marks<=90)
Else F printf(“\n Grade is A”);
OUTPUT:
else if(marks>70 && marks<=80)
Enter the marks: 70
printf(“\n Grade is B”);
Grade is C
Write a C program to simulate the Traffic signal.

OUTPUT:
Enter the colour of signal[r, y or g]: r
Red Signal: Stop

Enter the colour of signal[r, y or g]: y


Yellow Signal: Wait

Enter the colour of signal[r, y or g]: g


Green Signal: Go

Enter the colour of signal[r, y or g]: w


Invalid
Write a C program to check if given input is a
letter [A-Z, a-z], digit [0-9] or special
character.
OUTPUT:
Enter a character: S
Uppercase letter

Enter a character: r
Lowercase letter

Enter a character: 6
Digit

Enter a character: #
Special character
PROGRAM

An electricity board charges the following rates for the use of


electricity: for the first 200 units 80 paise per unit: for the next 100
units 90 paise per unit: beyond 300 units Rs. 1 per unit. All users are
charged a minimum of Rs. 100 as meter charge. If the total amount is
more than 400, then an additional surcharge of 15% of total amount
is charged. Write a program to read the name of the user, number of
units consumed and print out the charges.
Algorithm
Step 1: [Start]
Begin Step 5:[Calculate the amount]
Step 2: [Input customer name] amount = amount/100
Read name amount = amount+100
Step 3: [Input unit consumed] Step 6: [Check if amount is greater than 400
Read n then calculate additional charge of 15%]
Step 4: [Check units consumed to calculate the amount] if amount > 400 then
if n < = 200 calculate amount amount + amount * 15/100
amount = n*80 end if
otherwise check if n > 200 and n <= 300 then calculate Step 7: [Print total amount to be paid by the
customer]
amount = 200 * 80
Display amount
amount = amount +(n-200) *90
Step 8: [Finished]
otherwise calculate
Stop
amount =(n-300)*100
amount = amount+100*90
amount = amount+200*80
end if
Flowchart
#include<stdio.h>
void main()
{ else
char name[20]; {
int n; amount=(n-300)*100;
float amount; amount=amount+100*90;
amount=amount+200*80;
printf("Enter the consumer name\n"); }
scanf("%s", name); amount=amount/100; //To convert into Rupees
printf("Enter no. of units consumed \n");
scanf("%d",&n); amount=amount+100; // Additional 100 Rupees to be added
if(amount>400)
if (n<=200) {
{ amount=amount+amount*15/100;
amount=n*80; }
} printf("Total amount to be paid is %.2f Rs\n",amount);
else if(n>200 && n<=300) }
{
amount=200*80;
amount=amount+(n-200)*90;
}
Output
Enter the consumer name :

Bhagya

Enter no. of units consumed

275

Total amount to be paid is = 327.50


Switch Case
● A switch case statement is a multi-way decision statement.
● Switch statements are used:
● When there is only one variable to evaluate in the expression.
● When many conditions are being tested for
● Switch case statement advantages include:
● Easy to debug, read, understand and maintain
● Execute faster than its equivalent if-else construct
switch case
• Multi-way decision statement
• Syntax:
switch(variable)
{
case value1:
statement block1;
break;
case value2:
statement block2;
break;
……………..
case valuen:
statement blockn;
break;
default:
statement block;
break;
}
statement x;
Rules for switch case construct
• The control expressions that follows the keyword switch must be of integral
type.(i.e., int or any value-converted to an int)
• Each case label should be followed with a constant or a constant exp.
• Every case label must evaluate to a unique constant expression value.
• Case labels must end with a colon.
• Two case labels may have the same set of actions associated with them.
• Default label is optional and is executed only when the value of the exp does
not match with any labeled constant exp.
• Default label can be placed anywhere in the switch statement.
• There can be only one default label.
• C permits nested switch statements, i.e., a switch statement within another
switch.
Example:
char grade=‘C’;
switch(grade)
{
case ‘A’: printf(“\n Excellent”);
break;
case ‘B’: printf(“\n GOOD”);
break;
case ‘C’: printf(“\n Fair”);
break;
case ‘F’: printf(“\n Fail”);
break;
default: printf(“\n Invalid Grade”);
break;
}
// Program to classify a number as Positive, Negative or Zero

#include<stdio.h>
main()
{ // Program to print the day of the week
int num;
#include<stdio.h>
printf("\n Enter any number : ");
int main()
scanf("%d", &num);
{
if(num==0)
int day;
printf("\n The value is equal to zero");
printf(“\n Enter any number from 1 to 7 : “);
else if(num>0)
scanf(“%d”,&day);
printf("\n The number is positive");
switch(day)
else
{
printf("\n The number is negative");
case 1: printf(“\n SUNDAY”); break;
case 2 : printf(“\n MONDAY”); break;
}
case 3 : printf(“\n TUESDAY”); break;
case 4 : printf(“\n WEDNESDAY”); break;
case 5 : printf(“\n THURSDAY”); break;
case 6 : printf(“\n FRIDAY”); break;
case 7 : printf(“\n SATURDAY”); break;
default: printf(“\n Wrong Number”);
}
}
Comparison between the switch and if-else construct
Generalized switch statement Generalized if-else statement

switch(x) If(exp1)
{ {
case 1: // do this // do this
case 2: // do this }
case 3: // do this else if(exp2)
…….. {
default: // do this
// do this } else if(exp3)
} {
// do this
}
/*Write a program to demonstrate the use of /*Program to determine whether an entered character is a vowel or not.*/
switch statement without a break.*/
#include <stdio.h>
#include <stdio.h> int main()
main() {
{ char ch;
int option = 1; printf("\n Enter any character: ");
switch(option) scanf("%c", &ch);
{ switch(ch)
case 1: printf("\n In case 1"); {
case 2: printf("\n In case 2"); case 'A':
default: printf("\n In case default"); case 'a’: printf("\n % c is VOWEL", ch); break;
} case 'E':
return 0; case 'e’: printf("\n % c is VOWEL", ch); break;
} case 'I':
case 'i’: printf("\n % c is VOWEL", ch); break;
case 'O':
case 'o’: printf("\n % c is VOWEL", ch); break;
case 'U':
case 'u’: printf("\n % c is VOWEL", ch); break;
default: printf("%c is not a vowel", ch);
}
return 0;
}
Design and Develop a program to solve simple
computational problems using arithmetic
expressions and use of each operator leading to
simulation of a simple calculator.
Algorithm
Step 1: Start the program
Step 2: Read the two numbers and the operator
Step 3: Evaluate option based on the operator with case
statements
case ‘+’ : res = a + b
case ‘-’ : res = a - b
case ‘*’ : res = a * b
case ‘/’ : res = a / b
Step 4: if the entered case option is invalid code the print
“Wrong Choice”
Step 5: Print the res
Step 6: Stop the program
Flowchart
#include<stdio.h>
void main() case '/': if(b!=0)
{ res=a/b;
float a,b,res; else
char op; printf("Divide by zero error");
printf("Enter The Expression in form
of op1 operator op2\n"); break;
scanf("%f%c%f",&a,&op,&b);
switch(op)
{ default: printf("Illegal operator\n");
case '+': res = a + b; }
break; printf("Result is……\n");
case '-‘: res = a-b;
break; printf("%f%c%f=%f",a,op,b,res);
case '*‘: res = a*b; }
break;
OUTPUT
Enter The Expression in form of
op1 operator op2 :
4+5
Result is …….
4+5=9
Advantages of using a switch case statement
▪ Easy to debug

▪ Easy to read and understand

▪ Ease of maintenance as compared with its equivalent if-else


statements

▪ Like if-else statements, switch statements can also be nested

▪ Executes faster than its equivalent if-else construct


Write a C program using control statements for the following
1. To find largest of two numbers
2. To find maximum of three numbers
3. To check whether a number is positive, negative or zero
4. To print Number of Days in any Month entered by user
5. To check if a number entered is even or odd
6. Read a year as input and find out if it is a leap year or not
7. Read sides of triangle from the user and check if it is isosceles , equilateral
or scalene
8. Check if an entered character is vowel or consonant using i) switch ii) if
9. Check if entered number is divisible by 3 or 5 or not
Iterative Statements (while, do-while, for)
• Iterative statements are used to repeat the execution of a list of statements,
depending on the value of an integer expression.
• C language supports three types of iterative statements also known as
looping statements.
• They are :
• while loop
• do-while loop
• for loop
While Loop
• The while loop is used to repeat one or more statements while a particular
condition is true.
• In the while loop, the condition is tested before any of the statements in the
statement block is executed.
• If the condition is true, only then the statements will be executed otherwise the
control will jump to the immediate statement outside the while loop block.
• We must constantly update the condition of the while loop.

while (condition)
{
statement_block;
}
statement x;
While Loop
• A while loop in C programming
repeatedly executes a set of
statements as long as a given
condition is true
• When the condition is false the
loop will stop working
• SYNTAX:
while(expression)
{
Statements;
}
Program to print the numbers from 10 to
19
Output
#include <stdio.h>
int main () { value of a: 10
int a = 10; value of a: 11
while( a < 20 ) { value of a: 12
printf("value of a: %d\n", a); value of a: 13
a++; value of a: 14
} value of a: 15
return 0; value of a: 16
} value of a: 17
value of a: 18
value of a: 19
Do While Loop
● The do-while loop is similar to the while loop. The only difference is that in a
do-while loop, the test condition is tested at the end of the loop.
● The body of the loop gets executed at least one time (even if condition is
false).
● Test condition is enclosed in parentheses and followed by a semicolon.
● Statements in the statement block are enclosed within curly brackets.
● The do while loop continues to execute whilst a condition is true. There is no
choice whether to execute the loop or not. Hence, entry in the loop is
automatic there is only a choice to continue it further or not.
● The major disadvantage of using a do while loop is that it always executes at
least once, so even if the user enters some invalid data, the loop will execute.
● Do-while loops are widely used to print a list of options for a menu-driven
program.
Do While Loop

Statement x

Statement x; Statement Block

do
{ Update the condition expression
statement_block;
} while (condition); TRUE

Condition
statement y;
FALSE

Statement y
Program to print the value of a from 10 to 19
using do while
#include <stdio.h> value of a: 10
value of a: 11
int main () {
value of a: 12
int a = 10;
value of a: 13
do { value of a: 14
printf("value of a: %d\n", a); value of a: 15
a = a + 1; value of a: 16
}while( a < 20 ); value of a: 17
return 0; value of a: 18
value of a: 19
}
Program to demonstrate the use of while loop and do-while loop.
// Program to print numbers from 0 to 10 //Program to print numbers from 0-10
using while loop using do-while loop

#include<stdio.h> #include<stdio.h>
int main() int main()
{ {
int i = 0; int i = 0;
while(i<=10) do
{ {
printf(“\n %d”, i); printf(“\n %d”, i);
i = i + 1; // condition updated i = i + 1;
} } while(i<=10);
} }
for loop
● For loop is used to repeat a task until a particular condition is true.
● Aka determinate or definite loop-programmer knows exactly how many times
the loop will repeat.

● The syntax of a for loop

for (initialization; condition; increment/decrement/update)


{
statement block;
}
Statement Y;
for loop
• When a for loop is used, the loop variable is initialized only once.
• With every iteration of the loop, the value of the loop variable is updated and the
condition is checked. If the condition is true, the statement block of the loop is
executed else, the statements comprising the statement block-skipped and the
control jumps to the immediate statement following the for loop body.
• Updating the loop variable may include incrementing the loop variable,
decrementing the loop variable or setting it to some other value like, i +=2, where
i is the loop variable.
• Every section of for loop is separated from the other with semicolon.
• It is possible that one of the sections may be empty, though the semicolons still
have to be there.
• If condition is empty, it is evaluated as true and the loop will repeat until
something else stops it.
• Condition is tested before the statements contained in the body are executed.
Points to remember about for loop
• In for loop, any or all exp can be omitted, then there must be two semicolon.
• No semicolon after a for statement.
• Multiple initializations must be separated with a comma.
• If no initialization to be done, can be skipped by giving only semicolon.
• Multiple conditions can be tested by using logical operators(&& or ||)
• If loop controlling variable is updated within statement block, then third part can be
skipped.
• Multiple statements can be included in the third part of the for by using comma.
• Controlling variable can also be incremented or decremented by values other than 1.
• If for loop with two semicolons, then for loop may become infinite loop if n
stopping condition is specified.
• Don’t use floating point variable as the loop control variable.
Program to print first n numbers using a for loop.

#include<stdio.h>
int main()
{
int i, n;
printf(“\n Enter the value of n :”);
scanf(“%d”, &n);
for(i=0; i<= n; i++)
printf(“\n %d”, i);

}
Examples
1. for(i=1; i<=3;i++)
{ 2. for(i=0; i<5;i++)
printf(“Welcome\n”); {
} printf(“%d\t”,i);
printf(“This is CSE”); }
Output: Output:
Welcome 0 1 2 3 4
Welcome
Welcome
This is CSE
3. for(i=5; i>0;i--)
{
printf(“%d\t”,i); 5. for(i=0; i<5;i++);
} {
Output: printf(“Hello\n”);
5 4 3 2 1
}
4. for(; ;) Output:
{ Nothing is printed
printf(“Infinite Loop\n”); Since there is a semicolon
} at the end of the loop
Prints “Infinite Loop” infinitely
without halting
Selecting an appropriate loop

• Loops can be entry-controlled(AKA pre-test) or exit-controlled(AKA


post-test).

Entry-controlled(Pre-test) Exit-controlled(Post-test)
Condition is tested before the Condition is tested after the
loop starts. loop is executed.
If the condition is not met, thenThe body of the loop is
loop will never execute. executed unconditionally for
the first time.
Can use either for or while loop Can use do-while.
Selecting an appropriate loop

Counter-controlled Loop Sentinel-controlled Loop


When we know in advance the When we do not know in
number of times the loop advance the number of times
should be executed. the loop will be executed.
Counter is a variable that must A special value called sentinel
be initialised, tested, and value is used to change the loop
updated for performing the loop control expression from true to
operations. false.
AKA definite repetition loop AKA indefinite repetition loop
Can use for loop Can use either while or
do-while loop
Nested Loops
• C allows users to have nested loops, i.e., loops that can be placed inside
other loops.
• This feature will work with any loop such as while, do-while, and for.
• It is most commonly used with for loop, because this is easiest to control.
• A for loop can be used to control the number of times that a particular set of
statements will be executed.
• Another outer loop could be used to control the number of times that a
whole loop is repeated.
• In C, Loops can be nested to any desired level.
WAP to print the following pattern. WAP to print the following pattern.
1 1
12 12
123 123
1234 1234
#include <stdio.h>
#include <stdio.h> main()
main() {
{ int i, j, k;
int i, j; for(i=1;i<=4;i++)
for(i=1;i<=4;i++) {
{ for(k=4;k>=i;k--)
printf("\n"); printf(" ");
for(j=1;j<=i;j++) for(j=1;j<=i;j++)
printf("%d", j); printf("%d", j);
} printf("\n");
return 0; }
} return 0;
}
Break Statement
● The break statement is used to terminate the execution of the nearest
enclosing loop in which it appears.
● When compiler encounters a break statement, the control passes to the
statement that follows the loop in which the break statement appears.
● Syntax: break;
● In switch statement if the break statement is missing then every case from
the matched case label to the end of the switch, including the default, is
executed.
● Break statement is used to exit a loop from any point within its body,
bypassing its normal termination expression.
Continue Statement
For example,
• The continue statement can only appear in
#include<stdio.h>
the body of a loop.
• When the compiler encounters a continue void main()
statement then the rest of the statements in {
the loop are skipped and the control is int i;
unconditionally transferred to the for(i=1; i<= 10; i++)
loop-continuation portion of the nearest {
enclosing loop. if (i==5)
• Syntax: continue; continue;
• If placed within a for loop, the continue printf("\t %d", i);
statement causes a branch to the code that }
updates the loop variable. }

Output: 1 2 3 4 6 7 8 9 10
Goto Statement
• The goto statement is used to transfer control to a specified label.
• Here label is an identifier that specifies the place where the branch is to be
made.
• Label can be any valid variable name that is followed by a colon (:).
• Label is placed immediately before the statement where the control has to be
transferred.
• Label can be placed anywhere in the program either before or after the goto
statement. Whenever the goto statement is encountered the control is
immediately transferred to the statements following the label.
• Goto statement breaks the normal sequential execution of the program.
• If the label is placed after the goto statement then it is called a forward
jump and in case it is located before the goto statement, it is said to be a
backward jump.
• It is often combined with the if statement to cause a conditional transfer of
control.
Write a C program to find sum of 10
natural numbers using goto
#include<stdio.h>
void main()
{ Output :
int sum=0,i=0; Sum= 55
top : sum= sum+i;
i++;
if(i<=10)
goto top;
printf("sum = %d",sum);
}
Goto Statement (Contd..)
Example: Program to calculate the sum of all +ve nos. entered by the user.
#include<stdio.h>
int main() {
int num, sum=0;
read: // label for go to statement
printf("\n Enter the number. Enter 999 to end : ");
scanf("%d", &num);
if (num != 999)
{
if(num < 0)
goto read; // jump to label- read
sum += num;
goto read; // jump to label- read
}
printf("\n Sum of the numbers entered by the user is = %d", sum);
return 0;
}
Example Programs
Write a program to demonstrate menu
based calculator using switch
#include<stdio.h>
case 3: product=a*b;
void main() printf("product of %d and %d is %d",a,b,product);
{ break;
int a ,b,choice,sum,diff,product,q,r; case 4: if(b==0)
printf("Welcome \n 1. ADDITION \n 2.SUBTRACTION \n {
3.MULTIPLICATION \n 4.DIVISION \n "); printf("division by zero not possible");
printf("Enter your choice :"); }
scanf("%d",&choice); else
{
printf("enter the two operands");
q=a/b;
scanf("%d%d",&a,&b);
r=a%b;
switch(choice) printf("Quotient when %d divided by %d is %d",a,b,q);
{ printf("\n Remainder when %d divided by %d is
case 1: sum=a+b; %d",a,b,r);
printf("Sum of %d and %d is %d",a,b,sum); }
break;
break;
}
case 2: diff=a-b; }
printf("Difference between %d and %d is %d",a,b,diff);
break;
Write a program to accept a name and print
the name for a specified number of times
#include<stdio.h>
void main()
{
char name[30]; enter name
int n ,i=0; jim
printf("enter name \n"); enter the number
scanf("%s",name); of times to print
printf("enter the number of times to print the name \n");
the name
scanf("%d",&n); 3
while(i<n) name is : jim
{ name is : jim
printf("name is : %s \n",name); name is : jim
i++;
}
}
Display all numbers in a given range of m to
n
// Using while loop
#include<stdio.h>
void main()
{
int m,n;
printf("Enter the value of m & n");
scanf("%d%d",&m,&n);
while(m<=n)
{
printf("\n %d",m);
m++;
}
}
Display all even numbers from a given range
of m to n
// Using while loop
#include<stdio.h>
void main()
{
int m,n;
printf("Enter the value of m & n");
scanf("%d%d",&m,&n);
while(m<=n)
{
if((m%2)==0)
printf("\n %d",m);
m++;
}
}
Compute and print the sum of natural
numbers from m to n
void main()
{
int m,n,sum=0;
printf("Enter the value of m & n");
scanf("%d%d",&m,&n);
while(m<=n)
{
sum=sum+m;
m++;
}
printf("sum is %d",sum);
}
Use do-while loop to print squares of first n
natural numbers
void main()
{
int n,i=1,s;
printf("enter n");
scanf("%d",&n);
do
{
s=i*i;
printf("\n square of %d is %d",i,s);
i++;
}while(i<=n);
}
Sample Output
C program to print the following pattern

*
**
***
****
*****
void main()
{
int i,j;
*
for(i=1;i<=5;i++)
**
{
***
printf("\n");
****
for(j=1;j<=i;j++) *****
printf("*");
}
}
Program to compute factorial of a given
number
void main()
{
int i, num,fact=1;
printf("Enter any number to calculate factorial: ");
scanf("%d", &num);
if(num==0)
fact=1;
else
{
for(i=1; i<=num; i++)
{
fact = fact * i;
}
}
printf("Factorial of %d = %d", num, fact);
}
C program to print reverse of a number
#include<stdio.h>
void main()
{
int num, reverse = 0,digit;
printf("Enter any number to find reverse: ");
scanf("%d", &num);
while(num != 0)
{
digit = num % 10;
reverse = (reverse * 10) + digit;
num /= 10;
}
printf("Reverse = %d", reverse);
}
Program to check if an entered number is
palindrome or not
if(rev == num)
void main()
{ {
int n, num, rev = 0; printf("%d is palindrome.", num);
printf("Enter any number to }
check palindrome: "); else
scanf("%d", &n); {
num=n; printf("%d is not palindrome.",
while(n != 0) num);
{ }
rev = (rev * 10) + (n % 10);
}
n /= 10;
}
Program to read a number and print the
sum of digits in a number (using while loop)
#include<stdio.h>
void main()
{
int n, sum=0, digit;
printf("Enter a number: ");
Output:
scanf("%d", &n);
Enter a number: 512
while(n != 0)
{ Sum = 8
digit = n % 10;
sum = sum + digit;
n = n / 10;
}
printf(“Sum=%d”,sum);
}
Check if given number is divisible by 3 or 5 or not
Print the number of days in the given month
#include<stdio.h>
void main()
{
int n;
printf("\n Enter a number for month[1 to 12]: ");
scanf("%d", &n);
if(n==4 || n==6 || n==9 || n==11)
printf("\n There are 30 days in the month");
else if (n==2)
printf("\n There are either 28 or 29 days in the month");
else if (n==1 || n==3 || n==5 || n==7 || n==8 || n==10 || n==12)
printf("\n There are 31 days in the month");
else
printf("\n Invalid Input");
}
Write a C program to find out if a triangle is equilateral or
isosceles given the 3 sides of the triangle. Use Logical
operator

Hint :

If a, b, c are the three sides of a triangle ,then the condition is


If(a==b) &&(b==c) &&(c==a) Then the triangle is called equilateral
triangle
If(a==b) II(b==c) II (c==a) Then the triangle is called isosceles triangle
Display the largest and smallest of two numbers
using ternary operator
Program to print the even and odd numbers
Write a C program to find sum of given
series using while loop (1+2+3+… +n)
#include<stdio.h>
void main()
{ Output
int n ,sum=0,i=0; enter n : 4
printf("enter n : ");
scanf("%d",&n);
sum of the series
while(i<=n)
is 10
{
sum = sum+i;
i++;
}
printf("sum of the series is %d",sum);
}
Write a C program to find sum of
given series using while loop
(1^2+2^2+3^2+… +n^2)
// Using while loop
#include<stdio.h>
void main()
{
int n ,sum=0,i=0;
printf("enter n : ");
scanf("%d",&n);
while(i<=n)
{
sum = sum+i*i;
i++; Output
} enter n : 4
printf("sum of the series is %d",sum);
} sum of the series is 30
Write a C program to read inputs till 0
and find their sum
#include<stdio.h>
void main()
{
int n ,sum=0,i=0;
while(n!=0)
{
printf("enter number[ 0 to stop] : ");
scanf("%d",&n);
sum = sum+n;
}
printf("sum of the numbers is %d",sum);
}
Program to generate right triangle pattern
Program to generate Pyramid pattern
Program to find the sum of even and odd numbers
Write a C program to generate a fibonacci series
for a user entered value of n using for loop
#include<stdio.h>
for(i=3;i<=n;i++)
int main()
{
{ fib3=fib1+fib2;
int n,fib1=0,fib2=1,i,fib3; printf("\t %d", fib3);
fib1= fib2;
printf("enter n"); fib2=fib3;
}
scanf("%d",&n);
}
if(n<2)
return 0;
{ }
printf("fibonacci series does not exist"); OUTPUT
} enter n : 9
else
Fib series : 0 1 1 2 3 5 8 13 21
{
printf(" \n Fib series : %d \t %d ",fib1,fib2);
LAB PROGRAM 4

Develop a C program to print the sum of


even numbers from M to N.
// Using for loop
#include<stdio.h>
void main()
{
int m,n,i,sum=0;
printf("Enter the Range ");
scanf("%d%d",&m,&n);
for(int i=m;i<=n;i++)
{
if((i%2)==0)
{
sum=sum+i;
}
}
printf("\n The sum of all even numbers is %d",sum);
}
//Using while loop
#include<stdio.h>
void main()
{
int m, n, sum=0;
printf("Enter the value of m & n ");
scanf("%d%d",&m, &n);
while(m<=n)
{
if (m%2 == 0)
sum=sum + m;
m++;
}
printf("sum is %d", sum);
}
LAB PROGRAM 5

Develop a C program to sum the series


1+1/2+1/3+ …. 1/N.
#include<stdio.h>
void main()
{
int n;
float sum=0.0,i,n1;
printf("Enter the value of n ");
scanf("%d", &n);
for(i=1.0; i<=n; i++)
{
n1=1.0/i;
sum=sum+n1;
}
printf("The sum of the series is 1/1 + 1/2 +1/3...1/%d= %f", n, sum);
}
LAB PROGRAM 6

Develop a C program to compute the GCD of


two numbers.
#include<stdio.h>
void main() while(divisor)
{ {
int n1,n2,dividend,divisor,remainder;
printf(“Enter 2 numbers "); remainder=dividend % divisor;
scanf("%d%d",&n1,&n2); dividend=divisor;
if(n1>n2) divisor=remainder;
{
dividend=n1; }
divisor=n2; printf("\n GCD of %d and %d is
} =%d",n1,n2,dividend);
else{
dividend=n2;
divisor=n1; }
}
Ex: n1=25, n2=60
Sample Output
Tracing for GCD
Input n1= 25, n2=60
25>60 [False]
So, dividend=60, divisor=25 Iteration 3
Iteration 1 5 != 0 [True]
25 != 0 [True]
rem= 10 % 5 = 0
rem= 60 % 25 = 10
dividend = 25 dividend = 5
divisor = 10 divisor = 0
Iteration 2 Iteration 4
10 != 0 [True]
0 != 0 [False]
rem= 25 % 10 = 5
dividend = 10
divisor = 5 Therefore GCD=dividend = 5
Program to compute lowest common
Multiple(LCM) of two integer numbers

LCM(n1,n2)= (n1*n2) / GCD(n1,n2)


Code Modified to find LCM of 2 numbers using GCD
#include<stdio.h>
void main()
{ while(divisor)
int n1,n2,dividend,divisor,remainder,lcm; {
printf("enter 2 numbers"); remainder=dividend % divisor;
scanf("%d%d",&n1,&n2); dividend=divisor;
if(n1>n2) divisor=remainder;
{ }
dividend=n1; lcm=(n1*n2)/dividend;
divisor=n2; printf("\n GCD of %d and %d is
} =%d",n1,n2,dividend);
else{ printf("\n LCM of %d and %d is
dividend=n2; =%d",n1,n2,lcm);
divisor=n1; }
}
Program to classify if a given number as
prime or composite
int main() if(flag==0)
{ {
int i, num, flag=0; printf("%d is prime number", num);
printf("Enter any number to check prime: "); }
scanf("%d", &num); else
for(i=2; i < num/2; i++) {
{ printf("%d is composite ", num);
if(num % i==0) }
{ }
flag = 1;
break;
}
}
Write a C program to check if a
number is Armstrong or not
Armstrong number is a number that is equal to the sum of
cubes of its digits. For example 0, 1, 153, 370, 371 and 407
are the Armstrong numbers.

Eg :
#include<stdio.h>
#include<math.h>
void main()
{
int n,sum,d1,d2,d3; OUTPUT:
printf(“Enter the number \n"); Enter the number :
scanf("%d", &n); 153
d3= n%10; //Units digit Armstrong number
d2= (n/10)%10; //Tens digit
d1=n/100; //Hundreds digit
sum= pow(d1,3)+pow(d2,3)+pow(d3,3);
if(sum==n)
printf(“Armstrong number");
else
printf(" Not an armstrong number");
}
THANK
YOU

You might also like