Professional Documents
Culture Documents
PROGRAMMING FOR
PROBLEM SOLVING
UNIT 2
Course Learning Outcome (CLO – 1)
Syntax:
Example:
10<= 20
Relational Operator (Cont..)
Program: Output:
Program: Output:
Example:
a > b && x == 10
Logical AND (&&) Operator
• The ‘&&’ operator returns true when both the conditions under
consideration are satisfied. Otherwise it returns false.
• For example, a && b returns true when both a and b are true (i.e. non-
zero).
Program:
#include <stdio.h>
int main() Output:
{
AND condition not
int a=10,b=4,c=10,d=20;
satisfied
if (a>b && c==d)
printf(“a is greater than b AND c is equal to d \n");
else
printf(“AND condition not satisfied");
}
Logical OR (||) Operator
• The ‘||’ operator returns true even if one (or both) of the conditions under
consideration is satisfied. Otherwise it returns false.
• For example, a || b returns true if one of a or b or both are true (i.e. non-
zero). Of course, it returns true when both a and b are true.
Program:
Program:
Output:
#include <stdio.h>
int main() A is not zero
{
int a=10;
if ( !a )
printf(“a is zero\n");
else
printf(“a is not zero”);
}
Example
Output
CONDITION OPERATOR
Condition Operator
• The conditional statements are the decision-making statements that
depend upon the output of the expression. It is represented by two
symbols, i.e., '?' and ':’.
• As a conditional operator works on three operands, so it is also known as
the ternary operator.
• The behavior of the conditional operator is similar to the ‘if-else’ statement
as 'if-else' statement is also a decision-making statement.
Syntax: Example: Achieved using if-else:
Condition Operator - Example
. Program:
#include <stdio.h>
int main()
{
int age;
printf("Enter your age");
scanf("%d",&age);
(age>=18)? (printf("eligible for voting")) : (printf("not eligible for voting"));
return 0;
}
Output: Output:
OPERATOR PRECEDENCE
Operator Precedence
• The operators within C are grouped hierarchically according to their
precedence.
• Operations with a higher precedence are carried out before operations
having a lower precedence.
• The natural order of evaluation can be altered through the use of
parentheses.
• Parenthesis can be nested, one pair within another.
• In such cases, the innermost operations are carried out first, then the next
innermost operations and so on.
• Associativity is the order in which consecutive operations within the same
precedence group are carried out.
Operator Precedence - Example
• Operator precedence determines which operator is performed first in an
expression with more than one operators with different precedence.
Operator Associativity
• Operators Associativity is used when two operators of same precedence
appear in an expression.
• Associativity can be either Left to Right or Right to Left.
• For example:
‘*’ and ‘/’ have same precedence and their associativity
is Left to Right, so the expression “100 / 10 * 10” is treated as “(100 /
10) * 10”.
Operator Associativity - Example
Operator Precedence & Associativity
• Operators Precedence and Associativity are two characteristics of
operators that determine the evaluation order of sub-expressions in
absence of brackets.
• Associativity is only used when there are two or more operators of
same precedence.
• All operators with the same precedence have same associativity.
• Precedence and associativity of postfix ++ and prefix ++ are different.
• Comma has the least precedence among all operators and should be
used carefully.
• There is no chaining of comparison operators in C.
Operator Precedence & Associativity - Example
Summary of Operator Precedence & Associativity
EXPRESSION WITH PRE /
POST INCREMENT
OPERATOR
Expression with Pre Increment Operator
• The pre increment operator is used to increment the value of some variable
before using it in an expression.
• In the pre increment the value is incremented at first, then used inside the
expression.
• If the expression is a = ++b; and b is holding 5 at first, then a will hold 6.
Because increase b by 1, then set the value of a with it.
Syntax
a = ++ b;
Expression with Pre Increment Operator -
Example
Program:
Output:
#include <stdio.h>
int main() Pre Increment Operation
{
int x=10,a; a = 11
a= ++x; x = 11
printf(“Pre Increment Operation");
printf(“\n a = %d“,a);
printf(“\n x = %d“,x);
return 0;
}
Expression with Post Increment Operator
• The post increment operator is used to increment the value of some
variable after using it in an expression.
• In the post increment the value is used inside the expression, then
incremented by one.
• If the expression is a = b++; and b is holding 5 at first, then a will also hold
5. Because increase b by 1 after assigning it into a.
Syntax:
a = b ++;
Expression with Post Increment Operator -
Example
Program:
Output:
#include <stdio.h>
int main() Post Increment Operation
{
int x=10,a; a = 10
a= x++; x = 11
printf(“Post Increment Operation");
printf(“\n a = %d“,a);
printf(“\n x = %d“,x);
return 0;
}
EXPRESSION WITH PRE /
POST DECREMENT
OPERATOR
Expression with Pre Decrement Operator
• The pre decrement operator is used to decrement the value of some
variable before using it in an expression.
• In the pre decrement the value is decremented at first, then used inside the
expression.
• If the expression is a = --b; and b is holding 5 at first, then a will hold 4.
Because decrease b by 1, then set the value of a with it.
Syntax
a = -- b;
Expression with Pre Decrement Operator -
Example
Program:
Output:
#include <stdio.h>
int main() Pre Decrement Operation
{
int x=10,a; a=9
a= --x; x=9
printf(“Pre Decrement Operation");
printf(“\n a = %d“,a);
printf(“\n x = %d“,x);
return 0;
}
Expression with Post Decrement Operator
• The post decrement operator is used to decrement the value of some
variable after using it in an expression.
• In the post decrement the value is used inside the expression, then
decremented by one.
• If the expression is a = b--; and b is holding 5 at first, then a will also hold
5. Because decrease b by 1 after assigning it into a.
Syntax:
a = b --;
Expression with Post Decrement Operator -
Example
Program:
Output:
#include <stdio.h>
int main() Post Decrement Operation
{
int x=10,a; a=10
a= x--; X=9
printf(“Post Decrement Operation");
printf(“\n a = %d“,a);
printf(“\n x = %d“,x);
return 0;
}
EXPRESSION WITH
CONDITIONAL
OPERATORS
Expressions with Conditional Operator
• The conditional operator is kind of similar to the if-else statement as it
does follow the same algorithm as of if-else statement but the conditional
operator takes less space and helps to write the if-else statements in the
shortest way possible.
Syntax:
If else Statement:
Example:
#include <stdio.h>
int main() Output:
{
int m,n,max; Enter the value of m and n
printf("Enter the value of m and n"); 10 12
scanf("%d %d",&m,&n);
max=(m > n) ? m : n; The maximum is 12
printf("The maximum is %d",max);
return 0;
}
EXPRESSION WITH
ASSIGNMENT
OPERATORS
Assignment Operator
• Assignment operators are used to assigning value to a variable.
• The left side operand of the assignment operator is a variable and right
side operand of the assignment operator is a value.
• The value on the right side must be of the same data-type of the variable
on the left side otherwise the compiler will raise an error.
Assignment Operator - Example
Program
Output
L VALUE AND R VALUE IN
EXPRESSION
L value in Expression
• L-Value of Expressions refer to a memory locations.
• In any assignment statement L-Value of Expression must be a
container(i.e. must have ability to hold the data).
• Variable is the only container in C programming thus L Value must be any
Variable.
• L Value cannot be a Constant, Function or any of the available data type in
C. L-Value stands for Left Value. Diagram Showing L Value in Expression.
R value in Expression
• In any Assignment statement R-Value of Expression must be anything
which is capable of returning Constant Expression or Constant Value.
• R Value stands for Right value of the expression.
R value in Expression - Example
UNIT 2
Course Learning Outcome (CLO – 1)
return 0;
}
If – else Statements
• The if...else statement is an extension of the simple if statement.
• If the test expression is true, then the true-block statement(s), immediately
following the if statements are executed; otherwise, the false-block
statement(s) are executed.
• In either case, either true-block or false-block will be executed, not both.
• The general form is,
If – else Statements (Cont..)
• Let us consider an example of counting the number of boys and girls in a class. We use
code 1 for a boy and 2 for a girl.
• The program statement to do this may be written as follows:
• Here, if the code is equal to 1, the statement boy = boy + 1; is executed and the control is
transferred to the statement xxxxxx, after skipping the else part.
• If the code is not equal to 1, the statement boy = boy + 1; is skipped and the statement in
the else part girl = girl + 1; is executed before the control Xreaches the statement xxxxxxxx.
If – else Statements (Cont..)
• If the test expression is evaluated to true, statements inside the body of if
are executed and statements inside the body of else are skipped from
execution.
• If the test expression is evaluated to false, statements inside the body of
else are executed and statements inside the body of if are skipped from
execution.
If - else Statements - Example
// Check whether an integer is odd or even
Output:
#include <stdio.h>
int main()
Enter an integer: 10
{
10 is an even integer.
int number;
printf("Enter an integer: ");
scanf("%d", &number);
Enter an integer: 7
if (number%2 == 0)
10 is an odd integer.
{
printf("%d is an even integer.",number);
}
else
{
printf("%d is an odd integer.",number);
}
return 0;
}
If - else Statements - Example
// Find biggest among two numbers
Output:
#include <stdio.h>
int main()
y is greater than x.
{
int x, y;
x = 15;
y = 18;
if (x > y )
{
printf("x is greater than y");
}
else
{
printf("y is greater than x");
}
return 0;
}
Nested if – else Statements
• When a series of decisions are
involved, we may have to use
more than one if...else statement in
nested form.
• If the condition-1 is false, the
statement-3 will be executed;
otherwise it continues to perform
the second test.
• If the condition-2 is true, the
statement-1 will be evaluated;
otherwise the statement-2 will be
evaluated and then the control is
transferred to the statement-x.
Nested if – else Statements (Cont..)
Nested if – else Statements (Cont..)
• A commercial bank has introduced
an incentive policy of giving bonus
to all its deposit holders.
• The policy is as follows: A bonus of
2 per cent of the balance held on
31st December is given to every
one, irrespective of their balance,
and 5 per cent is given to female
account holders if their balance is
more than Rs. 5000.
Nested if – else Statements (Cont..)
• When nesting, care should be exercised to match every if with an else. Consider the
following alternative to the above program.
• In this case, else is associated with the outer if and therefore bonus is
calculated for the male account holders.
• However, bonus for the female account holders, whose balance is equal to
or less than 5000 is not calculated because of the missing else option for
the inner if.
Nested if - else Statements - Example
// Find biggest among three numbers else
{
#include <stdio.h> if(b > c)
void main( ) printf("b is the greatest");
{ else
int a, b, c; printf("c is the greatest");
printf("Enter 3 numbers..."); }
scanf("%d%d%d",&a, &b, &c); }
if(a > b)
{ Output:
if(a > c)
printf("a is the greatest"); Enter 3 numbers...
else 8 5 23
printf("c is the greatest"); C is the greatest
}
Nested if - else Statements - Example
Output:
Output:
Switch Statements - Example
// Print the color
Output:
Rule for Switch Statements
• The switch expression must be an integral type.
• Case labels must be constants or constant expressions.
• Case labels must be unique. No two labels can have the same value.
• Case labels must end with colon.
• The break statement transfers the control out of the switch statement.
• The break statement is optional. That is, two or more case labels may belong to the same
statements.
• The default label is optional. If present, it will be executed when the expression does not
find a matching case label.
• There can be at most one default label.
• The default may be placed anywhere but usually placed at the end.
• It is permitted to nest switch statements.
Difference between Switch case & Nested if
Switch case statement Nested if
• No two case statements can have identical • Same conditions ca be evaluated any
constants in the same switch. number of times.
• The switch case statement checks more • The nested if statement, switch case
option to take a decision. multiple conditions.
• In switch case statement “nested if” can • In nested if statement, switch case can be
be used. used.
• Switch case can check only constant • Nested if can check relational and logical
values. expressions.
The Nested Switch Statements
• It is possible to have a switch as a part of the statement sequence of an outer
switch. Even if the case constants of the inner and outer switch contain common
values, no conflicts will arise.
Nested Switch Statements - Example
Output:
ITERATION
Iteration
• Iteration is the process where a set of instructions or statements is
executed repeatedly for a specified number of time or until a condition is
met.
• These statements also alter the control flow of the program and thus can
also be classified as control statements in C Programming Language.
• Iteration statements are most commonly know as loops.
• Also the repetition process in C is done by using loop control instruction.
•
Iteration (Cont..)
•
Iteration (Cont..)
• For example, suppose we want to calculate the sum of squares of all
integers between 1 and 10, we can write a program using the if statement
as follows:
This program does the following things:
1. Initializes the variable n.
2. Computes the square of n and adds it to
sum.
3. Tests the value of n to see whether it is
equal to 10 or not. If it is equal to 10, then the
program prints the results.
4. If n is less than 10, then it is incremented
by one and the control goes back to compute
the sum again. The program evaluates the
statement: sum = sum + n * n
Iteration (Cont..)
• The test may be either to determine whether the loop has been repeated
the specified number of times or to determine whether a particular
condition has been met.
• The C language provides for three constructs for performing loop
operations. They are:
1) The while statement.
2) The do statement.
3) The for statement.
Iteration (Cont..)
Sentinel Loops
• Based on the nature of control variable and the kind of value assigned to it for testing the
control expression, the loops may be classified into following two general categories:
1) Counter-controlled loops
2) Sentinel-controlled loops
• When we know in advance exactly how many times the loop will be executed, we use a
counter controlled loop. We use a control variable known as counter.
• The counter must be initialized, tested and updated properly for the desired loop
operations.
• The number of times we want to execute the loop may be a constant or a variable that is
assigned a value.
• A counter-controlled loop is sometimes called definite repetition loop.
• In a sentinel-controlled loop, a special value called a sentinel value is used to change the
loop control expression from true to false.
THE WHILE LOOP
While Loop
• A while loop in C programming
repeatedly executes a target
statement as long as a given
condition is true.
• in the while loop, first the
condition is checked and then the
statements in while loop are
executed.
• If a condition is false at the first
place then the do while would run
once, however the while loop
would not run at all.
While Loop
• The while is an entry-controlled loop statement. The test-condition is
evaluated and if the condition is true, then the body of the loop is
executed.
• After execution of the body, the test-condition is once again evaluated and
if it is true, the body is executed once again. This process of repeated
execution of the body continues until the test-condition finally becomes
false and the control is transferred out of the loop.
• On exit, the program continues with the statement immediately after the
body of the loop.
• The body of the loop may have one or more statements. The braces are
needed only if the body contains two or more statements. It is a good
practice to use braces even if the body has only one statement.
While Loop (Cont..)
• The body of the loop is executed 10 times for n = 1, 2, ....., 10, each time
adding the square of the value of n, which is incremented inside the loop.
• The test condition may also be written as n < 11; the result would be the
same. This is a typical example of counter-controlled loops. The variable n
is called counter or control variable.
While Loop - Example
// Sum of the digits
Output:
#include <stdio.h>
Enter the value:
int main()
456
{
The sum of the digit is 15
int n,r,sum=0;
printf(“ Enter the value of n:”);
scanf(“%d”,&n);
Enter the value:
while(n>0)
123
{
The sum of the digit is 6
r=n%10;
sum=sum=r;
n=n/10;
}
printf(“The sum of the digit is %d“,sum);
return 0;
}
While Loop - Example
// Given number is Armstrong or not
Output:
#include <stdio.h>
int main() {
Enter the value of n:
int n,r,arm=0,t;
2589
printf("Enter the value of n:");
scanf("%d",&n);
The number 2589 is not
t=n;
an Armstrong number.
while(n>0) {
r=n%10;
arm=arm+r*r*r;
n=n/10;
Enter the value of n:
}if(t==arm)
153
printf("The number %d is an armstrong number.",t);
else
The number 153 is an
printf("The number %d is not an armstrong number.",t);
Armstrong number.
return 0;
}
While Loop - Example
// Factorial on n numbers
Output:
#include <stdio.h>
int main() Enter the value of n:
{ 5
int n,i=1,fact=1;
printf("Enter the value of n : "); 5! = 120
scanf("%d",&n);
while(i<=n)
{
fact=fact*i; Enter the value of n:
i++; 6
}
printf("%d ! = %d",n,fact); 6! = 720
return 0;
}
While Loop - Example
// Find the average of n numbers
#include <stdio.h> Output:
int main() {
int n,i=0;
How many numbers : 5
float x,avg,sum=0;
printf("How many numbers : "); Enter the numbers
scanf("%d",&n); 23 76 9 456 632
printf("Enter the numbers\n"); Average = 239.200000
while(i<n)
{
scanf("%f",&x);
sum=sum+x; How many numbers : 5
i++; Enter the numbers
}
56 65 45 85 21
avg=sum/n;
printf("Average = %f",avg); Average = 54.400002
return 0;
}
THE DO WHILE LOOP
Do While Loop
• A do while loop is similar to while loop with one exception that it executes
the statements inside the body of do-while before checking the condition.
• The do statement, the program proceeds to evaluate the body of the loop
first.
• At the end of the loop, the test-condition in the while statement is
evaluated.
• If the condition is true, the program continues to evaluate the body of the
loop once again. This process continues as long as the condition is true.
• When the condition becomes false, the loop will be terminated and the
control goes to the statement that appears immediately after the while
statement.
Do While Loop (Cont..)
• The general form is,
Do While Loop (Cont..)
• The test-condition is evaluated at the bottom of the loop, the do...while
construct provides an exit-controlled loop and therefore the body of the
loop is always executed at least once.
• This segment of a program reads a
number from the keyboard until a
zero or a negative number is keyed
in, and assigned to the sentinel
variable number.
• The test conditions may have
compound relations as well. For
instance, the statement
UNIT 2
Course Learning Outcome (CLO – 1)
Array
• The array size need not be specified explicitly when initial values are
included as part of an array definition.
Output: