C Programming Notes
C Programming Notes
Module-2
Operators in C
An operator is a symbol that tells the compiler to perform specific mathematical and logical
functions. The different operators supported in ‘C’ are:
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Bitwise Operators
6. Unary Operators 🡪 Increment and Decrement
7. Ternary/ Conditional Operator
8. Special Operators
2. Relational Operators: These are used to compare two quantities. The output will be either 0 (False) or 1
(True). The different relational operators are:
3. Logical Operators: These are used to test more than one condition and make decision. The different
logical operators are: NOT, AND, OR
✓ Logical NOT (!) The output is true when input is false and vice versa. It accepts only
one input.
Input Output
X !X
0 1
1 0
✓ Logical AND (&&) The output is true only if both inputs are true. It accepts two or more
inputs.
Input Output
X Y X && Y
0 0 0
0 1 0
1 0 0
1 1 1
✓ Logical OR (| |) The output is true only if any of its input is true. It accepts two or more
inputs.
Input Output
X Y X || Y
0 0 0
0 1 1
1 0 1
1 1 1
4. Assignment Operators: These are used to assign the result or values to a variable. The different
types of assignment operators are:
Simple Assignment a = 10
Shorthand Assignment a += 10 🡪 a = a + 10
Multiple Assignment a = b = c = 10
5. Bitwise Operators: These works on bits and performs bit by bit operations. The different types of
bitwise operators are:
i. Bitwise NOT (~)
ii. Bitwise AND (&)
iii. Bitwise OR (|)
iv. Bitwise XOR (^)🡪 Output is True when odd number of 1’s are present.
v. Bitwise left shift (<<)
vi. Bitwise right shift (>>)
X ~X
0 1
1 0
✓ Bitwise Left Shift (<<) 🡪Shift specified number of bits to left side.
X 0 1 0 0 0 1 1 0
X<<2 0 0 0 1 1 0 0 0
✓ Bitwise Right Shift (>>)🡪 Shift specified number of bits to right side.
X 0 1 0 0 0 1 1 0
X>>2 0 0 0 1 0 0 0 1
Pre-increment Post-increment
First value of the operand is incremented First value of the operand is used for evaluation
then, it is incremented (added) by 1.
(added) by 1 then, it is used for evaluation.
Ex: ++a Ex: a++
5. EXPRESSIONS
sum = a + b
✓ Following table provides the Precedence and Associativity of operators:
=
*= /= %=
+= -= &= Assignment operators Right to left 14
^= |=
<<= >>=
, Comma operator Left to right 15
TYPE CONVERSION
⮚ Converting the value of one data type to another type is called as Type Conversion.
⮚ It occurs when mixed data occurs.
⮚ Type conversion is performed by a compiler.
⮚ In type conversion, the destination data type can’t be smaller than the source data type.
⮚ Conversion at Compile time
⮚ Generally takes place when in an expression more than one data type is present. In such conditions type
conversion (type promotion) takes place to avoid loss of data.
✓ In typing casting, a data type is converted into another data type by the programmer using
the casting operator during the program design.
✓ In typing casting, the destination data type may be smaller than the source data type when
converting the data type to another data type, that’s why it is also called narrowing
conversion.
✓ It is a forced conversion used to convert operand/ variables of larger data type to smaller size
or vice versa.
Syntax/Declaration:-
destination_datatype = (target_datatype) variable;
( ): is a casting operator.
✓ Ex: int a = 7, c;
float b = 4.0;
b = a % (int) b; printf(“%d” , c);
These ate the statements in which all the commands or instructions are executed in linear order without
any branching.
Following typical C code for area of triangle when 3 sides are given:
Scanf(“%d%d%d”, &a,&b,&c);
S=(a+b+c)/2.0;
Area= sqrt ((s*(s-a)*(s-b)*(s-c));
Printf(“Area=%d”, area);
Following is the typical C code to check whether the number is odd or even:
#include<stdio.h>
int main()
{
scanf(“%d”, &n);
if (n%2= = 0)
printf (“%d is even”, n)
else
printf(“%d is odd:,n);
}
These non sequential or branching statements are again classified into two types:
1. if statement
2. if – else statement
3. Nested if else statement
4. Cascaded if else (also called else-if ladder)
Multi-way Selection statement
5. Switch statement
✓ The Expression is evaluated first, if the value of Expression is true (or non zero) then Statement1 will be
executed; otherwise if it is false (or zero), then Statement1 will be skipped and the execution will jump to the
Statement2.
✓ Remember when condition is true, both the Statement1 and Statement2 are executed in sequence. This is
illustrated in Figure1.
Note: Statement1 can be single statement or group of statements.
Expression True
False Statement1
Statement2
Example:
#include<stdio.h>
void main( )
{
int a=20, b=11;
if (a >b)
{
printf(“A is greater\n”);
}
}
Output: A is greater
if (Expression)
{
Statement1; true-block
}
else
{
Statement2; true-block
}
Statement3;
✓ If the Expression is true (or non-zero) then Statement1 will be executed; otherwise if it is false (or zero),
then Statement2 will be executed.
✓ In this case either true block or false block will be executed, but not both.
✓ This is illustrated in Figure 2. In both the cases, the control is transferred subsequently to the Statement3.
Fals Tru
Expression
e e
Statement2 Statement1
Statement3
Example:
void main( )
{
int a=10, b=11;
if (a >b)
{
printf(“A is greater\n”);
}
else
{
printf(“B is greater”);
}
}
Output: B is greater
3. Nested if .. else statement: When a series of decisions are involved, we have to use more than one
if..else statement in nested form as shown below in the general syntax.
if (Expression1)
{
if(Expression2)
{
Statement1;
}
else
{
Statement2;
}
}
else if (Expression3)
{
Statement3;
}
else
{
Statement4;
}
✓ If Expression1 is true, check for Expression2, if it is also true then Statement1 is executed.
✓ If Expression1 is true, check for Expression2, if it is false then Statement2 is executed.
✓ If Expression1 is false, then Statement3 is executed.
✓ Once we start nesting if .. else statements, we may encounter a classic problem known as dangling else.
✓ This problem is created when no matching else for every if.
✓ C solution to this problem is a simple rule “always pair an else to most recent unpaired if in the current
block”.
✓ Solution to the dangling else problem, a compound statement.
✓ In compound statement, we simply enclose true actions in braces to make the second if a compound
statement.
Example1:
#include<stdio.h>
void main( )
{
int a = 20, b=15, c=3;
if(a>b)
{
if(a>c)
{
printf(“A is greater\n”);
}
else
Downloaded by Kavya Nayak (nayakkavya2008@[Link])
Prof. Sunanda H G Page 11
lOMoARcPSD|60099504
{
printf(“C is greater\n”);
}
}
else
{
if(b>c)
{
printf(“B is greater\n”);
}
else
{
printf(“C is greater\n”);
}
}
Output: A is greater
Example2:
# include <stdio.h>
# include<conio.h>
void main()
{
int marks;
printf(“ enter the marks of the subject:\n”);
scanf (“%d”, &marks);
if (m>=40)
{
if (m>=60)
printf(“ first class”);
else
printf (“ second class”);
}
else
printf (“Fail”);
}
4. else if ladder or cascaded if else: There is another way of putting ifs together when multipath
decisions are involved. A multi path decision is a chain of ifs in which the statement associated with
each else is an if. It takes the following form.
if (Expression1)
{
Statement1;
}
else if(Expression2)
{
Statement2;
}
else if(Expression3)
{
Statement3;
}
else
{
Statement4;
}
Next Statement;
Example1:
#include<stdio.h>
void main( )
{
int a=20, b=5, c=3;
if((a>b) && (a>c))
printf(“A is greater\n”);
else if((b>a) && (b>c))
printf(“B is greater\n”);
else if((c>a) && (c>b))
printf(“C is greater\n”);
else
printf(“All are equal\n”);
}
Output: A is greater
Example2:
C- program to create result w.r.t., pass and fail, first class. Distinction, second class and fail using else if
ladder.
# include <stdio.h>
# include<conio.h>
Void main()
{
int m ;
clrscr();
printf(“ enter the marks:\n”) ;
scanf (“%d”, &m) ;
if (m<=34)
printf (“Fail”) ;
5. Switch Statement
✓ C language provides a multi-way decision statement so that complex else-if statements can be easily
replaced by it. C language’s multi-way decision statement is called switch.
General syntax of switch statement is as follows:
switch(choice)
{
case label1: block1;
break;
case label2: block2;
break;
case label3: block-3;
break;
default:default-block;
break;
}
✓ Here switch, case, break and default are built-in C language words.
✓ If the choice matches to label1 then block1 will be executed else if it evaluates to label2 then block2
will be executed and so on.
✓ If choice does not matches with any case labels, then default block will be executed.
In this program if ch=1 case ‘1’ gets executed and if ch=2, case ‘2’ gets executed and so on.
Unconditional branching statements: These are the statements in which alters the flow of
execution of a program from one part to another part unconditionally There are 4 types of
unconditional branching statements.
1) goto Statement
2) break Statement
3) continue Statement
4) return Statement
1. goto Statement: It is a simple unconditional branching statement used to transfer the flow of
execution from one part to another part without any test condition but just with a label name. (it is
also known as jump statement, here the control will jump to the specified label in the program.)
Syntax:
goto Label ;
✓ A label is a valid variable name. But many programmers avoid the usage of goto statement
because it results in unstructured programming.
✓ Label need not be declared and must be followed by colon.
✓ Label should be used along with a statement to which control is transferred.
✓ Label can be anywhere in the program either before or after the goto label.
.
Syntax Example
goto label; void main( )
{
statement1 int a=5,
b=7; goto
; end; a=a+1;
b=b+1;
statement2 end: printf(“a=%d b=%d”, a,b);
}
;
label:
✓ Here control jumps to label skipping statement1 and statement2 without verifying any
condition tha t is the reason we call it unconditional Forward jumping statement.
✓ If label appear before goto then it jumps backward repeating the statements between label
and goto label called Backward jump
2. break Statement: It is an another simple unconditional branching statement used to come out
of the particular control structure (if or switch or loop ) without any test condition.
Syntax:
break ;
Syntax Flowchart
#include<stdio.h>
while(condition) void main( )
{ {
Statements; int i;
if(condition) for(i=1; i<=5; i++)
break; {
Statements; if(i==3)
} break;
printf(“%d”, i)
}
}
OUTPUT 12
Syntax:
continue ;
Syntax Flowchart
#include<stdio.h>
while(condition) void main( )
{ {
Statements; int i;
if(condition) for(i=1; i<=5; i++)
continue; {
Statements; if(i==3)
} continue;
printf(“%d”, i)
}
}
OUTPUT 1245
[Link] statement: return is also an unconditional branching statement generally used with
function programs.
Syntax :
return ;
#include<stdio.h>
#include<conio.h>
void main( )
{
int i=1, fact=1, n ,loop;
clrscr( ) ;
/* C program to find only odd no in the given range n using continue statement:*/
#include<stdio.h>
#include<conio.h>
void main( )
{
int i , n ,
clrscr( ) ;
[Link] loop statement: It is the popular loop statement used to execute the statements repeatedly
for a specified number of times. Here user will know in advance, how many times the set of
statements with in loop will be executed. This is the simple loop can be used for almost all type of
iterative statements.
Syntax:
for ( Initial Condn ; Test Condn ; Modifying Value )
{
Statement 1;
Statement 2;
------------ n;
}
Where for is a key word, initial condition is the beginning loop index should be terminated by the
symbol semicolon. Test condition determines how many times loop should be repeated, and this
also should be terminated by semicolon. Modifying value represents the step value either in
increment or decrement order.
Statements 1 to n are known as body of the loop, these statements will be repeatedly executed as
long as the test condition is true. These statements should be enclosed with two flower brackets.
Note: Like if and switch statements for statements should not be ended with semicolon.
Next stmt.
Note: In for loops whether both i++ or ++i operations will be treated as pre-increment only.
Ex 1. Write a C program to find sum of first N natural numbers using for loop.
Hint: ( 1 + 2 + 3 + 4 + . . . . . . . . . . n )
# include< stdio.h>
# include< conio.h>
void main( )
{
int n, i, sum=0 ;
sum = sum + i ;
}
Ex 2. Write a C program to find sum of squares of N natural numbers using for loop.
Hint: ( 1 2 + 2 2 + 3 2 + 4 2 + ----------- n2 )
# include< stdio.h>
void main( )
{
int n, i, sq_sum=0 ;
printf( “ Enter the total no of elements to be summed\n”) ;
scanf( “%d” , &n) ;
for (i=0 ; i<=n ; i++ )
sq_sum = sq_sum + i * i ;
Ex 3. Write a C program to find sum of odd no. and even no. in first N natural no.
Solution: / * C program to find odd sum and even sum of first N natural numbers */
# include< stdio.h>
void main()
{
int n, i, even_sum=0 , odd_sum=0 ;
printf( “ Enter the total no of elements to be summed\n”) ;
scanf( “%d” , &n) ;
for (i=1 ; i<=n ; i+=2 )
odd_sum = odd_sum + i ;
even_sum = even_sum + i ;
fact = fact * i ;
[Link] loop statement: It is an another form of loop statement used to execute the statements
repeatedly for a specified number of times. Here user will not know exactly how many times a set
of statements are to be repeated. Loop execution depends on the test condition which checked at
the beginning of the loop. Hence it is also known as pre-tested or entry controlled loop.
Syntax :
Where while is a key word, Test condition determines how many times loop should be repeated,
this looping statement does not include initial condition and modifying value with in the loop
statement instead they are either in the body of the loop or outside the loop.
Here also the statements followed by while will be repeatedly executed as long as the test condition
is true. These statements should be enclosed with two flower brackets.
Note: Like if and for statements while also should not be ended with semicolon.
Initial condition
Next stmt.
** Here modifying value is included in the body of the statement itself, and initial
Condition will be outside the while.
Ex 1: Write a C program to find sum of first N natural numbers using while loop.
Hint: ( 1 + 2 + 3 + 4 + -----------n )
Solution: / * C program to find sum of first N natural numbers using while loop*/
# include< stdio.h>
void main( )
{
int n , i=1 , sum=0 ;
printf( “ Enter the total no of elements to be summed\n”) ;
scanf( “%d” , &n) ;
while ( i<=n )
{
sum = sum + i ;
i = i++
}
Ex 2. Write a C pgm to find sum of squares of N natural numbers using while loop.
Hint: ( 1 2 + 2 2 + 3 2 + 4 2 + ----------- n2 )
Solution: / * C program to find sum of squares of first N natural numbers */
# include< stdio.h>
# include< conio.h>
void main( )
{
int n, i=1, sq_sum=0 ;
clrscr( ) ;
printf( “ Enter the total no of elements to be summed\n”) ;
scanf( “%d” , &n) ;
while ( i<=n )
{
sq_sum = sq_sum + i * i ;
i = i++ ;
}
Prof. Sunanda H G Page 25
Ex 3. Write a C program to find sum of odd no. and even no. in first N natural no.
Hint: ( 1 + 3 + 5 + ----------- ) & ( 2 + 4 + 6 + ------------ )
Solution: / * C program to find odd sum and even sum of first N natural numbers */
# include< stdio.h>
# include< conio.h>
void main( )
{
int n, i =1, j=2, even_sum=0 , odd_sum=0 ;
printf( “ Enter the total no of elements to be summed\n”) ;
scanf( “%d” , &n) ;
while ( i<=n )
{
odd_sum = odd_sum + i ;
i=i+2;
}
while (j<=n )
{
even_sum = even_sum + j ;
j=j+2;
}
printf ( “ The sum of odd no. in first N natural no=%d” , odd_sum) ;
printf ( “ The sum of even no. in first N natural no=%d” , even_sum) ;
i = i++ ;
}
printf ( “ The factorial of given no=%d” , fact) ;
}
3. do while loop statement: It is a repetitive statement used to execute set of statements depending
on the condition which is checked at the end of loop structure.( opposite to while statement) Hence
it is also referred as post tested or exit control loop. Here the statements followed by while will
be executed at least once irrespective of the test condition.
Syntax:
do
{
Statement 1;
Statement 2;
------------ n;
while (Test Condition) ;
}
Where do is a key word, the statements followed by do will be executed at least once irrespective
of the test condition. Here also the statements below do should be enclosed with in two flower
brackets.
Note: Most importantly while statement should end with semicolon.
Flow chart:
loop:
do
Statement 1;
Statement 2;
Modifying val;
----------- n;
True
Ex: 1 Ex 1: Write a C pgm to find sum of first N natural numbers using do-while
Hint: ( 1 + 2 + 3 + 4 + -----------n )
Solution: / * C program to find sum of first N natural numbers using do while loop*/
# include< stdio.h>
void main( )
{
int n , i=1, sum=0 ;
printf( “ Enter the total no of elements to be summed\n”) ;
scanf( “%d” , &n) ;
do
{
sum = sum + i ;
i = i++ ;
} while ( i<=n ) ;
Ex 2 : Write a C pgm to display the string BIT n times using do-while loop
Solution: / * C program to find sum of first N natural numbers using do while loop*/
# include< stdio.h>
# include< conio.h>
void main()
{
int n , i=1;
printf( “ Enter the no of times the string is to be printed \n”) ;
scanf( “%d” , &n) ;
do
{
Printf(“ BIT\n”);
i = i++ ;
} while ( i<=n ) ;
printf ( “ Bangalore-60) ;
Statements after while will be executed Statements after do will be executed at least
only when the test condn. is true. once irrespective of the test condition.
while loop is widely used in pgms do while is rarely used looping structure.
when compared do while.
There is no semi colon at the end of while The semi colon is compulsory at the end of while.
Syntax: Syntax:
while (Test Condition) do
{ {
Statement 1; Statement 1;
Statement 2; Statement 2;
------------ n; ------------ n;
} } while (Test condition) ;
Example:
Note: If updation is not present in loops then, it will execute infinite times.
If initialization is not given then, program prints nothing.
Pascal's triangle:
Pascal triangle is one of the classic example taught to engineering students. It has many
interpretations. One of the famous one is its use with binomial equations.
All values outside the triangle are considered zero (0). The first row is 0 1 0 whereas only 1 acquire
a space in pascal's triangle, 0s are invisible. Second row is acquired by adding (0+1) and (1+0).
The output is sandwiched between two zeroes. The process continues till the required level is
achieved.
Pascal's triangle can be derived using binomial theorem. We can use combinations and factorials
to achieve this.
Algorithm
Assuming that we're well aware of factorials, we shall look into the core concept of drawing a
pascal triangle in step-by-step fashion −
Implementation
#include <stdio.h>
int main()
{
int rows, num = 1, space, i, j;
printf("Enter number of rows: ");//number of rows for generating pascal triangle
scanf("%d",&rows);
printf("%4d", num);
}
printf("\n");
}
return 0;
}
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1