0% found this document useful (0 votes)
10 views41 pages

C Notes Module-2

The document serves as an introduction to C programming, focusing on operators and decision-making structures such as branching and looping. It outlines various types of branching statements, including simple if, if-else, nested if, else-if ladder, and switch statements, providing syntax and examples for each. Additionally, it discusses the limitations and rules for using the switch statement in C.
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)
10 views41 pages

C Notes Module-2

The document serves as an introduction to C programming, focusing on operators and decision-making structures such as branching and looping. It outlines various types of branching statements, including simple if, if-else, nested if, else-if ladder, and switch statements, providing syntax and examples for each. Additionally, it discusses the limitations and rules for using the switch statement in C.
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

INTRODUCTION TO C PROGRAMMING

Module-2
Operators
Operators are the basic components of C programming. They are symbols that represent some kind
of operation, such as mathematical, relational, bitwise, conditional, or logical computations, which
are to be performed on values or variables. The values and variables used with operators are called
operands.

[Link], Dept. of CSE, BLDEACET Page 1


INTRODUCTION TO C PROGRAMMING

[Link], Dept. of CSE, BLDEACET Page 2


INTRODUCTION TO C PROGRAMMING

[Link], Dept. of CSE, BLDEACET Page 3


INTRODUCTION TO C PROGRAMMING

[Link], Dept. of CSE, BLDEACET Page 4


INTRODUCTION TO C PROGRAMMING

[Link], Dept. of CSE, BLDEACET Page 5


INTRODUCTION TO C PROGRAMMING

[Link], Dept. of CSE, BLDEACET Page 6


INTRODUCTION TO C PROGRAMMING

[Link], Dept. of CSE, BLDEACET Page 7


INTRODUCTION TO C PROGRAMMING

[Link], Dept. of CSE, BLDEACET Page 8


INTRODUCTION TO C PROGRAMMING

[Link], Dept. of CSE, BLDEACET Page 9


INTRODUCTION TO C PROGRAMMING

Decision Making, Branching, Looping


Branching and Looping
Branching Statements:

In sequential control, all the statements are executed in the order in


which they are written sequentially in a program from top to bottom. However,
it is necessary for the programmer to execute or skip certain set of statements
based on certain conditions and is possible by using branching statements.
These branching statements are also called as conditional or decision making
statements.

C language provides the following 5 types of branching statements for the


programmers to take decisions.

1. Simple if statement (One way selection statement)

2. if … else statement (Two way selection statement)

3. nested if statement or nested if else statement (Multi way)

4. else if ladder or cascaded if statement (Multi way)

5. switch statement (Multi way)

Simple if statement: This is one-way selection statement available in C. It


helps the programmer to execute or skip true block of statements based on
given condition. The syntax, flowchart and examples are as follow.

Syntax:

if (condition)

true block of statements;

Statements-X;

[Link], Dept. of CSE, BLDEACET Page 10


INTRODUCTION TO C PROGRAMMING

In the above syntax, the given condition will be evaluated for TRUE or
FALSE by machine, if it is True, then the true block statements are executed;
otherwise, no.

Example: C program to find largest of two numbers using simple if statement.

#include<stdio.h>
void main()
{

int n1,n2;
printf(“Enter any two numbers”);
scanf(“%d%d”,&n1,&n2);
if (n2>n1)
{

printf(“\n Largest number is %d”, n2);


}

if (n1>n2)
{

printf(“\n Largest number is %d”, n1);


}

More Examples:

To find largest of three numbers. To check for positive or negative number.


large=a;
if(b>large) if(n>0)
large=b; printf(“\n %d is positive number”,n);
if(c>large) if(n<0)
large=c; printf(“\n %d is negative number”,n);
printf(“\n Largest number is %d”, large);

To check for EVEN or ODD number. To check eligibility for vote.


if (n%2= =0) if (age<18)
printf(“\n %d is even number”, n); printf(“You are not eligible for vote”);
if (n%2! =0) if (age>=18)
printf(“\n %d is odd number”, n); printf(“You are eligible for vote”);

[Link], Dept. of CSE, BLDEACET Page 11


INTRODUCTION TO C PROGRAMMING

2) if … else statement: It is two way selection statement. It executes either true


block of statements or false block of statements based on a given condition. It is
used by programmers to select one from two alternatives.
Syntax:
if (condition)

True block of statements;

else

False block of statements;

Statement-X;

In the above syntax, the given condition will be evaluated for TRUE or FALSE by
machine, if it is True, then the True Block of Statements are executed;
otherwise, False Block of Statements are executed.

Example1:C program to find largest of two numbers using simple if … else statement.

#include<stdio.h>
void main()
{

int n1,n2;
clrscr();
printf(“Enter any two numbers”);
scanf(“%d%d”,&n1,&n2);
if (n1>n2)
{

printf(“\n Largest number is %d”, n1);


}

else
{

printf(“\n Largest number is %d”, n2);


}

[Link], Dept. of CSE, BLDEACET Page 12


INTRODUCTION TO C PROGRAMMING

More Examples on if ... else statement :

/*C program to find area of circle if the user name is your First Name and password is 999*/
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{

char name[25]; /* string variable or character array*/


int pwd;
float r,area;
printf("\n Enter User Name:");
scanf("%s",&name);
printf("\n Enter Password:");
scanf("%d", &pwd);
if (( strcmp(name,"john") ==0) && pwd= =999 )
{

printf("\n Login Successful ");


printf("\n Enter radius of circle:");
scanf("%f",&r);
area=3.142*r*r;
printf("\n Area of circle is %f",area);
}

else
{

printf("\n Invalid user name or password!");


}

/*C program to check for upper case letters*/


#include<stdio.h>
#include<conio.h>
void main()
{

char ch;
clrscr();
printf("\n Entera character:");
scanf("%c",&ch);
if (ch>='A' && ch<='Z')
printf("\n %c is uppercase letter",ch);
else
printf("\n %c is not uppercase letter",ch);

[Link], Dept. of CSE, BLDEACET Page 13


INTRODUCTION TO C PROGRAMMING

3. Nested if statement: It is a multi-way selection statement. In this type, the


programmer uses simple if or if … else statement within another if
statement. Hence, it is called nested if statement. It helps to select one from
many alternatives based on given conditions. The syntax, flowchart and
examples are as follow.
Syntax:

Syntax:
if (exprn-1)
{
if (exprn-2)
{
Statement1;
}
else
{
Statement2;
}
}
else
{
Statement3;
}
Statement-X;
Example: To find largest of three numbers by using nested if statement

# include <stdio.h>
void main( )
{
int a, b, c, large;
clrscr();
printf(“Enter three numbers”);
scanf(“%d%d%d”, &a, &b, &c);
if (a>b)
{
if (a>c)
large=a;
else
large=c;
}
else
{
if (b>c)
large=b;
else
large=c;
}
printf(“\n %d is large number”, large);
}

[Link], Dept. of CSE, BLDEACET Page 14


INTRODUCTION TO C PROGRAMMING

4. The else .. if ladder or cascaded if statement: It is another multi way selection statement
available in C to select one from many alternative. It helps the programmer to use another if
else statement only within the else part of the previous if else statement. So, it is called else if
ladder or cascaded if statement. The syntax, flowchart and examples are as follow.
Syntax:
if (expression-1)
statement1;
else if (expression -2)
statement2;
else if (expression -3)
statement3;
else if (expression -n)
statement-n;
else
default statement;
statement-X;
In the above syntax, the expression-1 will be evaluated by machine for True or False,
if it is True then Statement-1 executes followed by statement-x. Otherwise; other expressions
will be evaluated for True/False to execute concerned block for the True condition. If, all the
expressions are False then default statement will be executed by machine.

Example: C program to display the grades obtained by student based on the average marks
scored.
Average Marks Grade
80 to 100 Honors
60 to 79 First Division
50 to 59 Second Division
40 to 49 Third Division
0 to 39 Fail
# include <stdio.h>
void main( )
{

float avg;
printf(“\n Enter average marks scored by student”);
scanf(“%f”, &avg);
if (avg>=80)
printf(“\n Honors!!”);
else if (avg>=60)
printf(“\n First Division”);
else if (avg>=50)
printf(“\n Second Division”);
else if (avg>=40)
printf(“\n Third Division”);
else
printf(“\n Fail”);
}

[Link], Dept. of CSE, BLDEACET Page 15


INTRODUCTION TO C PROGRAMMING

/* To find roots of a quadratic equation*/


#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{

float a, b, c, r1, r2,d;


clrscr();
printf("\n Enter the coefficients of a Quadratic equation:");
scanf(" %f %f %f ", &a, &b, &c);
if (a!=0)
{

d=(b*b)-(4*a*c);
if(d>0)
{

printf("\n Roots are real and distinct");


r1=(-b + sqrt(d)) / (2*a);
r2=(-b - sqrt(d)) / (2*a);
printf("\n Root1=%f \t Root2= %f ", r1, r2);
}

else if (d = =0)
{

printf("\n Roots are real and equal");


r1=-b / (2*a);
r2=r1;
printf(" \n Root1=%f \t Root2=%f ",r1,r2);
}

else
{

} printf("\n Roots are imaginary");


r1=-b / (2*a);
else r2=sqrt (abs(d)) / (2*a);
printf("\n Root1= %f + i %f \t Root2= %f –i %f ",r1, r2, r1, r2);
}

printf("Coefficients are not non zero");


getch();
}

[Link], Dept. of CSE, BLDEACET Page 16


INTRODUCTION TO C PROGRAMMING

5. The Switch Statement: It is another multi way statement. It helps the programmer to
select one from many alternatives. It is mainly used by programmers to provide menu
options for the end users of a program to select one from displayed menu options.

Syntax:
Switch (value)
{
case value1:
statements block1;
break;
case value2:
statements block2;
break;
case value3:
statements block3;
break;



default:
default statement;
break;
}
Statement-X;
In the above syntax, the passed value will be compared against all the case values one after
another from top to bottom, wherever it matches that associated block of statements executes
; otherwise, default statement executes.
Limitations of using switch statement:

1. We can pass only integer value or character constant to switch body.


Rules for using switch statement:

1. The switch value must be an integer type. (or character also)


2. Case labels must be unique and constants.
3. Case labels must end with the colon(:).
4. The break and default statements are optional.

Example:

[Link], Dept. of CSE, BLDEACET Page 17


INTRODUCTION TO C PROGRAMMING

/*Simple C program to illustrate switch statement */


#include<stdio.h>
#include<conio.h>
void main()
{

int ch;
clrscr();
printf("\n Enter your choice [1 2 3]?:");
scanf("%d",&ch);
switch(ch)
{

case 1:
printf("\n You have selected first choice");
break;
case 2:
printf("\n You have selected second choice");
break;
case 3:
printf("\n You have selected third choice");
break;
default:
printf("\a Invalid choice!");
break;
}

getch();
}

Output 1:

Enter your choice [1 2 3]?: 2


You have selected second choice

Output 2:

Enter your choice [1 2 3]?: 5


Invalid choice!

[Link], Dept. of CSE, BLDEACET Page 18


INTRODUCTION TO C PROGRAMMING

More examples on Switch :

Write a c program to display the color names like Red, Green, Blue by reading first
character of color as input.

/* To display color names */


#include<stdio.h>
#include<conio.h>
void main()
{
char ch;
clrscr();
printf("\n Enter first character of color [R/G/B]? :");
ch=getchar();
switch(ch)
{
case 'R':
case 'r':
printf("\n RED");
break;
case 'G':
case 'g':
printf("\n GREEN"); break;
case 'B':
case 'b':
printf("\n BLUE");
break;
default:
printf("\a Invalid choice!");
break;
}
getch();
}

Output:
1.
Enter first character of color [R/G/B]? : b
BLUE
2.
Enter first character of color [R/G/B]? : G
GREEN
3.
Enter first character of color [R/G/B]? : i Invalid choice

[Link], Dept. of CSE, BLDEACET Page 19


INTRODUCTION TO C PROGRAMMING

Write a c program to print a word for given digit (0- 9).


/*To print a word for a digit */
#include<stdio.h>
#include<conio.h>
void main()
{

int digit;
printf("\n Enter a digit (0-9):");
scanf("%d",&digit);
switch(digit)
{

case 0:
printf("Zero");
break;
case 1:
printf("One");
break;
case 3:
printf("Three");
break;
/* Here write the code for remaining cases 4, 5, 6,7,8*/
case 9:
printf("Nine");
break;
default:
printf("\a Invalid input!");
break;
} }

Write a c program to check whether the character is vowel or not vowel.


/*To check character for vowel*/
#include<stdio.h>
#include<conio.h>
void main()
{

char ch;
printf("\n Enter a character :");
scanf("%c",&ch);
switch(ch)
{

case 'a':
case 'A':
case 'e':
case 'E':
case 'i':
case 'I':
case 'o':
case 'O':
case 'u':

[Link], Dept. of CSE, BLDEACET Page 20


INTRODUCTION TO C PROGRAMMING

case 'U':
printf("Vowel");
break;
default:
printf("\a Not Vowel");
break;
}

Write a c program to find area of circle, area of triangle and area of rectangle by using switch
statement to display menu options for the users to select any one to work accordingly.
*To find area of geometrical figures*/
#include<stdio.h>
#include<conio.h>
void main()
{

int ch;
float r,l,b,breadth,height,area;
printf("\n 1. Area of Circle");
printf("\n 2. Area of Circle");
printf("\n 3. Area of Circle");
printf("\n Enter your choice[1 2 3]?:");
scanf("%d",&ch);
switch(ch)
{

case 1:
printf("Enter radius of circle");
scanf("%f",&r);
area=3.142*r*r;
printf("\n Area of circle is %5.2f",area);
break;
case 2:
printf("Enter breadth and height of triangle");
scanf("%f%f",&breadth,&height);
area=0.5*breadth*height;
printf("\n Area of triangle is %5.2f",area);
break;
case 3:
printf("Enter length and breadth of rectangle");
scanf("%f%f",&l,&b);
area=l*b;
printf("\n Area of rectangle is %5.2f",area);
break;
default:
printf("\a Invalid choice!");
break;
}

[Link], Dept. of CSE, BLDEACET Page 21


INTRODUCTION TO C PROGRAMMING

Introduction to Loop Control Statements


As we know, the statements from written computer program executes
sequentially from top to bottom. However, it is necessary for the programmer to
execute certain block of statements repeatedly till certain condition satisfies
while solving complex problems by using a machine and is possible by loop
control statements. The loop statements are also called as iterative statements.
C provides the following three types of loop statements for the C
programmers to repeat certain block of statements repeatedly till certain
condition satisfies.
1. The while loop (entry controlled or pre-test loop)
2. The do … while loop (exit controlled or post test loop)
3. The for loop (entry controlled or pre-test loop)

1. The while loop: It is one of the entry controlled loop statement. It repeats the
given true-block of statements repeatedly till the given condition is true.
Whenever, the condition becomes false then loop terminates.
The while loop is also called as pre-test loop or event controlled loop.
The syntax, flowchart and examples are as follow.

Syntax:
while (expression)
{
true - block loop
true - block loop statements;
statements
}
Statements-X;
Statement-X

In the above syntax, the given expression will be checked for True or
False. If, it is True, then loop statements are executed repeatedly till the
condition becomes False.

Examples:

[Link], Dept. of CSE, BLDEACET Page 22


INTRODUCTION TO C PROGRAMMING

To display the “Hello World!” message for 10 times.


/* Example for while loop */
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
clrscr();
i=1;
while (i<=10)
O/p:
{
Hello World!
printf(“\n Hello World!”); Hello World!
i=i+1; …
} …
getch(); Hello World!
}

To display 1 to 10 numbers.
/* Example for while loop */
#include<stdio.h>
#include<conio.h>
void main()
{
O/p:
int i; 1
clrscr(); 2
i=1; 3
while (i<=10) .
.
{
10
printf(“\n %d”,i);
i=i+1;
}
getch();
}

To display 1 to n numbers. O/p:


/* To display 1 to n numbers */ Enter the value of n: 100
#include<stdio.h> 1
2
#include<conio.h> 3
void main() .
{ .
int i,n; 100
clrscr();
printf(“Enter the value of n: ”);
scanf(“%d”,&n);
i=1;
while (i<=n)
{
printf(“\n %d”,i);
i=i+1;
}
}

[Link], Dept. of CSE, BLDEACET Page 23


INTRODUCTION TO C PROGRAMMING

Write a C program to find sum of odd numbers, even numbers and average of all numbers
between 1 to n.

/*To find sum of even, odd and all nos with average of 1 to n numbers*/
#include<stdio.h>
#include<conio.h>
void main()
{
int n,i,esum=0,osum=0,sum=0;
float avg;
clrscr();
printf("Enter n:");
scanf("%d",&n);
i=1;
while (i<=n)
{
if (i%2==0)
esum=esum+i; O/p:
else Enter the value of n: 5
osum=osum+i; Even Sum =6 Odd Sum=9 Sum=15 Average=3.00
sum=sum+i;
i++;
}
avg=(float)sum/n;
printf("\n Even Sum=%d Odd Sum=%d Sum=%d Average=%f", esum, osum, sum, avg);
getch();
}

Write a c program to find factorial of n.

/* To find factorial of n. */
#include<stdio.h>
#include<conio.h>
void main() O/p:
{ Enter the value of n: 5
int i, n, prod=1; Factorial of 5 is 120
clrscr();
printf(“Enter the value of n: ”);
scanf(“%d”, &n);
i=1;
while (i<=n)
{
prod=prod*i;
i=i+1;
}
printf(“\n Factorial of %d is %d”, n, prod);
getch();
}

[Link], Dept. of CSE, BLDEACET Page 24


INTRODUCTION TO C PROGRAMMING

Write a c program to display first „n‟ Fibonacci numbers. [Exam Question]


/*To generate first n fibonacci numbers*/
#include<stdio.h> O/p:
#include<conio.h> Enter n: 7
void main() Fibonacci Series
{ 0
int i=2,n,fib1=0,fib2=1,fib3; 1
1
clrscr(); 2
printf("Enter n:"); 3
scanf("%d",&n); 5
printf("\n Fibonacci Series\n"); 8
printf("\n%d\n%d",fib1,fib2);
while(i<n)
{
fib3=fib1+fib2;
printf("\n%d",fib3);
fib1=fib2;
fib2=fib3;
i++;
}
getch();
}

/* To find GCD and LCM of two numbers by Euclid's algorithm*/


#include<stdio.h>
#include<conio.h>
void main()
{
int m,n,temp1,temp2,rem,gcd,lcm;
clrscr();
printf("\n Enter any two numbers m and n:");
scanf("%d%d",&m,&n);
temp1=m,temp2=n;
while(n!=0)
{
rem=m%n; m=n; n=rem;
}
gcd=m; lcm=(temp1*temp2)/gcd;
printf("\n GCD=%d and LCM=%d",gcd,lcm); getch();
}

O/p:
Enter any two numbers m and n: 12 24
GCD=12 LCM=24

[Link], Dept. of CSE, BLDEACET Page 25


INTRODUCTION TO C PROGRAMMING

2) The do…while loop: It is exit controlled loop statement available in C. It helps the
programmer to repeat certain block of true statements repeatedly till the given condition is
True. Whenever, the given condition becomes False then the loop terminates.
The major difference between while and do…while is that, if the given condition is
False for the first time, then the body of the do while works at least once, whereas no
execution of while loop.
The do while is also called as post test or event controlled loop.
The syntax, flowchart and examples are as follow.
Syntax
do

true block of loop statements;

} while (expression);
true block of loop
statement-X; statements
In the above syntax, the statements from
true block of loop statements are executed repeatedly
till the given expression is true.

To display 1 to n numbers.
/* To display 1 to n numbers */ #include<stdio.h> #include<conio.h> Statement-X
void main()
{
int i,n; clrscr();
printf(“Enter the value of n: ”); scanf(“%d”,&n);
i=1;
do
{
printf(“\n %d”,i); i=i+1;
} while (i<=n);
getch();
}
O/p:
Enter the value of n: 100 1
2
3
.
. 100

[Link], Dept. of CSE, BLDEACET Page 26


INTRODUCTION TO C PROGRAMMING

/*To find sum and average of 1 to n numbers*/ #include<stdio.h>


#include<conio.h> void main()
{
int n,i,sum=0; float avg; clrscr(); printf("Enter n:");
scanf("%d",&n); i=1;
do
{
sum=sum+i; i++;
} while (i<=n); avg=(float)sum/n;
printf("\n Sum=%d Average=%f",sum, avg); getch();
}

O/p:
Enter the value of n: 5 Sum is 15 Average=3.00

[Link], Dept. of CSE, BLDEACET Page 27


INTRODUCTION TO C PROGRAMMING

Write a c program to find factorial of n.

/* To find factorial of n. */
#include<stdio.h>
#include<conio.h>
void main()
O/p:
{
Enter the value of n: 5
int i, n, prod=1;
Factorial of 5 is 120
clrscr();
printf(―Enter the value of n: ‖);
scanf(―%d‖, &n);
i=1;
do
{
prod=prod*i;
i=i+1;
}while (i<=n);
printf(―\n Factorial of %d is %d‖, n, prod);
getch();
}

Write a c program to reverse a number.

/*To reverse a number*/


#include<stdio.h>
#include<conio.h>
void main()
{
int num, rev=0, rem;
clrscr();
O/p:
printf("Enter n:"); Enter n: 123
scanf("%d", &num); The reversed number is 321
do
{
rem=num%10;
rev=(rev*10)+rem;
num=num/10;
} while (num!=0);
printf("\n The reversed number is %d", rev);
getch();
}

/*To repeat the application to find area of circle*/


#include<stdio.h>
#include<conio.h>
void main()
{
float r,area;
char ch;
clrscr();
do
{
printf("\n Enter radius of circle:");
scanf("%f",&r);
area=3.142*r*r;
printf("\n Area of circle is %f",area);
printf("\n Would you like to continue?[y/n]:");
ch=getch();
} while(ch=='y'||ch=='Y');
printf("\n Thank You");
getch();
}

[Link], Dept. of CSE,BLDEACET Page 1


INTRODUCTION TO C PROGRAMMING

Differences between while and do while loop


Sl.
While loop do … while loop
No.
It is entry controlled loop statement. It It is exit controlled loop statement. It
repeats the given true block of loop repeats the given true block of loop
statements repeatedly till the given statements repeatedly till the given
1
condition is True. When the condition condition is True. When the condition
becomes False then the loop becomes False then the loop
terminates. terminates.
If the given condition is False for the If the given condition is False for the
2 first time, then no execution of while first time, then body of do while
loop body. works at least once.
Syntax of while loop Syntax of do … while loop
while (condition) do
{ {
3
loop statements; loop statements;
} } while (condition);
statement-x; statement-x;
Flowchart Flowchart

Example: Example:
program to find factorial of n program to find factorial of n
i=1,prod=1; i=1,prod=1;
clrscr(); clrscr();
printf(― Enter n:‖); printf(― Enter n:‖);
scanf(―%d‖,&n); scanf(―%d‖,&n);
5
while(i<=n) do
{ {
prod=prod*i; prod=prod*i;
i++; i++;
} }while(i<=n);
printf(―\n factorial is %d‖, prod); printf(―\n factorial is %d‖, prod);
It is also called as pre test or event It is also called as post test or event
6
controlled loop. controlled loop.

[Link], Dept. of CSE,BLDEACET Page 2


INTRODUCTION TO C PROGRAMMING

2) The for loop: It is counter controlled loop statement available in C. It helps the
programmer to repeat given true bock of loop statements repeatedly till the given expression
is True. Whenever, the given condition becomes False then loop gets terminated. If the
number of iterations well known by programmers then they prefer the use of for loop
statement.
Syntax:
Entry
for (initialization; expression; increment/decrement)

