CP Unit-II - RIT CSE (1)

Download as pdf or txt
Download as pdf or txt
You are on page 1of 29

Programming For Problem Solving Using C

UNIT-II
OPERATORS & CONTROL STATEMENTS
Operators, Operator Precedence and Associativity, Evaluating Expressions, Selection &
Making Decisions: Two Way Selection, Multiway Selection, Repetition: Concept of Loop,
Pre-test and Post-test Loops, Initialization and Updating, Event and Counter Controlled Loops,
Loops in C, Other Statements Related to Looping, Looping Applications- Summation, Powers,
Smallest and Largest, Programming Examples.
Operators:
An operator is a symbol that tells the computer to perform certain mathematical or logical
operations. They are used to manipulate data.
Types:
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operators
5. Increment and decrement operators
6. Conditional operators
7. Bitwise operators
8. Special operators
Arithmetic operators:
Arithmetic operators are used to perform arithmetic operations like addition, subtraction,
multiplication , division and to find the remainder in division. The corresponding symbols are
+(addition or unary plus), - (subtraction or unary minus), *, /,%(modulo division). C does not
have an operator for exponentiation.
Relational operators:
It is used to relate any two or more quantities.
Operator Meaning
< is less than
> is greater than
>= is greater than or equal to
<= is lesser than or equal to
== is equal to
!= is not equal to
Logical operators:
It is used to combine two or more relational expressions.
Operator Meaning
&& logical and
|| logical or
! logical not
Assignment operators:

CSE, RIT Page 1


= is used to assign value to a variable. In addition to this C has a set of shorthand assignment
operators.
Syntax:

Statement with simple Statement with short


Assignment operator. Hand operator.
a=a+1 a+=1
a=a-1 a-=1
a=a*1 a*=1
a=a/1 a/=1
a=a%b a%=b
Advantages:
1. No need to repeat the operator again in the right hand side.
2. The statement is more concise and clear.
3. The statement is more efficient.
4. It is easy to read.
Increment and Decrement operators:
To decrement the value of the variable by one or to increment the value of the variable by one.
Operators (unary operators):
++ adds 1 to the operand
-- subtracts 1
Example:
++m; (++ used as prefix operator)
m++; (++ as postfix operator)
Consider the following
m=5;
y=++m;
In the above case m and y would be 6.
m=5;
y=m++;
In the above case m would be 6 and y would be 5.
Similarly for the --operator.
Conditional operator:
The conditional operator is used for two-way decisions. The operator is a combination of ? and :
and takes three operands. The operator is otherwise called as the ternary pair.
Syntax:

The conditional expression is evaluated first. If it is non zero then expression1 is evaluated else
expression 2 is evaluated. It is an alternative for If-else statement.
Example:
//program to find the greater of 2 numbers

CSE, RIT Page 2


#include<stdio.h>
void main()
{
int a, b, great;
printf(“Enter 2 numbers……”);
scanf(“%d %d”,&a,&b);
great = (a>b) ? a : b;
printf(“the greater value is %d”,great);
}
Sample output:
Enter 2 numbers……10 23
The greater value is 23

Bitwise operators:
Manipulates the data at bit level.
Operator Meaning
& bitwise AND
| bitwise OR
^ bitwise EXCLUSIVE OR
<< shift left
>> shift right
~ one‟s complement
Special operators:
Sizeof() - to determine the size of the variable
,(comma) - to link the related expressions together
Example : value=(x=10,y=17,x+y)
. and -> - member selection operator
& and * - pointer operator

Expressions:
Combination of both operand and operator.
Types:
1. Arithmetic
2. Relational
3. Logical
Arithmetic expression:
Operand combined with arithmetic operators are called as arithmetic expressions.
Examples:
a+b
c-d
Types:
1. Integer arithmetic
2. Real arithmetic
3. Mixed arithmetic
Integer arithmetic:
Arithmetic operator combined with integer operands.
CSE, RIT Page 3
Example:
a + b; where a and b are of type integer.
Real arithmetic:
Arithmetic operator combined with real operands.
Example:
a + b where a and b are of type real.
Mixed mode arithmetic:
Expression consists of both integer and real operands.
Example:
a-b where a is of type integer and b is of type real.
An arithmetic expression is a combination of variables, constants and operators. C has no
operator for exponentiation.
Syntax :
variable = expression;
 The expression is evaluated first and the results are placed on the variable on the left.
 All variables must be assigned values before they are used in an expression.
 Spaces before and after an operator is optional. It is used to enhance the readability of the
