Cunit 2
Cunit 2
x= a++ 1. x= a
x= ++a 1. a=a+1
2. a=a+1 2. x= a
INCREMENT AND DECREMENT OPERATORS-
Example
void main()
{
int x,i; i=10;
x=i++;
printf("x: %d",x);
printf("i: %d",i);
}
void main() void main()
{ {
int x,i; i=10; int x,i; i=10;
x=++i; x=++i;
printf("x: %d",x); printf("x: %d",x);
printf("i: %d",i); printf("i: %d",i);
} }
Conditional Operators
• The conditional operator takes three operands, so it is a ternary operator.
The conditional operator is the only ternary operator available in the C
programming language, so the names ternary operator and conditional
operator are used alternatively to mean the conditional operator.
Bitwise operators
Unary Operators
1. sizeof :
sizeof(int)
2. Unary Plus/Minus:
+3, -3
3. Cast Operator:
float(x)
#include <stdio.h>
int main() printf("%d\n",sizeof(a));
{ printf("%d\n",sizeof(b));
int a; printf("%d\n",sizeof(c));
float b; printf("%d\n",sizeof(d));
char c; printf("%d\n",sizeof(e));
double d; printf("%d\n",sizeof(f));
short e; printf("%d\n",sizeof(g));
long int f; printf("%d",sizeof(h));
long long int g; return 0;
long double h; }
Expressions
An expression is a sequence of operands and operators that reduces to
a single value. It can be simple or compound.
Simple Expression contains only one operator. Ex: 2+3
Complex Expression contains more than one operator
ex: 2+3+6*5
The order in which the operators in complex expressions are evaluated
is determined by a set of priorities known as precedence.
If two operators with the same precedence occur in a complex
expression, another attribute that takes control is associativity.
Expressions (Conti.)
• An expression always reduces to a single value.
• Simple expressions are divided into six categories:
• Primary
• Postfix
• Prefix
• Unary
• Binary
• Ternary
Precedence and
Associativity
Evaluate an Expression
Let a=3 , b=4, c=5 , then Solve:
x= a* 4 + b / 2 – c * b
y = --a * (3+b) / 2 – c++ * b
#include<stdio.h>
int main()
Evaluate an {
//local declarations
Expression int a=3;
int b=4;
Let a=3 , b=4, c=5 , then Solve: int c=5;
int x;
x= a* 4 + b / 2 – c * b int y;
y = --a * (3+b) / 2 – c++ * b
//statements
printf("initial values of variables:\n");
printf("a=%d\tb=%d\tc=%d\n\n",a,b,c);
x=a*4+b/2-c*b;
printf("value of the expression a*4+b/2-c*b :%d\n",x);
y=--a*(3+b)/2-c++*b;
printf("value of the expression --a*(3+b)/2-c++*b :%d\n",y);
printf("values of variables are now:\n");
printf("a=%d\tb=%d\tc=%d\n\n",a,b,c);
return 0;
}
Problems : Evaluation of expressions
• If x=2, y=3 and z=1 ; evaluate the following expressions
• x+2/6+y
• y-3*z+2
• z-(x+z)%2+4
• x-2*(3+z)+y
• y++ + z-- + x++
Type Conversion
• Expressions with different data types?
To evaluate, one of the types must be converted
1. Implicit Type Conversion.
2. Explicit Type Conversion.
Implicit Type Conversion
When the types of the two operands in a binary expression are different, C
automatically converts one type to another based on:
• Conversion Rank
• Conversion in Assignment Expressions
• Promotion
• Demotion
• Implicit type casting means conversion of data types without losing its original
meaning. This type of typecasting is essential when you want to change data
types without changing the significance of the values stored inside the variable.
• Implicit type conversion in C happens automatically when a value is copied to its
compatible data type. During conversion, strict rules for type conversion are
applied. If the operands are of two different data types, then an operand having
lower data type is automatically converted into a higher data type.
#include<stdio.h>
int main(){
short a=10; //initializing variable of short data type
int b; //declaring int variable
b=a; //implicit type casting
printf("%d\n",a);
printf("%d\n",b); Output:
}
10
10
#include <stdio.h>
main() {
int number = 1;
char character = 'k'; /*ASCII value is 107 */
int sum;
sum = number + character;
printf("Value of sum : %d\n", sum ); Output:
}
Value of sum : 108
Conversion Rank
#include <stdio.h>
main() {
int num = 13;
char c = 'k'; /* ASCII value is 107 */
float sum;
sum = num + c;
printf("sum = %f\n", sum ); Output:
}
sum = 120.000000
Explicit type Conversions
• Uses unary cast operator:
int a;
(float) a;
#include<stdio.h>
int main()
{
float a = 1.2;
int b = (int)a + 1;
printf("Value of a is %f\n", a);
printf("Value of b is %d\n", b); Output:
return 0;
} Value of a is 1.200000
Value of b is 2
#include <stdio.h>
int main()
{
int a=5; O U T P U T :
a = 5
float x=5.63; y = 1 0 . 6 3
x = 5 . 6 3
float y=a+x; //implicit promotion c = 1 6 . 2 6
float c= x+y; b = 1 5 . 6 3
z = 1 6
int b= x + (int) y; // explicit conversion
int z= x+ y;
printf("a= %d\n", a);
printf("x= %f\n", x);
printf("y= %f\n", y);
printf("c=%f\n", c);
printf("b=%d\n", b);
printf("z=%d\n", z) ;
return 0;
}
#include <stdio.h>
int main()
{ Output:
int a=5;
float x=5.63;
float y=a+x; //implicit promotion
a= 5
float c= x+y; x= 5.630000
int b= x + (int) y; // explicit conversion y= 10.630000
int z= x+ y;
printf("a= %d\n", a); c=16.260000
printf("x= %f\n", x); b=15
printf("y= %f\n", y);
printf("c=%f\n", c); z=16
printf("b=%d\n", b);
printf("z=%d\n", z) ;
return 0;
}
//statements
// Demonstrate
Automatic promotion of printf("bool + char is char:%c\n", b+c);
numeric types: printf(“int * short is int: %d\n",i*s);
printf("float * char is float: %f\n",d*c);
#include<stdio.h>
#include<stdbool.h> c= c + b; //bool promoted to char
int main() d= d + c; // char promoted to float
{ b= false;
//local declarations b= - d; //Float demoted to bool
bool b=true;
char c='A'; printf("\n After execution...\n");
66
float d=245.3; printf("char + true: %c\n”,c); 310.3
0c
int i=3650; printf("float + char :%f\n",d);
short s=78; printf("bool = - float:%f\n",b);
return 0;
}
#include<stdio.h> printf("fltnum1 contains: %6.2f\n",fltnum1);
int main() printf("fltnum2 contains: %6.2f\n",fltnum2);
{ fltnum3=(double)(intnum1/intnum2);
//local declarations printf("\n(double)(intnum1 /intnum2):%6.2f\n",fltnum3);
char achar='\0‘;
int intnum1=100; fltnum3=(double)intnum1/intnum2;
int intnum2=45; printf("\n(double) intnum1 /intnum2:%6.2f\n",fltnum3);
double fltnum1=100.0; achar=(char)(fltnum1 - fltnum2);
double fltnum2=45.0; printf("(char)(fltnum1 - fltnum2) :%c\n",achar);
double fltnum3; return 0;
}
//statements
printf("achar numeric : %3d\n",achar);
printf("intnum1 contains: %3d\n",intnum1);
printf("intnum2 contains: %3d\n",intnum2);
Programs
1. C-Program to calculate quotient and reminder of two numbers.
2. C-Program to calculate the sum of three numbers / C-Program to demonstrate
a Simple Calculator.
3. C-Program to calculate the area and circumference of a circle using PI as a
defined constant.
c=2*pi*r
area= pi*r*r
4. C-Program to convert temperature given in Celsius to Fahrenheit and
Fahrenheit to Celsius
C = 5/9(°F – 32)
F = 9/5°C + 32
Selection-Making Decision
Two-Way Selection
• If… else
• Null else
• Nested if statements
If…else
• An if…else statement is a composite
statement used to make decisions
between two alternatives.
Ex:
1 2
If (a > 1)
a++;
else
a--;
If…..else wIth compound statements:
if (j !=3)
{
b++;
printf(“%d”, b);
}
else
{
c++;
printf(“%d”,c);
}
NULL else statements
If (expression)
{ If (expression)
-------------- {
} --------------
} //endif
else
;
1. Program to find the entered number is odd or even?
statement n;
Example Programs
• Write a program to find largest of 3 numbers.
#include<stdio.h>
int main()
{
int a,b,c;
printf("Enter the value of a,b,c\n");
scanf("%d %d %d",&a, &b, &c);
if((b>a && c>a))
{
if(b>c)
printf("b is largest");
else
printf("c is largest");
}
else
printf("a is largest");
return 0;
}
Dangling else problem
Dangling else problem
if (exp)
{
if(exp)
st1
}
else
{
st2
}
Return Statement
• A return statement terminates a function. All functions including the
main must have a return statement. When there is no return
statement at the end of the function, the system inserts one with a
void return value.
return expression;
A return value of 0 tells the OS that the program executed successfully
Multiway Selection
In addition to two-way selection, most programming
languages provide another selection concept known as
multiway selection. Multiway selection chooses among
several alternatives. C has two different ways to
implement multiway selection: the switch statement
and else-if construct.
int main()
{
int n = 0;
#include <stdio.h>
int main()
{
int marks = 91;
if (marks <= 100 && marks >= 90)
printf("A+ Grade");
else if (marks < 90 && marks >= 80)
printf("A Grade");
else if (marks < 80 && marks >= 70)
printf("B Grade");
else if (marks < 70 && marks >= 60)
printf("C Grade");
else if (marks < 60 && marks > 50)
printf("D Grade");
else if (marks < 50)
printf("F Failed");
return 0;
}
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 rupees 1 per unit.
All users are charged a minimum of rupees 100 as a meter charge. If the
total amount is more than Rs 400, then an additional surcharge of 15%
of the total amount is charged.
Write a program to read the name of the user, the number of units
consumed, and print out the charges.
#include<stdio.h> else
#include<string.h> charge = 1.00;
amt = unit_con*charge;
void main()
if (amt>400)
{ surcharge = amt*15/100.0;
int cust_no, unit_con;
float charge,surcharge=0, amt, total_amt; total_amt = amt+surcharge;
char nm[25];
printf("\t\t\t\nElectricity Bill\n\n");
printf("Enter the customer IDNO :\t");
printf("Customer IDNO :\t%d",cust_no);
scanf("%d",&cust_no);
printf("\nCustomer Name :\t%s",nm);
printf("Enter the customer Name :\t"); printf("\nunit Consumed :\t%d",unit_con);
scanf("%s",nm); printf("\nAmount Charges @Rs. %4.2f per
printf("Enter the unit consumed by customer :\t"); unit:\t%0.2f",charge,amt);
scanf("%d",&unit_con); printf("\nSurchage Amount :\t%.2f",surcharge);
printf("\nMinimum meter charge Rs :\t%d",100);
if (unit_con <200 )
printf("\nNet Amount Paid By the Customer
charge = 0.80; :\t%.2f",total_amt+100);
else if (unit_con>=200 && unit_con<300) }
Repetition Statements
(loops)
74
Concept of Loop
We must design a loop so that before and after the
iteration, it checks to see if the task is done. If it is not
done the loop repeats one more time, or else it
terminates.
• Pretest Loop
• Post-Test Loop
Event Controlled loops
Initialize Initialize
Condition Condition
false
Condition Action
true
Update
Action
Condition
Update
Condition
true Condition
false
exit exit
Post-test loop
Pre-test loop
Counter Controlled loops
Set count to 0 Set count to 0
false
Count < n Action
true
Increment
Action
count
Increment
count
true Count < n
false
exit exit
Post-test loop
Pre-test loop
Loop Comparison
• Repetition Statements
• While
• Do
• For
79
Repetition Statements
• Repetition statements allow us to execute a statement or
a block of statements multiple times
• Often they are referred to as loops
• Like conditional statements, they are controlled by
boolean expressions
• Java has three kinds of repetition statements:
while
do
for
• The programmer should choose the right kind of loop
statement for the situation
80
The while Statement
• A while statement has the following syntax:
while ( condition )
statement;
81
Logic of a while Loop
condition
evaluated
true false
statement
5
The while Statement
• An example of a while statement:
int count = 0;
while (count < 2)
{
printf(“welcome to java!");
count++;
}
• If the condition of a while loop is false initially, the
statement is never executed
• Therefore, the body of a while loop will execute
zero or more times
83
animation
7
animation
Trace while Loop, cont.
(count < 2) is true
int count = 0;
while (count < 2)
{
printf("Welcome to Java!");
count++;
}
8
animation
Trace while Loop, cont.
Print Welcome to Java
int count = 0;
while (count < 2)
{
printf("Welcome to Java!");
count++;
}
9
animation
Trace while Loop, cont.
Increase count by 1
int count = 0; count is 1 now
10
animation
Trace while Loop, cont.
(count < 2) is still true since count
int count = 0; is 1
11
animation
Trace while Loop, cont.
Print Welcome to Java
int count = 0;
while (count < 2)
{
printf("Welcome to Java!");
count++;
}
12
animation
Trace while Loop, cont.
Increase count by 1
int count = 0; count is 2 now
13
animation
Trace while Loop, cont.
(count < 2) is false since count is 2
int count = 0; now
14
animation
Trace while Loop
The loop exits. Execute the next
int count = 0; statement after the loop.
15
Example (Average)
#include<stdio.h>
int main()
{
int sum=0, count=0;
float avg;
93
Infinite Loops
• Executing the statements in the body of a while loop must
eventually make the condition false
• If not, it is called an infinite loop, which will execute until the user
interrupts the program
• This is a common logical error
• You should always double check the logic of a program to ensure that
your loops will terminate
94
Infinite Loops
• An example of an infinite loop:
int count = 1;
while (count <= 25)
{
printf(“%d”,count);
count = count - 1;
}
• This loop will continue executing until the user
externally interrupts the program.
95
Nested Loops
• Similar to nested if statements, loops can be nested as well
• That is, the body of a loop can contain another loop
• For each iteration of the outer loop, the inner loop iterates
completely
96
Nested Loops
• How many times will the string "Here" be printed?
count1 = 1;
while (count1 <= 10)
{
count2 = 1;
while (count2 <= 20)
{
System.out.println ("Here");
count2++;
}
count1++;
}
10 * 20 = 200
97
The do Statement
• A do statement has the following syntax:
do
{
statement;
}
while ( condition );
98
Flowchart of a do Loop
statement
true
condition
evaluated
false
99
The do Statement
• An example of a do loop:
int count = 0;
do
{
printf("Welcome to Java!");
count++;
}
while (count < 2); Don’t forget this semicolon!
100
Comparing while and do
The while Loop The do Loop
statement
condition
evaluated
true
condition
true false
evaluated
statement
false
101
animation
Trace do Loop
Initialize count
int count = 0;
do
{
printf("Welcome to Java!");
count++;
} while (count < 2);
25
animation
26
animation
do
{
printf("Welcome to Java!");
count++;
} while (count < 2);
27
animation
28
animation
29
animation
do
{
printf("Welcome to Java!");
count++;
} while (count < 2);
30
animation
do
{
printf("Welcome to Java!");
count++;
} while (count < 2);
31
animation
Trace do Loop
The loop exits. Execute the next
int count = 0; statement after the loop.
do
{
printf("Welcome to Java!");
count++;
} while (count < 2);
32
The for Statement
• A for statement has the following syntax:
110
The for Statement
• A for loop is functionally equivalent to the following while
loop structure:
initialization;
while ( condition )
{
statement;
increment;
}
• Example:
for(int i = 0; i < 10; i++) int i = 0;
{ while(i < 10)
//some code {
} //some code
i++;
}
Flowchart of a for loop
initialization
condition
evaluated
true false
statement
increment
112
Flowchart - example
Initial-Action i=0
Action-After-Each-Iteration i++
113
(A) (B)
The for Statement
• The initialization section can be used to declare a variable
114
Infinite for-loop
• If the condition is left out, it is always considered to be
true, and therefore creates an infinite loop
115
animation
116
animation
117
animation
118
animation
119
animation
120
animation
121
animation
122
animation
123
animation
124
Which Loop to Use?
Use the one that is most intuitive and comfortable for
you. In general:
- A for loop may be used if the number of repetitions is
known, as, for example, when you need to print a
message 100 times.
- A while loop may be used if the number of repetitions
is not known, as in the case of reading the numbers
until the input is 0.
- A do-while loop can be used to replace a while loop if
the loop body has to be executed before testing the
continuation condition. 125
#include <stdio.h>
int main() {
int i = 1;
while (i <= 5)
{
printf("%d\n", i);
++i;
}
return 0;
}
Output:
#include <stdio.h>
int main() { 1
int i = 1; 2
3
4
while (i <= 5) 5
{
printf("%d\n", i);
++i;
}
return 0;
}
#include <stdio.h>
int main() {
int i;
• The break statement causes execution to “break” out of the repetitive loop
execution (goes to just outside the loop’s closing “}”)
132
Example:
int i;
0
int i; 1
2
3
for (i = 0; i < 10; i++) {
if (i == 4) {
break;
}
printf("%d\n", i);
}
Continue
The continue statement breaks one iteration (in the loop), if a specified
condition occurs, and continues with the next iteration in the loop.
int i;
for (i = 0; i < 10; i++) {
if (i == 4) {
continue;
}
printf("%d\n", i);
}
Continue
The continue statement breaks one iteration (in the loop), if a specified
condition occurs, and continues with the next iteration in the loop.
int i; Output:
0
1
for (i = 0; i < 10; i++) { 2
if (i == 4) { 3
continue; 5
} 6
7
printf("%d\n", i); 8
} 9
goto
• Goto statement in C is a jump statement that
is used to jump from one part of the code to
any other part of the code in C.
• Goto statement helps in altering the normal
flow of the program according to our needs.
• This is achieved by using labels, which means
defining a block of code with a name so that
we can use the goto statement to jump to that
label.
Example:
#include <stdio.h>
#include <math.h> // to make the number positive multiply by -1
n = n*(-1);