{
for i = 1 to n step 1 False
True block of loop statements;
True
}

Statement-x;

Statements-X
Where,
Initialization  Counter will be assigned with initial value. e.g. i=1,i=0,etc.
Expression  The conditional expression on which number of iterations depends. E.g. i<n,
i<=n, etc.
increment/decrement  increment or decrement expression for the counter. E.g. i++, j++, i--,
j--,etc.
To display 1 to 10 numbers. O/p:
#include<stdio.h> 1
#include<conio.h> 2
void main() 3
.
{
.
int i; 10
clrscr();
i=1;
for(i=1;i<=10;i++)
{
printf(―\n %d‖,i);
}
getch();
}

[Link], Dept. of CSE,BLDEACET Page 3


INTRODUCTION TO C PROGRAMMING

To display 1 to n numbers.
/* To display 1 to n numbers */ Enter the value of n: 100
#include<stdio.h> 1
#include<conio.h> 2
void main() 3
{ .
int i,n; .
clrscr(); 100
printf(―Enter the value of n: ‖);
scanf(―%d‖,&n);
i=1;
for(i=1;i<=n;i++)
{
printf(―\n %d‖,i);
}
getch();
}

Write a c program to find factorial of n.

/* To find factorial of n. */
#include<stdio.h>
#include<conio.h>
void main()
O/p:
{
Enter the value of n: 5
int i, n, prod=1;
Factorial of 5 is 120
clrscr();
printf(―Enter the value of n: ‖);
scanf(―%d‖, &n);
i=1;
for(i=1;i<=n;i++)
{
prod=prod*i;
}
printf(―\n Factorial of %d is %d‖, n, prod);
getch();
}

/*To display multiple table of n*/


#include<stdio.h>
#include<conio.h>
O/p:
void main()
Enter n: 5
{
Multiple Table of 5
int i,n;
5 X 1 =5
clrscr();
5 X 2 =10
printf("Enter n:");
5 X 3 = 15
scanf("%d",&n);

printf("\n Multiple Table of %d \n",n);

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

{
5 X 10 = 10
printf("\n %d X %d = %d",n,i,n*i);
}
getch();
}

[Link], Dept. of CSE,BLDEACET Page 4


INTRODUCTION TO C PROGRAMMING

Nested loops: The programmer can use one loop statement within another loop statement and
is called nested loop. It informs the machine to do repetitive work repeatedly. It is used by
programmer to solve complex problems that include complex repetitive steps. The ANSI C
supports 32 times of nesting of loops.
Examples
i=1;
while (i<=5) /* outer loop works for 5 times */
{
j=1;
while (j<=10) /*every time inner loop works for 10 times*/
{
printf(―\t VTU, Belagavi‖);
j++;
}
i++;
printf(―\n‖);
}

Output: The given message ―VTU, Belagavi‖ will be displayed for 5 X 10 i.e. 50 times.

To read elements of matrix A[m x n].

printf(―\n Enter elements of matrix A‖);


for(i=0;i<m;i++) /* outer loop works for m times [to generate row index] */
{
for(j=0;j<n;j++) /*every time inner loop works for n times [column index] */
{
scanf(―%d‖, &a[i][j]);
}
}

To display elements of matrix A[m x n] in matrix format.

printf(―\n Elements of matrix A \n‖);


for(i=0;i<m;i++) /* outer loop works for m times [to generate row index] */
{
for(j=0;j<n;j++) /*every time inner loop works for n times [column index] */
{
printf(―%d‖, a[i][j]);
}
printf(―\n‖);
}

[Link], Dept. of CSE,BLDEACET Page 5


INTRODUCTION TO C PROGRAMMING

/*To display the number pattern*/


#include<stdio.h>
#include<conio.h>
void main()
{
int i,j;
clrscr();
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
printf("\t %d",j);
}
printf("\n");
}
getch();
}
/*To display the number pattern*/
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j;
O/p:
clrscr();
*
for(i=1;i<=5;i++)
* *
{
* * *
for(j=1;j<=i;j++)
* * * *
{
* * * * *
printf("\t *");
}
printf("\n");
}
getch();
}

/*To display the pattern*/ O/p:


#include<stdio.h> *
#include<conio.h>
void main()
* *
{ * * *
int i,j,k; * * * *
clrscr();
for(i=1;i<=5;i++) * * * * *
{
for(j=5;j>=i;j--)
{
printf(" ",j);
}
for(k=1;k<=i;k++)
{
printf(" *");
}
printf("\n");
}
getch();
}

Know it :

for ( i=1,j=10; (i<=10 && j>=1);i++,j--;) for ( ; ;)


{ {
printf(―\n %d \t %d‖, i, j); printf (―Hello World!‖);
} }
o/p: 1 10 o/p: infinite loop
2 9
3 8 Dept. of C SE, BLDEAs CET, Vijayapur,
… visit the blog [Link] Page No. 31

10 1
INTRODUCTION TO C PROGRAMMING

Introduction to Break and Continue Statements

As we know, the loop control statements like while, do while and for are
used by programmers to repeat certain block of statements repeatedly till the
given condition is True. However, it is necessary for the programmers to exit
from loop body before the condition satisfies or to skip certain statements from
loop body based on certain conditions. This is possible by making the use of
break and continue statements available in C. These are also called as loop
interrupt statements.

The break statement:


This is one of the loop interruption statements. It is used by C
programmers to exit from the body of while, do-while and for loop statements
based on certain condition. i.e loop terminates before the expression of loop
becomes False. It is usually used in association with the if statement. A break is
also used to exit from particular case of switch statement .
Syntax:
while (expression) do for(exp1;exp2;exp3)
{ { {
statements; statements; statements;
if (condition) if (condition) if (condition)
break; break; break;
statements; statements; statements;
} } while (expression); }
statement-x; statement-x; statement-x;