statement.
Precedence of arithmetic operators:
An arithmetic expression without parenthesis is always evaluated from left to right. An
arithmetic expression has two priorities.
The highest priority - /, *, %
The lowest priority - +, -
During the first pass, the high priority operators are evaluated as they are encountered. During
the second pass, the low priority operators are evaluated.
Example:

CSE, RIT Page 4


DECISION MAKING AND BRANCHING
There are a number of situations where the order of execution of statements has to be changed
based on certain conditions or repeat a group of statements until certain conditions are met. This
involves some decision making to see if a particular condition has been met or not. C supports
such decision making and branching through the statements as follows:
 If
 Switch
 Conditional operator
 Goto
 Loops
If and If-Else statements:
There are four decision making or control statements as follows
1.If statement
2.Switch statement
3.Conditional operator statement
4.Goto statement
If statement:
It is a powerful decision making statement to control the flow of execution. It is basically two-
way decision statement and is used in conjunction with an expression.
Syntax:

It allows the system to evaluate the expression first and then, depending on whether the value is
true or false it transfers the control to the particular statement.

Different forms of IF statement:


1. Simple if statement
2. If …else statement
3. Nested if … else statement
4. Else if ladder
Simple if statement:
CSE, RIT Page 5
Syntax:

In the above statement if test expression is true then statement block will be executed else
statement block will be skipped.

Flowchart for simple if

Example:
// Program to find if a number is divisible by 7 or not
#include<stdio.h>
main()
{
int n;
printf(“Enter the number”);
scanf(“%d”,n);
if ((n%7)== 0)
printf(“The number is divisible by 7\n”);
printf(“Thank you”);
}

CSE, RIT Page 6


Sample Output 1:
Enter the number 7
The number is divisible by 7
Thank you
Sample Output 2:
Enter the number 10
Thank you

If …else statement:
Syntax:

In the above statement if the test expression is true then true block statement, immediately
following the If statement are executed; otherwise the false block statement are executed. In
either case either true block will be executed or false block will be executed but not both.

Flowchart for if..else


Example:
// Program to find the greatest of 2 numbers
#include<stdio.h>
CSE, RIT Page 7
void main()
{
int a,b;
printf(“Enter 2 numbers);
scanf(“%d %d”,&a,&b);
if(a>b)
printf(“%d is greater”,a);
else
printf(“%d is greater”,b);
}
Output:
Enter 2 numbers 2 3
3 is greater
Nesting of if … else statement:
Syntax:

In the above statement if test condition 1 is true then if test condition 2 will be tested and if it is
also true then statement 1 will be executed. If the second condition is false then statement 2 will
be executed. If the first condition is false then statement 3 will be executed.

CSE, RIT Page 8


Flowchart for nested if..

Example:
//Program to find the greatest of 3 numbers
#include<stdio.h>
void main()
{
int a,b,c;
printf(“Enter the 3 numbers”);
scanf(“%d %d %d”,&a,&b,&c);
if( a>b)
{
if(a>c)
printf(“a is greater”);
else
printf(“c is greater”);
}
else
{
if(b>c)
printf(“b is greater”);
else
printf(“c is greater”);
}
}
CSE, RIT Page 9
Sample Output;
Enter the 3 numbers 2 3 5
c is greater
Enter the 3 numbers 5 3 2
a is greater
Enter the 3 numbers 2 5 3
b is greater
Else … if ladder:
Syntax:

Else If ladder is used for multi path decisions (ie) a chain of ifs in which the statement associated
with each else is another if. The condition are evaluated from the top to bottom as soon as a true
condition is found, the statement associated with it is executed and the control is transferred to
the statement x. When all the „n‟ conditions become false then the final else containing the
default-statement will be executed.

Example:
//Program to find the grade
CSE, RIT Page 10
#include<stdio.h>
void main()
{
int marks;
char grade;
printf(“Enter marks);
scanf(“%d”,marks);
if(marks>89)
grade=‟O‟;
else if(marks>79)
grade=‟A‟;
else if(marks>69)
grade=‟B‟;
else If(marks>40)
grade=‟C‟;
else
grade=‟F‟;
printf(“Marks is %d and the grade is %c”,marks, grade);
}
Sample Output:
Enter marks 89
Marks is 95 and grade is O