In the given syntax, whenever the given if (condition) becomes True then
loop terminates followed by statement-x.
Examples:

i=1; O/p: for(i=1; i<=100 ; i++) O/p:


while(i<=100) 1 { 1
{ 2 if ( i = = 5) 2
if ( i = = 5) 3 break; 3
break; 4 4
printf(―\n %d‖, i); printf(―\n %d‖, i);
i++;
} }
INTRODUCTION TO C PROGRAMMING

Write a c program to check whether the unknown number ‗n‘ is prime or not
prime.
/* To check for prime number*/
#include<stdio.h>
#include<conio.h>
void main()
{
int n,i,flag=1;
clrscr(); O/p:
printf("\n Enter n:");
scanf("%d",&n); Enter n: 7
for(i=2;i<=n/2;i++) 7 is prime number
{
if(n%i==0)
{ Enter n: 20
flag=0; 20 is not prime number
break;
}
}
if(flag = =1)
printf("\n %d is prime number",n);
else
printf("\n %d is not prime number",n);
getch();
}

The continue statement: It is another loop interrupt statement available in C. It


helps the programmers to skip certain statements from the body of loop
statements like while, do while and for based on certain conditions.
Syntax:

while (expression) for(exp1;exp2;exp3)


{ {
statements; statements;
if (condition) if (condition)
continue; continue;
statements block2; /* skip */ statements block2; /* skip */
} }
statement-x; statement-x;
INTRODUCTION TO C PROGRAMMING

In the above syntax, whenever the given if (condition) becomes True then
statements bock-2 are not going to execute.

Examples:

i=1; O/p: for(i=1; i<=5 ; i++) O/p:


while(i<=5) 1 { 1
{ 2 if ( i = = 3) 2
if ( i = = 3) Infinite continue; 4
continue; loop printf(―\n %d‖, i); 5
printf(―\n %d‖, i);
i++; }
}

To find sum of even numbers between 1 to n by using continue inside loop.

/* Example for continue statement*/


#include<stdio.h>
#include<conio.h> O/p:
void main()
{ Enter n: 6
int n,i,sum=0; Sum of even numbers 12
clrscr();
printf("\n Enter n:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
if (i%2!=0)
continue;
sum=sum+i;
}
printf("\n Sum of even numbers =%d",sum);
getch();
}
INTRODUCTION TO C PROGRAMMING

Differences between break and continue statements

[Link]. The break statement The continue statement


1 It is loop interruption statement. It It is also loop interruption
terminates (breaks) the repetitive statement. It skips certain
process of loop statements ( while, statements from the loop
do while and for loop) based on statements based on certain
certain conditions. i.e loop conditions.
terminates before the loop
expression becomes False.
2 Syntax: Syntax:
while (expression) while (expression)
{ {
statements; statements;
if (condition) if (condition)
break; continue;
statements; statements;
} }
statement-x; statement-x;
3 Example: Example:
for(i=1;i<=5;i++) for(i=1;i<=5;i++)
{ {
if (i= = 3) if (i= = 3)
break; continue;
printf(―\t%d‖,i); printf(―\t%d‖,i);
} }
o/p: 1 2 o/p: 1 2 4 5
4 It can be used in the body of It is not permitted in the body of
switch statement to terminate the switch statement.
cases.

The goto statement (unconditional statement):


The goto is unconditional statement available in C. It transfers the
program execution flow from one point of the program to another point. It is
usually used by programmers to exit from deeply nested loops. Unfortunately,
the programmers do not use goto statement in structured programming because
the program debugging and modification is difficult.
INTRODUCTION TO C PROGRAMMING

Syntax:
Statements; Statements;
label: if (expr-n)
statements; goto label;
if (expr-n) statements;
goto label; label:
statements; statements;

/* Example for goto statement*/


#include<stdio.h>
#include<conio.h>
void main()
{
int n;
clrscr(); O/p:
top: Enter n:
printf("\n Enter n:"); -7
scanf("%d",&n); Negative number!
Enter n: 8
if (n<0) 8 is even number
{
printf("\n Negative number! \n");
goto top;
}

if (n%2==0)
printf("\n %d is even number",n);
else
printf("\n %d is odd number",n);
getch();
}
INTRODUCTION TO C PROGRAMMING

/* To find sum of all numbers till user enters 999*/


#include<stdio.h>
#include<conio.h>
void main()
{
int n,sum=0;
clrscr();
top:
printf("\n Warning!!! Press 999 to exit.");
printf("\n\n Enter numbers to be sum:");
for(;;)
{ O/p:
scanf("%d",&n); Warning!!! Press 999 to exit.
if (n==999) Enter numbers to be sum:
goto bottom; 1 2 3 4 5 999
Sum of all numbers =15
sum=sum+n;
}
bottom:
printf("\n Sum of all numbers=%d",sum);
getch();
}

Important Questions on Module-2 for Examination


1. Explain all the FIVE branching statements with syntax, flowchart and minimum two
examples.
2. Explain all the THREE loop statements with syntax, flowchart and minimum two
examples.
3. Explain break, continue and goto statement with syntax and examples.
4. Write the difference between while and do while loop statements.
5. Write the differences between break and continue statements.
6. Practice the following important programs on rough paper for examination purpose.
a. To find largest of 3 numbers
b. The programs on switch statements.
c. To find factorial of n by using while loop
d. To find factorial of n by using do … while loop
e. To find factorial of n by using for loop
f. To reverse a number
g. To check for palindrome
h. To find GCD and LCM of two numbers by using Euclid‘s algorithm.
i. To print first N Fibonacci numbers.
j. To find sum of even numbers, sum of odd numbers, sum of all numbers and
average of 1 to n numbers.
k. To print multiple table of ‗n‘.
l. To check for prime number.
INTRODUCTION TO C PROGRAMMING

WIT and WISDOM

Don‘t compare yourself with anyone in this world, if you do so, you are
insulting yourself. –Alen Strike

Don‘t compare yourselves with others, instead compare yourself with your last
performance- Bill Gate

Attitude is a little thing that makes a big difference. – Winston Churchill

There is no use of running fast, when you are on the wrong road. So, first
choose the correct way in your life. - German Proverb

The causes of failure in the examination [By- Dr. C. R. Chandrashekar]

Subject / Course is difficult for the student or he/she has no interest in it. It was
forced on them by others.

Wrong study habits like ( continuous reading without understanding, no review,


no recall exercises, poor in representation, last hour preparation, poor time
management, poor self confidence, and negative attitudes.)

The future depends on what we do in the present – Mahatma Gandhi

―Success is the sum of small efforts, repeated day in and day out.‖ ~ Robert
Collier

―Learn from mistakes‖- Thomas Edison tried two thousand different materials
in search of a filament for the light bulb. When none worked satisfactorily, his
assistant complained, ―All our work is in vain. We have learned
nothing.‖Edison replied very confidently, ―Oh, we have come a long way and
we have learned a lot. We know that there are two thousand elements which we
cannot use to make a good light bulb.‖
INTRODUCTION TO C PROGRAMMING

When you are not practicing, then remember that, someone somewhere is
practicing for the same and when you will meet him/her, then he/she will be the
winner. – By Ed Macauley

Striving for success without hard work is like trying to harvest where you have
not planted. – By David Bly

The roots of education are bitter, but the fruits are sweat- Aristotle.

―If you try and lose then it isn't your fault. But if you don't try and we lose, then
it's all your fault.‖ ― Orson Scott Card, Ender's Game

―Hard work is much more important than talent‖― Carlo Rotella

―Yesterday is gone. Tomorrow has not yet come. We have only today. Let us
begin.‖ ― Mother Teresa

―The future depends on what you do today.‖― Mahatma Gandhi

―The future belongs to those who believe in the beauty of their dreams.‖
— Eleanor Roosevelt

Dear Student,

You are talented student, only you need to do is that read more to
understand unknown things.

while (Not Understood)


{
read (recommended text books || notes || both);
}
if ( you have understood )
Success in examination or life;
else
First Attempt In Learning;
Read Read Read Understand Re Write Re call Revise frequently Success (Ur dreams will be
converted to True)

You might also like