Switch:
Switch statement is used as an alternative for else-if ladder. The major disadvantage with else –if
ladder is that when there are more number of alternatives, the else-if ladder grows. This reduces
the readability of the program. Thus switch can be used as an alternative for else-if ladder for
multi path decisions. The value of any variable or expression is used to select one branch among
several alternatives. The switch tests the value of given variable (or) expression against a list of
case values and when a match is found, a block of statements associated with that case is
executed.

Syntax:

CSE, RIT Page 11


In the above syntax the expression is an integer expression or characters. The value-1,value-2,….
are constants or constant expressions and are known as case labels.
Each of these values should be unique within a switch statement. block-1,block-2,….. are
statements contain zero or more statements. There is no need to put braces around these blocks.
The case labels must end with a colon. When a switch is executed, the value of expression is
compared with case values, if matches, then the block of statements that follows the case are
executed. The break statement is used to exit from the switch statement. Default is an optional
case. When default is present, it will be executed if the value of the expression does not match
with any of the case values. If default is not present then no action takes place and the control is
transferred to statement –x.

CSE, RIT Page 12


Flowchart for Switch …case
Example:
// program to implement a simple calculator
#include<stdio.h>
void main()
{
int a, b, c, choice; // c is a temporary variable
printf(“1. Addition \n”);
printf(“2. Subtraction \n”);
printf(“3. Multiplication \n”);
printf(“4. Division \n”);
printf(“Enter your choice……..”);
scanf(“%d”,&choice);
printf(“\n Enter 2 values”);
switch(choice)
{

CSE, RIT Page 13


case 1: c=a+b;
break;
case 2: c=a-b;
break;
case 3: c=a*b;
break;
case 4: c=a/b;
break;
}
printf(“The value = %d\n”,c);
}
}
Sample output:
1. Addition
2. Subtraction
3. Multiplication
4. Division
Enter your choice…….1
Enter 2 values 3 4
The value = 7
Conditional operator:
The conditional operator is used for two-way decisions. The operator is a combination of ? and :
and takes three operands. The operator is otherwise called as the ternary pair.
Syntax:

The conditional expression is evaluated first. If it is non zero then expression1 is evaluated else
expression 2 is evaluated. It is an alternative for If-else statement.
Example:
//program to find the greater of 2 numbers
#include<stdio.h>
void main()
{
int a, b, great;
printf(“Enter 2 numbers……”);
scanf(“%d %d”,&a,&b);
great = (a>b) ? a : b;
printf(“the greater value is %d”,great);
}
Sample output:
Enter 2 numbers……10 23
The greater value is 23

Goto:

CSE, RIT Page 14


C supports the goto statement that branches unconditionally from one point of the program to
another. The goto requires a label in order to identify the place where the branch is to be made. A
label is a valid variable name that has to be followed by a semicolon. The label is placed before
the statement where the control needs to be transferred.
Syntax:

Example:
/*program to find the sum of 5 positive numbers the program branches unconditionally to x
when it encounters a negative number*/
#include<stdio.h>
void main()
{
int a, sum =0, count=1;
printf(“Enter 5 positive numbers\n”);
x: scanf(“%d”,&a);
if(a<0)
{
printf(“Enter a positive number”);
goto x:
}
else
{
sum = sum + a;
count++;
}
if (count<=5)
goto x;
else
printf(“sum = %d”, sum);
}
Sample output:
Enter 5 positive numbers
1
-1
enter a positive number
1
1
1
1
sum = 5
If the label is placed after the statement „goto‟ then it is called a forward jump. If the label is
placed before the statement „goto‟ then it is called a backward jump.

CSE, RIT Page 15


LOOP CONSTRUCTS (ITERATIONS)
It is used to repeat the block of statements for n number of times.
Process involved in looping statement is as follows:-
1. Setting and initialization of counter.
2. Execution of the statements of the statements in the loop.
3. Test for a specified condition for execution of the loop.
4. Incrementing the counter.
Types:
1. While statement
2. Do statement
3. For statement
1) While statement:
a. The while is an entry- controlled loop statement.
b. The test -condition is evaluated first and if the condition is true, then the body of loop is
executed. Again the test-condition is tested and body of the loop will be
repeated until the condition becomes false
c. If at the entry condition itself the test-condition is false then body of the loop will be
skipped.
Syntax:

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

CSE, RIT Page 16


int i=1;
while (i>1)
{
printf(“The number is one”);
i--;
}
printf(“Thank you”);
}
Sample Output:
Thank you
2) The do While Loop:
a. The do is an exit- controlled loop statement.
b. The body of loop will be executed once and the condition is tested if the condition is
true then body will be repeated or else exit from the loop.
Syntax:

Example:
//program using the do statement
#include<stdio.h>
void main()
{
int i=1;
do
{
printf(“the number is one\n”);
}while(i>1);
printf(“thank you”);
}
Sample output:
The number is one
Thank you
For Loop:
If we know the exact number of times for repetition of block of statements, then for statement
can be used. It is an entry controlled loop.
Syntax:

CSE, RIT Page 17


Execution of „for‟ statement as follows:
1. Initialization of the control variable is done first using an assignment statement. The variables
used for initialization are called control variables.
2. The value of the control variable is tested using the test condition. If the test condition is true
then the block is executed otherwise the loop is terminated and the execution continues with the
statement immediately following the loop.
3. When the body of the loop is executed, then the control is transferred back to the For loop.
The control variable will be incremented by using the increment and again tested using the test
condition. This will be repeated until the test condition becomes false.
4. It allows negative increments. In that case the initial value should be greater than the final
value.
5. In normal situations initial value is lesser than the final value.
6. It allows more than one variable initialization as well as more than one variable
incrementation.

Examples:
for (i=1; i<=10; i++) (positive increment)
for (i=10; i>0; i--) (negative increment)
for (i=0,j=8; i<=j; i++,j--) (multiple initializations, increment and decrements)

7. For statement is not followed by semicolon(;).


8. Nested loop is also possible. (ie.,) loop within a loop.

Example :
----------------
----------------
for (i=1;i<=n;i++)
{
for(j=1;j<=m;j++)
{
------------------
------------------
}
}
-------------------
9. Break statement is used to exit from the loop. It can be used as a part of If statement.

CSE, RIT Page 18


Example:

10. To skip a portion of statements in the for loop continue statement can be used in conjunction
with if statement .

Thus an important aspect of the for loop is that all the three sections namely, the initialization,
testing and incrementing are placed in the for statement itself, making it visible for the
programmers from one place itself.

CSE, RIT Page 19


Additional features of for loop:
1. More than one variable can be initialized at a time in the for statement
Example:
for(p=1, i=1; i<=10; i++)
2. The increment section also may have more than one part.
Example:
for(p=10, i=1; i<=10; i++,p--)
3. The test condition may have any compound relation.
Example:
for(p=1; p<=10 && sum <100; p++)
{
------
-------
}
4. The programmer is also allowed to use expressions in the assignment statements of
initialization and increment sections.
Example:
for(x=(m+n)/2; x>10; x=x/2)
{
………
………
}
5. Both the initialization and the increment sections can be omitted in the for statement.
In such cases the sections are left blank, but the semi colons must remain.
Example:
m=5;
for ( ; m<=10; )
{
printf(“%d”,m);
m =m+5;
}
6. Time delays can be set up using null statements
Example:

CSE, RIT Page 20


for( a=1000; a>0; a--);

This loop is executed 1000 times without producing any output and thus causes a time delay.
This kind of statement is known as the null statement. (it contains semicolon at the end)
Example:
//program to find the factorial of a number //factorial of a number (n) = 1*2*3*…..*n
#include<stdio.h>
void main()
{
int n, i,fact =1;
printf(“Enter the number…”);
scanf(“%d”,&n);
for(i = 1; i<=n; i++)
fact = fact * i;
printf(“\n The factorial of the given number %d is %d”,n, fact);
}
Sample Output:
Enter the number…3
The factorial of the given number 3 is 6.

Exercises (Write C Programs for the following, using loops)

• Display n natural numbers.


• Find sum of first n natural numbers.
• Find factorial of a number.
• Find the sum of digits of a number.
• Check whether a number is Armstrong‟s number or not.
• Check whether a number is perfect number or not. (sum of all its factors = number itself
e.g. 6,28. 496..)
• Check whether a number is Prime or not.
• Program to display Fibonacci series upto n terms. ( 0,1,1,2,3,5,8,13,………)
• Check whether a number is Palindrome or not .
• Find GCD and LCM of two given numbers.
• Program to display all factors of a given number.
• Convert a decimal number to binary .
• Program to find the series sum for 2+4+6+…+n and many more…

CSE, RIT Page 21


Nesting of Loops:

Nested loop means a loop statement inside another loop statement. That is why nested loops are
also called as “loop inside loop“.

Syntax for Nested For loop:


for ( initialization; condition; increment ) {

for ( initialization; condition; increment ) {

// statement of inside loop


}

// statement of outer loop


}

Example:

#include <stdio.h>
int main()
{
int n;// variable declaration
printf("Enter the value of n :");
// Displaying the n tables.
for(int i=1;i<=n;i++) // outer loop
{
for(int j=1;j<=10;j++) // inner loop
{
printf("%d\t",(i*j)); // printing the value.
}
printf("\n");
}

CSE, RIT Page 22


Syntax for Nested While loop:
while(condition) {

while(condition) {

// statement of inside loop


}

// statement of outer loop


}

Example: Multiplication Table

#include <stdio.h>
#include <stdlib.h>
int main()
{
printf("Multiplication table\n\n");
int i=1,j;
while(i<=10)
{
j=1;
while(j<=10)
{
printf("%d\t",j*i);
j++;
}
printf("\n");
i++;
}
getch();
return 0;
}

CSE, RIT Page 23


Output:
multiplication table printing using nested while loop in C language
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100

Syntax for Nested Do-While loop:


do{

do{

// statement of inside loop


}while(condition);

// statement of outer loop


}while(condition);

Example

#include <stdio.h>
int main()
{
do
{
printf("I'm from outer do-while loop ");

CSE, RIT Page 24


do
{
printf("\nI'm from inner do-while loop ");
}
while(1 > 10);
}
while(2 > 10);
return 0;
}

Output
I'm from outer do-while loop
I'm from inner do-while looput:

 There is no rule that a loop must be nested inside its own type. In fact, there can
be any type of loop nested inside any type and to any level.
Syntax:
do{
while(condition) {
for ( initialization; condition; increment ) {
// statement of inside for loop
}
// statement of inside while loop
}
// statement of outer do-while loop
}while(condition);

The Infinite Loop


A loop becomes an infinite loop if a condition never becomes false. The for loop is traditionally
used for this purpose. Since none of the three expressions that form the 'for' loop are required,
you can make an endless loop by leaving the conditional expression empty.

#include <stdio.h>
CSE, RIT Page 25
int main () {

for( ; ; ) {
printf("This loop will run forever.\n");
}

return 0;
}

When the conditional expression is absent, it is assumed to be true.

Difference between while and Do…while

while do-while

Condition is checked first then statement(s) is Statement(s) is executed atleast once,


executed. thereafter condition is checked.

It might occur statement(s) is executed zero


times, If condition is false. At least once the statement(s) is executed.

No semicolon at the end of while. Semicolon at the end of while.


while(condition) while(condition);

If there is a single statement, brackets are not


required. Brackets are always required.

Variable in condition is initialized before the variable may be initialized before or within
execution of loop. the loop.

while loop is entry controlled loop. do-while loop is exit controlled loop.

while(condition) do { statement(s); }
{ statement(s); } while(condition);

Some C Programs using Loops

CSE, RIT Page 26


Sum of Natural Numbers Using for Loop

#include <stdio.h>
int main() {
int n, i, sum = 0;

printf("Enter a positive integer: ");


scanf("%d", &n);

for (i = 1; i <= n; ++i) {


sum += i;
}

printf("Sum = %d", sum);


return 0;
}

The above program takes input from the user and stores it in the variable n. Then, for loop is
used to calculate the sum up to n.

Power of a Number Using the while Loop

#include <stdio.h>
int main() {
int base, exp;
long long result = 1;
printf("Enter a base number: ");
scanf("%d", &base);
printf("Enter an exponent: ");
scanf("%d", &exp);

while (exp != 0) {
result *= base;
--exp;
}
printf("Answer = %lld", result);
return 0;

CSE, RIT Page 27


}

Output

Enter a base number: 3


Enter an exponent: 4
Answer = 81

C Program to find Smallest and Largest number using Loop


#include<stdio.h>
int main()
{
int i, n, lar,sm, elem;
printf ("Enter total number of elements n");
scanf ("%d", &elem);
printf ("Enter first number n");
scanf ("%d", &n);
lar = n;
sm=n;
for (i=1; i<= elem -1 ; i++)
{
printf ("n Enter another number n");
scanf ("%d",&n);
if (n>lar)
lar=n;
if (n<sm)
sm=n;
}
printf ("n The largest number is %d", lar);
printf ("n The smallest number is %d", sm);
return 0;
}

Output

Enter total number of elements 5

CSE, RIT Page 28


Enter first number 3

Enter another number 8

Enter another number 42

Enter another number 12

Enter another number 89

The largest number is 89

The smallest number is 3

CSE, RIT Page 29

You might also like