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

C Programming

Ramaprasad H.C
9945426447
ramaprasadhc@10seconds.co.in

10 SECONDS 1
Current Job Market
Ramaprasad H C

10 SECONDS 2
 As per Nasscom Indian IT sector,
which crossed USD 100 billion
mark last year, will clock at least
double-digit growth this year.
 As per Nasscom, Indian IT industry
currently employed 25 lakh people.
If we look at a projected 10-11 %
growth, then we are looking at 2-2.5
lakh additional people being hired by
the industry.
 India produces around 7.5 laks
engineers every year. This number
10 SECONDS 3
is expected to be 13 laks from 2014
Work Force Supply and
Demand Scenario

10 SECONDS 4
a – 1000 b – 2000 c – 3000
register int c, b, a;
int a, b, c; - rejected
register int a, b, c;

10 SECONDS 5
int a; register int b; volatile int c;

10 SECONDS 6
a – 1000 b – 2000 c – 3000
register int c, b, a;
int a, b, c; - 97 students - Rejected
register int a, b, c;

10 SECONDS 7
int a; register int b; volatile int c;

10 SECONDS 8
 AICTE report shows, we have approx
13 lakhs Engineering seats in India.
 Approx 7 lakhs fresh job aspirants
every year.

10 SECONDS 9
What companies are
looking for

10 SECONDS 10
register int c, b, a;
int a, b, c; - Rejected
register int a, b, c;

10 SECONDS 11
int a; register int b; volatile int c;
% - Remainder Sign of the result
10 % 3 = 1 is always sign of
-10% 3 = -1 the numerator…
10 % -3=1
-10 % -3 =-1
Note: we cannot Can we apply No
apply % operator modulus operator
on floating point on floating point
numbers… numbers?
I have one client fmod ( ) –
from UK / US .. He remainder of 2
/ She wants that. floating point
What I should do? numbers…

10 SECONDS 12
int a; int a;
a = 5; a = 5;
a++; ++a;
printf (“%d”, a); printf (“%d”, a);

Post increment and pre


increment operators behave in a
same manner if we use them
independently

10 SECONDS 13
One has to apply the concept of post increment and pre
increment
Post increment – first use the value, then increment
Pre increment – first increment and then use the value

int a, b, c, d;
a = 5;
b = 6;
c = a++ + ++b;
d = ++a + b++;

10 SECONDS 14
int a = 5;
Printf (“%d%d%d%d%d%d”, a++,
++a, a--, --a, a++, ++a);

10 SECONDS 15
Comma operator
int a, b, c;
c = (a = 5, b = 6, a+b);
printf (“%d”, c);

10 SECONDS 16
 Software lobby Nasscom says only
25% of graduates working in IT are
readily employable.
 India's $100-billion IT industry is
already spending > $1.5 billion a year
on readying fresh hired graduates.
 IT recruitment experts say often
freshers are not business-ready due
to the industry-academia gap, and
have to be trained extensively.
10 SECONDS 17
C Programming
 Modulus (%) operator cannot be
applied on floating point numbers.
 Modulus operator gives the
remainder.
 Sign of the remainder is always same
as the sign of the numerator.
 Can we apply mod operator on
floating point numbers?
 fmod () – remainder of 2 floating
point numbers
10 SECONDS 18
Integer and Float conversion
 An arithmetic operation between an integer and
integer always yields an integer result.
 An operation between a real and real always yields a
real result.
 An operation between an integer and real always
yields a real result. In this operation integer is first
promoted to a real and then the operation is
performed. Hence the result is real.
Ex:
5/2=2
5.0 / 2 = 2.500000
Type conversion in assignments
int i = 3.5;
float a = 4;

10 SECONDS 19
int nofb, nofg;
float r;
nofb = 10;
nofg = 3;
r = nofb /nofg; 3
r = nofb / (float)nofg; 3.333333

10 SECONDS 20
Comma operator

 int a, b, c;
 c = (a = 10, b = 20, a+b);
 Printf (“Sum = %d\n”, c);
 a = 10
 b = 20
 c = 30
 Sum = 30
 Left to right. Result of the right most
expression is assigned to LHS
10 SECONDS 21
Hierarchy of operations
Priority Operators

1st */%

2nd +-

3rd =

10 SECONDS 22
EX:
 result = 2 * 3 / 4 + 4 / 4 + 8 – 2 + 5 / 8;
 = 6 / 4 + 4 / 4 + 8 – 2 + 5 / 8;
 1 + 4 / 4 + 8 – 2 + 5 / 8;
 1 + 1+ 8 – 2 + 0
 8

10 SECONDS 23
Unit 2: The Decision Control
Structure
 C has three major decision making
instructions –
 The if statement
 The if-else statement
 Nested if-else
 else if ladder
 The switch statement

10 SECONDS 24
The if statement
 Syntax
if (this condition is true)
execute one statement;

if (this condition is true)


{
1st stmt; If one wants to execute
2nd stmt; more than one statement
3rd stmt; then braces are must.
.
.
.
Nth statement;
}

10 SECONDS 25
void main ( )
{
int a;
printf (“Enter one number \n”);
scanf (“%d”, &a);
if (a > 0)
printf (“Number is positive\n”);
printf (“Hello world \n”);
}

10 SECONDS 26
void main ( )
{
int a;
printf (“Enter one number \n”);
scanf (“%d”, &a);
if (a > 0)
{
printf (“Number is positive\n”);
printf (“Hello world \n”);
}
} 10 SECONDS 27
void main ( )
{
int a;
printf (“Enter one number \n”);
scanf (“%d”, &a);
if (a > 0)
{
printf (“Number is positive\n”);
printf (“Hello world \n”);
}
printf (“good day \n”);
10 SECONDS 28

}
Relational operators
 ==
 !=
 <
 >
 <=
 >=
 10 == 5 != 4 >= 5 < 9 > 10 <= 0

10 SECONDS 29
 10 == 5 != 4 >= 5 < 9 > 10 <= 0
 10 == 5 != 0 <9 > 10 <= 0

 10 == 5 != 1 > 10 <= 0
 10 == 5 != 0 <= 0
 10 == 5 != 1
 0 != 1
 1

10 SECONDS 30
Ex1:
# include <stdio.h>
void main ( )
{
int num;
printf (“Enter a number less than 10”);
scanf (“%d”, &num);
if (num < 10)
printf (“What an obedient servant you
are \n”);
printf (“Hello world \n”);

} 10 SECONDS 31
Example: 2
The current year and the year in which the employee joined the
organization are entered through the keyboard. If the number of
years for which the employee has served the organization is
greater than 3, then a bonus of Rs. 2500/- is given to the
employee. If the years of service is not greater than 3, the
program should do nothing.

// Program: Calculation of Bonus Single line comment


// Author: H.C. Ramaprasadjois
// Date: 24 / 07 / 2009
# include <stdio.h>
void main ( )
{
int bonus, cy, yoj, yos;
printf (“Enter current year and year of joining \n”);
scanf (“%d%d”, cy, yoj);
yos = cy – yoj;
if (yos > 3)
{
bonus = 2500;
printf (“Bonus = %d”, bonus);
}
}
10 SECONDS 32
The if..else statement
Syntax: if (this condition is true)
if (this condition is true) {
execute one statement; 1st stmt;
else 2nd stmt;
execute one statement; . More than one statement
.
Nth stmt;
}
else
{
1st stmt;
2nd stmt;
. More than one statement
.
Nth stmt;
}

10 SECONDS 33
void main ( )
{
int a;
printf (“Enter one number \n”);
scanf (“%d”, &a);
if (a >= 0)
printf (“Number is positive\n”);
else
printf (“Number is negative\n”);
printf (“Hello world \n”);
}
10 SECONDS 34
void main ( )
{
int a;
printf (“Enter one number \n”);
scanf (“%d”, &a);
if (a >= 0)
printf (“Number is positive\n”);
printf (“Hello India \n”);
else
printf (“Number is negative\n”);
printf (“Hello world \n”);
} 10 SECONDS 35
void main ( )
{
int a;
printf (“Enter one number \n”);
scanf (“%d”, &a);
if (a >= 0)
{
printf (“Number is positive\n”);
printf (“Hello India \n”);
}
else
{
printf (“Number is negative\n”);
printf (“Hello world \n”);
} 10 SECONDS 36
Example 1:
C Program to find larger of two
numbers.
/* Program: Larger of two numbers
Author: Ramaprasadjois Multi line comment
Date: 24 / 07 / 2009 */
# include <stdio.h>
void main ( )
{
int num1, num2;
printf (“Enter 2 numbers \n”);
scanf (“%d%d”, &num1, &num2);
if (num1 > num2)
printf (“%d is larger than %d”, num1, num2);
else
printf (“%d is larger than %d”, num2, num1);
}

10 SECONDS 37
Example 2:
In a company an employee is paid as under:
If his basic salary is less than Rs.1500, then HRA = 10% of basic salary and DA =
90% of basic salary. If his salary is either equal to or above Rs.1500, then HRA =
Rs.500 and DA = 98% of basic salary. If the employee’s salary is input through the
keyboard write a program to find his gross salary.

/* Program: else
Author: {
Date: hra = 500;
*/ da = bs * 98 / 100;
# include <stdio.h> }
void main ( )
{ gs = bs + hra + da;
float bs, gs, da, hra; printf (“gross salary = %f”, gs);
printf (“Enter basic salary \n”); }
scanf (“%f”, &bs)
if (bs < 1500)
{
hra = bs * 10 / 100;
da = bs * 90 / 100;
}

10 SECONDS 38
Logical operators
 && Logical and
 || Logical or
 ! Logical Not

 !10&&5||0
 0&&5||0
 0||0
 0
10 SECONDS 39
 10==5 != 0 <= 4 > 45 < 90 >= 10
 0!= 0 <= 4 > 45 < 90 >= 10

 0 <=4 > 45 < 90 >= 10


 1 > 45 < 90 ..=10
 0< 90 >= 10
 1 >= 10
 0

10 SECONDS 40
Note:

 In C language any non-zero


# include <stdio.h> value is considered as true
void main ( ) and zero is considered as
false.
{  Another common mistake
int i; while using the if statement
is to write a semicolon (;)
printf (“Enter value for i \n”); after the condition.
scanf (“%d”, &i);  ; is considered as do nothing
if (i = 5); statement in C language.
printf (“You entered 5 If (this condition is true)
\n”); execute one stmt;
else else
printf (“You entered execute one stmt;
something other than 5 \n”);
}

10 SECONDS 41
If (some condition)
stamt;
Else;
stmt;

10 SECONDS 42
The conditional operator (?:)
 Syntax:
 expression 1 ? expression 2 : expression 3;

 Example:
 int x, y;
 scanf (“%d”, &x);
 y = (x > 5 ? 3 : 4);
 The above statement can also be written as follows:
 if ( x > 5)
 y = 3;
 else
 y = 4;

10 SECONDS 43
Symbolic constants
 Example 1: program without symbolic constants
 # include <stdio.h>
 void main ( )
 {
 float r, area;
 printf (“Enter radius \n”);
 scanf (“%f”, &r);
 area = 3.1412 * r * r;
 printf (“area of a circle = %f”, area);
 }

10 SECONDS 44
Symbolic constants cont..
 Example 2:
 # include <stdio.h>
 # define PI 3.1412
 void main ( )
 {
 float r, area;
 printf (“Enter radius \n”);
 scanf (“%f”, &r);
 area = PI * r * r;
 printf (“area of a circle = %f”, area);

10 SECONDS 45
Keywords / Reserved words
 Extended keywords – specific to
compiler –
 Different compilers?
 Turbo C – Microsoft
 Dev C++ -
 Gcc
 ANSI - _ _ asm, _ _ far, _ _ near;

10 SECONDS 46
Keywords / Reserved words
 Comma operator
int a, b, c;
c = (a = 10, b = 20, a + b);
Printf (“sum = %d”, c);

10 SECONDS 47
Increment operator
int a; int a;
a = 5; a = 5;
a++; ++a;
printf (“%d”, a); printf (“%d”, a);

10 SECONDS 48
int a, b, c, d;
a = 5;
b = 6;
c = a++ + ++b;
d= ++a + b++;
Printf (“%d%d%d%d”, a, b, c, d);

10 SECONDS 49
int a = 5;
printf (“%d%d%d%d%d%d”,
a++, ++a, --a, a--, ++a, a++);

10 SECONDS 50
void main ( ) int add (int p, int q)
{ {
int a, b, c; int r;
int add (int, int); r = p + q;
a = 10; return r;
b = 20; }
c = add (a, b);
printf (“%d”, c)
}

10 SECONDS 51
int a; int a;
a = 5; a = 5;
a++; ++a;
printf (“%d”, a); printf (“%d”, a);

6 6

10 SECONDS 52
int a, b, c, d;
a = 5;
b = 10;
c = a++ + ++b;
d = ++a + b++;
printf (“%d%d%d%d”, a, b, c, d);

10 SECONDS 53
int a;
a = 5;
printf (“%d%d%d%d%d%d\n”,
a++, ++a, --a, a--, ++a, a++);

10 SECONDS 54
int a, b; int a, b;
a = 5; a = 5;
b = a++; b = ++a;
Printf (“%d%d” a, b); Printf (“%d%d”, a,b );
% Can we apply mod operator on
10 % 3 = 1 floating point numbers?
-10 % 3 = -1 No
10 % -3=1
-10 % -3=-1
I want .. I have client from UK / fmod () – which gives remainder
US, he wants .. What to do? of 2 floating point numbers

10 SECONDS 55
Decision Control Problems

10 SECONDS 56
# include <stdio.h>
int main ( )
{
int a = 300, b, c;
if (a >= 400)
b = 300;
c = 200;
printf (“%d%d”, b, c);
return 0;
}
10 SECONDS 57
# include <stdio.h>
int main ( )
{
int a = 500, b, c;
if (a >= 400)
b = 300;
c = 200;
printf (“%d%d”, b, c);
return 0;
}
10 SECONDS 58
# include <stdio.h>
int main ( )
{
int x = 10, y = 20;
if ( x == y);
printf (“%d%d”, x, y);
return 0;
}

10 SECONDS 59
# include <stdio.h>
int main ( )
{
int x = 3, y, z;
y = x = 10;
z = x < 10;
printf (“x = %d y = %d z = %d”, x, y,
z);
return 0;
}
10 SECONDS 60
# include <stdio.h>
int main ( )
{
int i = 65;
char j = ‘A’;
if (i == j)
printf (“C is good”);
else
printf (“C is headache”);
return 0;
} 10 SECONDS 61
# include <stdio.h>
void main ()
{
if (condition)
printf (“Hello”);
else
printf (“world”);
}

10 SECONDS 62
Unit 3: The Loop Control
Structure
Note:
 Increment & Decrement operator.
 There are 3 methods by way of which
we can repeat a part of program.
They are:
 for
 while
 do..while
10 SECONDS 63
 for statement
 Syntax

for (initialize counter; test counter; increment
counter)

execute one statement;

 for (initialize counter; test counter; increment
counter)
 {
 do this;
 and this; More than one statement.
 and this;
 }

10 SECONDS 64
Example 1
 C program to print the message “Hello
world” 5 times.
 # include <stdio.h>
 void main ( )
 {
 int count;
 for (count = 0; count < 5; count++)
 printf (“Hello world \n”);
 printf (“Hello India \n”);
10 SECONDS 65

 }
 # include <stdio.h>
 void main ( )
 {
 int count;
 for (count = 0; count <5;count++)
{
 printf (“Hello world \n”);

Printf (“Hello India \n”);


}
Printf (“Good day \n”);
 }

10 SECONDS 66
Example 2
 C program to calculate simple interest for 3 sets of p, t and r.
 # include <stdio.h>
 void main ( )
 {
 float p, t, r, si;
 int count;
 for (count = 1; count <= 3; count++)
 {
 printf (“Enter values of p, t and r \n”);
 scanf (“%f%f%f”, &p, &t, &r);
 si = p * t * r / 100;
 printf (“simple interest = %f”, si);
 }
 }

10 SECONDS 67
While loop
 Syntax:
 initialize loop counter;
 while (test loop counter using a
condition)
 {
 do this;
 and this;
 increment loop counter;
 }
10 SECONDS 68
void main ()
{
int count;
count = 0;
while (count < 5)
{
printf (“Hello world \n”);
count ++;
}
printf (“Good day \n”);
}
10 SECONDS 69
Example:
 Calculation of simple interest  while (count <= 3)
for 3 set of p, t and r  {
 # include <stdio.h>  printf (“Enter
 void main ( ) values for p, t and r \n”);
 {  scanf
 float p, t, r, si; (“%f%f%f”, &p, &t, &r);
 int count;  si = p * t * r /
 count = 1; 100;
 
 printf (“simple
interest = %f”, si);

 count++;
 }
 }

10 SECONDS 70
Note:
 is not necessary that a loop counter
must only be an int. It can even be a
float

10 SECONDS 71
The break statement
 We often come across situations where we
want to jump out of a loop instantly,
without waiting to get back to the
conditional test.
 The keyword break allows us to do this.
 When break is encountered inside any
loop, control automatically passes to the
first statement after the loop.

10 SECONDS 72
Example:
 Write a Program to determine whether a
number is prime or not.
 # include <stdio.h>
 void main ( )
 {
 int num, i;
 printf (“Enter a number \n”);
 scanf (“%d”, &num);
 i = 2;

10 SECONDS 73
 while (i <= num – 1)
 {
 if (num % i == 0)
 {
 printf (“Not a prime number
\n”);
 break;
 }
 i++;
 }
 if (i == num)
 printf (“Prime number \n”);
 }

10 SECONDS 74
The continue statement

 In some programming situations, we want


to take the control to the beginning of the
loop, bypassing the statements inside the
loop, which have not yet been executed.
 The keyword continue allows us to do this.
 When continue is encountered inside any
loop, control automatically passes to the
beginning of the loop.

10 SECONDS 75
Example:

 # include <stdio.h>
 void main ( )
 {
 int i, j;
 for (i = 1; i <= 2; i++)
 {
 for (j = 1; j <= 2; j++)
 {
 if (i == j)
 continue;

 printf (“%d%d”, i, j);
 }
 }
 }

10 SECONDS 76
The do..while loop
 Initialization;
 do
 {
 this;
 and this;
 and this;
 and this;
 } while (this condition is true);

10 SECONDS 77
Example:

 # include <stdio.h>
 void main ( )
 {
 do
 {
 printf (“Hello world \n”);
 } while (1 < 4);
 }

10 SECONDS 78
int count = 0;
do
{
printf (“Hello world \n”);
printf (“Hello India \n”);
count++;
}while (count < 3);
Printf (“good day \n”);

10 SECONDS 79
Loop Control Problems

10 SECONDS 80
# include <stdio.h>
int main ( )
{
int i = 1;
while (i <= 10);
{
printf (“%d”, i);
i++;
}
return 0;
}
10 SECONDS 81
# include <stdio.h>
int main ( )
{
int x = 4;
while (x == 1)
{
x = x – 1;
printf (“%d”, x);
--x;
}
return 0;
}
10 SECONDS 82
# include <stdio.h>
int main ( )
{
int x = 4, y, z;
y = --x;
z = x--;
printf (“%d%d%d”, x, y, z);
return 0;
X=2
Y=3
Z=3
10 SECONDS 83

}
int a;
a = 5;
a++;
Printf (“%d”, a);

int a;
a = 5;
++a;
printf (“%d”, a);

10 SECONDS 84
 int a, b, c, d;
 a = 5, b = 6;

 c = a++ + ++b;
 = (5 ) + (7)
 d = ++a + b++;
 = ( 7) + ( 7)

A=7
B=8
10 SECONDS 85
 C = 12
 int a = 5;
 Printf (“%d%d%d%d%d%d”,

 a++, ++a, --a, a--, a++, ++a);


 665766
 A=7

 Int b = 10, a = 5;
 Printf (“%d%d%d%d”, a++, b++, --a, --
b);
 4 949
 A=5
 B = 10
10 SECONDS 86
# include <stdio.h>
int main ( )
{
int x = 4, y = 3, z;
z = x-- - y;
printf (“%d%d%d”, x, y, z);
return 0;
}

10 SECONDS 87
# include <stdio.h>
int main ( )
{
while (‘a’ < ‘b’)
printf (“Malayalam is a palindrome
\n”);
return 0;
}

10 SECONDS 88
# include <stdio.h>
int main ( )
{
int i;
while (i = 10)
{
printf (“%d”, i);
i = i+1;
}
return 0;
}
10 SECONDS 89
# include <stdio.h>
int main ( )
{

int x = 4, y = 0, z;
while (x >= 0)
{
x--;
y++;
if (x == y)
continue;
else
printf (“%d%d”, x, y);
}
return 0;
}

10 SECONDS 90
# include <stdio.h>
int main ( )
{
int x = 4, y = 0, z;
while (x >= 0)
{
if (x == y)
break;
else
printf (“%d%d”, x, y);
x--;
y++;
}
return 0;
}

10 SECONDS 91
Case Control Instruction

10 SECONDS 92
int main ( )
{
int x = 4, y = 0, z;
while (x >= 0)
{
if (x == y)
break;
else
printf (“%d%d”, x, y);
x--;
y++;
}
return 0;
}

10 SECONDS 93
Int choice’
Printf (“1. paid premium before due
date \n”);
Printf (“2. Not paid \n”);
Scanf (“%d”, &choice);
Switch (choice);
{
case 1: balance = balance + 2000;
case 2: balance = balance + 5000;
}

10 SECONDS 94
# include <stdio.h>
int main ( )
{
int k;
float j = 2.0;
switch (k = j + 1)
{
case 3:
printf (“Trapped \n”);
break;
default:
printf (“Caught \n”);
}
return 0;
} 10 SECONDS 95
# include <stdio.h>
int main ( )
{
int ch = ‘a’ + ‘b’;
switch (ch)
{
case ‘a’:
case ‘b’:
printf (“You entered b \n”);
case ‘A’:
printf (“a as in ashar”);
case ‘b’ + ‘a’:
printf (“You entered a and b”);
}
return 0;
} 10 SECONDS 96
# include <stdio.h>
int main ( )
{
int i = 1;
switch (i – 2)
{
case -1:
printf (“Feeding fish \n”);
case 0:
printf (“Weeding grass \n”);
case 1:
printf (“Mending roof \n”);
default:
printf (“Just to survive \n”);
}
return 0;
}
10 SECONDS 97
Unit 4: Arrays & Datatypes
 Homogeneous group of elements are
called arrays.
 Declaration
 int a[10];
 float b[20];

10 SECONDS 98
How to accept elements into an
array?

 int a[5], i;
 for (i = 0; i < 5; i++)
 scanf (“%d”, &a[i]);

10 SECONDS 99
How to print elements of an
array?

 for (i = 0; i < 5; i++)


 printf (“%d\t”, a[i]);

10 SECONDS 100
C program to accept 5 elements
into an array and to print the
elements.

 # include <stdio.h>
 void main ( )
 {
 int a[5], i;
 printf (“Enter 5 elements \n”);
 for (i = 0; i < 5; i++)
 scanf (“%d”, &a[i]);
 printf (“Array elements are: \n”);
 for (i = 0; i < 5; i++)
 printf (“%d”, a[i]);
 }

10 SECONDS 101
C program to accept n elements into an array and to
print the elements.

 # include <stdio.h>
 void main ( )
 {
 int a[20], i, n;
 printf (“Enter the value for n \n”);
 scanf (“%d”, &n);
 printf (“Enter array elements \n”);
 for (i = 0; i < n; i++)
 scnaf (“%d”, &a[i]);
 printf (“Array elements are: \n”);
 for (i = 0; i < n; i++)
 printf (“%d”, a[i]);
 }

10 SECONDS 102
Array Initialization

 int num[5] = { 10, 20, 30, 40, 50};


 int n[ ] = {10, 20, 30};
 int a[3] = {10, 20, 30, 40};
 int a[4] = {10, 20};

10 SECONDS 103
Bound checking

 In C, there is no check to see if the


subscript used for an array exceeds the size
of the array. Data entered with a subscript
exceeding the array size will simply be
placed in memory outside the array.
 This may lead to unpredictable results,
and there will be no error message to warn
you that you are going beyond the array
size.
 In some cases computer may just hang.
10 SECONDS 104
Passing array elements to a function (Call by
value)

 # include <stdio.h>
 void main ( )
 {
 int i;
 void display (int);
 int marks[ ] = {10, 20, 30, 40, 50};
 for (i = 0; i < 5; i++)
 display (marks[i]);
 }
 void display (int m)
 {
 printf (“%d”, m)
 }

10 SECONDS 105
Passing array elements to a
function (Call by reference)

 # include <stdio.h>
 void main ( )
 {
 int i;
 void display (int *);
 int marks[ ] = {10, 20, 30, 40, 50};
 for (i = 0; i < 5; i++)
 display (&marks[i]);
 }
 void display (int *m)
 {
 printf (“%d”, *m)
 }

10 SECONDS 106
Integers, long and short

 shorts are at least 2 bytes big.


 longs are at least 4 bytes big.
 shorts are never bigger than ints.
 ints are never bigger than longs.

10 SECONDS 107
Integers, long and short cont..
Compiler Short Int Long

16 bit 2 2 4
(Turbo C /
C++)
32 bit 2 4 4
(Visual
C++)

10 SECONDS 108
Integers, long and short cont..
 Ex:
 short int a;
 short b;
 long int c;
 long d;

10 SECONDS 109
Integers, signed and unsigned
 unsigned int num_students;
 Note:
 With unsigned int, the range of permissible integer
values (for 16-bit ) will shift from -32767 to + 32767
to the range 0 to 65535.
 Thus declaring an integer as unsigned almost doubles
the size of the largest possible value that it can
otherwise take.
 This so happens because on declaring the integer as
unsigned, the left-most is now free and is not used to
store the sign of the number.
 Unsigned integer still occupies two bytes.

10 SECONDS 110
Chars, signed and unsigned
 Ordinary char has a range from -128
to +128.
 Unsigned char has a range from 0 to
255.

10 SECONDS 111
Floats, doubles and long
doubles
 float – 4 bytes %f
 double – 8 byes %lf
 long double – 10 bytes %Lf
 Note:
 The sizes and ranges of int, short
and long are compiler dependent.
The above are on 16-bit compiler.

10 SECONDS 112
Data Type Range Bytes Format
Signed char -128 to + 127 1 %c
Unsigned char 0 to 255 1 %c
Short signed -32767 to 2 %d
int +32767
Short unsigned 0 to 65535 2 %u
int
Signed int 4 %d
Unsigned int 4 %u
Long signed int 4 %ld
Long unsigned 4 %lu
int
Float 4 %f
Double 8 %lf
Long double 10 %Lf
10 SECONDS 113
Unit 5: Functions & Pointers
 C program to add 2 integer numbers without
using functions
 # include <stdio.h>
 void main ( )
 {
 int a, b, res;
 printf (“Enter 2 numbers \n”);
 scanf (“%d%d”, &a, &b);
 res = a + b;
 printf (“Result = %d”, res);
 getch ( );
 }

10 SECONDS 114
C program to add 2 integer numbers with the use of function
# include <stdio.h>

void main ( )
{
int a, b, res;
int add (int p, int q); // Function declaration Calling Function
printf (“Enter 2 numbers \n”);
scanf (“%d%d”, &a, &b);
res = add (a, b); // Function call or Function activation or Function invocation or
Function instantiation. In this function variable a and b
are called actual parameters.
printf (“Result = %d”, res);
getch ( );
}

int add (int p, int q)


{
int sum;
Called function. In this function variables p and q are
sum = p + q; called formal parameters.
return sum;
}

10 SECONDS 115
void praveen ( ) int suman (int p, int q)
{ {
int a, b, c; int r;
int suman (int, r = p + q;
int); return r;
a = 10; }
b = 20;
c = suman (a, b);
printf (“%d”, c);
}

10 SECONDS 116
C program to add two floating point
numbers without using functions
 # include <stdio.h>
 void main ( )
 {
 float p, q, res;
 printf (“Enter 2 floating point numbers
\n”);
 scanf (“%f%f”, &p, &q);
 res = p + q;
 printf (“Result = %f”, res);
 }

10 SECONDS 117
Void main ( ) int add (int p, int q)
{ {
int a, b, c;
int r;
int add (int, int);
r = p + q;
a = 10;
b = 20; retrun r;
c =add (a, b); }
printf (“%d”, c);
}

10 SECONDS 118
C program to add two floating point numbers
with the use of function

 # include <stdio.h>
 void main ( )
 {
 float p, q, res;
 float sum (float, float);
 printf (“Enter 2 floating point numbers \n”);
 scanf (“%f%f”, &p, &q);
 res = sum (p, q);
 printf (“Result = %f”, res);
 }
 float sum (float p, float q)
 {
 float res;

 res = p + q;
 return res;
 }

10 SECONDS 119
Pointers
Ordinary Variable Pointer Variable

int a; int *a;

Meaning: a is an ordinary Meaning: a is a pointer


variable, which can hold variable, which can hold the
numbers like 10, 20, 30 etc address of an integer
variable.
float b; float *b;

Meaning: b is an ordinary Meaning: b is a pointer variable,


variable, which can hold which can hold the address of a
10 SECONDS 120
numbers like 10.5, 24.5, 32.8 floating point variable
Definition:

 Pointer is a variable which can hold


the address of another variable.

10 SECONDS 121
C program to swap contents of 2 variables
without using pointers
 # include <stdio.h>  void swap (int p, int q)
 void main ( )  {
 {  int temp;
 int a, b; 
 void swap (int p, int q);  temp = p;
 printf (“Enter 2 numbers  p = q;
\n”);  q = temp;
 scnaf (“%d%d”, &a, &b);  }
 printf (“Elements before
swapping \n”);
 printf (“a = %d \n b = %d”,
a, b);
 swap (a, b);
 printf (“Elements after
swapping \n”);
 printf (“a = %d \n b = %d”,
a, b);
 }

10 SECONDS 122
C program to swap contents of
2 variables using pointers
 # include <stdio.h>  void swap (int *p, int *q)
 void main ( )  {
 {  int temp;
 int a, b; 
 void swap (int * , int *);  temp = *p;
 printf (“Enter 2 numbers  *p = *q;
\n”);  *q = temp;
 scnaf (“%d%d”, &a, &b);  }
 printf (“Elements before
swapping \n”);
 printf (“a = %d \n b = %d”,
a, b);
 swap (&a, &b);
 printf (“Elements after
swapping \n”);
 printf (“a = %d \n b = %d”,
a, b);
 }

10 SECONDS 123
if (!printf (“Hello”))
printf (“Hello”);
else
printf (“World”);

Hello World.

10 SECONDS 124
Important points on array
 int num[]={24,34,12,44,56,17};
 By mentioning the name of the array, we get
its base address.
 Thus by saying *num,we would refer to the
zeroth element of the array(i.e 24 in this case).
 *num and *(num+0) both refers to 24.
 When we say num[i], the c compiler internally
converts it to *(num+i).This means that all the
following notations are same.
 num[i].....*(num+i)...*(i+num)...i[num]

10 SECONDS 125
Pointers and Arrays

pa 9700

a[0] a[1] a[2] a[3] a[4]


20 30 40 50 60

9700 9702 9704 9706 9708

The notation a[i] refers to the ith element of the


array. If pa is a pointer to an integer declared as
int *pa;
Then the assignment pa=&a[0]; sets pa to point to
the first element of a. /* pa=a; */
The assignment x=*pa; will copy the contents of a[0]
into x.
10 SECONDS
126
Pointers and Arrays

pa 9700 pa+1 pa+2

a[0] a[1] a[2] a[3] a[4]


20 30 40 50 60

9700 9702 9704 9706 9708

*(pa+1) refers to contents of a[1].


Note:
------
1) pa=&a[0]; ( or pa=a;)
2) a[i] can also be written as *(a+i)-→ content
3) &a[i] can also be writen as (a+i).--→address
As such pa[i] and *(pa+i) are also identical.
10 SECONDS
127
Program which reads in array elements and finds
the sum of the array elements using pointers.

#include <stdio.h>
int main()
{ int a[10],*pa,i,n=10,sum=0;
pa=&a[0];
for(i=0;i<10;i++)
scanf(“%d”,pa+i); /* or scanf(“%d”,&pa[i]); */
for(i=0;i<10;i++)
sum=sum + *(pa+i); /* or sum=sum + pa[i] */
printf(“\n sum=%d”,sum);
}

10 SECONDS 128
Pointers and strings
char str[]=“Infosys”;
char *cptr=“Infosys”;
Both declarations are same.
The compiler allocates enough space to hold the
string along with its terminating null character.
A pointer pointing to a string contains the base
address of the character array and entire array
or part of array can be accessed using this
pointer.

10 SECONDS 129
Program to illustrate pointers and strings
#include <stdio.h>
int main() cptr=cptr+5;
{ char str1[]=“INFO puts(cptr);
TECH”;
cptr=str2;
char str2[]=“Java and
puts(cptr);
Internet”;
cptr=cptr+9;
char *cptr;
puts(cptr);
puts (str1); puts(str2);
}
cptr=str1;
puts(cptr);

10 SECONDS 130
Output:
INFO TECH
Java and Internet
INFO TECH
TECH
Java and Internet
Internet

10 SECONDS 131
Program:Length of string using pointers

#include <stdio.h> output


int main() String length=12
{ char str[20]=“c++ and Java”;
char *cptr;
int length=0;
cptr=str;cptr++)
for(;*cptr!=NULL;cptr++)
length++;
Printf(“String
length=%d”,length);
}

10 SECONDS 132
Pointers and strings
NOTE 1 NOTE 2
char str1[]=“hello”; char str1[]=“hello”;
char str2[10]; char *p=“good”;
char *s=“good”; str1=“bye”;/*error*/
char *q; p=“bye”;/* correct */
We cannot assign a string to
another
str2=str1;/* error */
Whereas ,we can assign a
char pointer to another
char pointer.
q=s; /* correct */

10 SECONDS 133
Limitations of Array of Pointers
and strings.
#include <stdio.h>
int main()
{char *names[6];
int i;
for(i=0;i<6;i++)
{ printf(“enter name\n”);
scanf(“%s”,names[i]);/* error */
}
return 0;}
solution to this problem dynamically allot memory

10 SECONDS 134
solution
#include <stdio.h> p=(char *)malloc(len+1);
#include <string.h> strcpy(p,n);
int main() names[i]=p;
{char *names[6]; }
char n[50]; for(i=0;i<6;i++)
int len,i; printf(“%s\n”,names[i]);
char *p; return 0;
for(i=0;i<6;i++) }
{printf(“Enter name\n”);
scanf(“%s”,n);
len=strlen(n);

10 SECONDS 135
Pointers and multidimensional array

int arr[3][5];

A pointer variable ptr that can point to an


element of arr(i.e, can point to a 5 element
integer array ) is declared as:

int (*ptr)[5];
ptr=arr;

The parenthesis are required because the brackets


have higher precedence than asterisk(*)

10 SECONDS 136
Program to demonstrate pointers and multi
dimensional array
#include <stdio.h>
int main()
{ int arr[3][5]={{1,2,3,4,5},{6,7,8,9,10},{11,12,13,14,15}};
int (*ptr)[5], i, j;
ptr=arr;
for(i=0;i<3;i++)
{ printf(“\n”);
for(j=0;j<5;j++)
printf(“%d “,(*ptr)[j]);
ptr++; /*moves pointer to first element of next row */
}}
10 SECONDS 137
Diagramitic -2 dim array----- int arr[3][5];

0 1 2 3 4
arr 0 3501 3503 3505 3507 3509

arr+1 1 3511 3513 3515 3517 3519

arr+2 2 3521 3523 3525 3527 3529

int (*ptr)[5];
ptr=arr; /*ptr will have address 3501 */
ptr++; or ptr+1; -> now address 3511
ptr+2 -> address will be 3521

10 SECONDS 138
Dynamic memory allocation- malloc()

int *arr;
arr=(int *)malloc (5*sizeof(int));

arr
The header file stdlib.h contains memeory
management functions
malloc(),calloc(),realloc(),free()

10 SECONDS 139
program allocates a required block using malloc()
displays addresses,reads and prints data.

printf(“memory addresss \n”);


#include <stdio.h>
for(i=0;i<n;i++)
#include<stdlib.h>
printf(“%u”,arr+i);
int main() printf(“Input data \n”);
{ int *arr,n,i; for(i=0;i<n;i++)
printf(“Enter no of elements\n”); scanf(“%d”,arr+i);
scanf(“%d”,&n); printf(“Display data \n”);
arr=(int *)malloc(n*sizeof(int)); for(i=0;i<n;i++)
if(arr==NULL){ printf(“%d”,*(arr+i));
printf(“could not allocate
memory”); free(arr);
exit(1); }
}
10 SECONDS 140
Arrays of pointers
An array of pointers would be a collection of addresses. The
addresses present in it can be addresses of individual
variables or addresses of array elements.
int *arr[4]; /* array of integer pointers */
Assume we declare four variables,
int i=30,j=40,k=50,l=60;
then if we write arr[0]=&i;arr[1]=&j;arr[2]=&k;arr[3]=&l;
i j k l
30 40 50 60
65514 65510 65506 65502

65514 65510 65506 65502

arr[0] arr[1] arr[2] arr[3]


array of integer pointers... To access contents of i
we write (*arr[0])
10 SECONDS 141
An array of pointers containing the
addresses of other arrays.
#include <stdio.h>
int main()
{ int a[]={0,1,2,3,4};
int *p[]={a,a+1,a+2,a+3,a+4};
printf(“%u %u %d\n”,p,*p,*(*p));
}
Output
????

10 SECONDS 142
contd
Prev output
Address of p
Address of a[0]
Content of a[0]...i.e 0
Note:
to print content of a[3],
*(*(p+3)) or *(p[3])

10 SECONDS 143
2 dim array, using array of pointers-malloc()
#include <stdio.h>
#include <stdlib.h> /* display */
int main()
for (i=0;i<m;i++)
{ int *arr[10];
int m,n,i,j,sum=0; for(j=0;j<n;j++)
printf(“Enter number of rows nd printf(“%d”,*(arr[i]+j));
columns\n”); }
scanf(“%d %d”,&m,&n);
for(i=0;i<m;i++)
arr[i]=(int *malloc(n*sizeof(int));
/* input */
for (i=0;i<m;i++)
for(j=0;j<n;j++)
scanf(“%d”,arr[i]+j);

10 SECONDS 144
Arrays of pointers to strings
#include <stdio.h>
int main() Output:
{ char *names[]={ Original:raman srinivas
New:srinivas raman
“akshay”,”parag”,”raman”,” In this program, the
srinivas”,”gopal”,”rajesh”}; addresses (of the
char *temp; names }stored in
array of pointers got
printf(“Original string: %s
exchanged.
%s\n”,names[2],names[3]);
temp=names[2];
names[2]=names[3];
names[3]=temp;
printf(“New %s
%s\n”,names[2],names[3]);
return 0;}
10 SECONDS 145
Storage Classes in C
 If we don’t specify the storage class
of a variable in its declaration, the
compiler will assume a storage class
depending on the context in which
the variable is used.
 Thus, variables have certain default
storage classes.

10 SECONDS 146
Storage Classes in C cont..
 Locations in computer where value will be stored:
CPU registers and Memory.
Storage class tells following:
1. Where the variable would be stored.
2. What will be the initial value of the variable, if initial
value is not specifically assigned. (i.e. default initial
value)
3. What is the scope of the variable, i.e., in which
functions the value of the variable would be
available.
4. What is the life of the variable, i.e., how long would
variable exist.

10 SECONDS 147
Storage Classes in C cont..
 There are four storage classes in C
◼ Automatic storage class
◼ Register storage class
◼ Static storage class
◼ External storage class

10 SECONDS 148
Automatic storage class
 Storage: Memory
 Default initial value: An unpredictable
value, which is often called a garbage
value.
 Scope: Local to the block in which the
variable is defined.
 Life: Till the control remains within
the block in which the variable is
defined.
10 SECONDS 149
Automatic storage class cont..
# include <stdio.h>
int main ( )
{
auto int i, j; // int i, j;
printf (“%d\n%d”, i, j);
return 0;
}
Output:
12345
34567

10 SECONDS 150
Automatic storage class cont..
# include <stdio.h>
int main ( )
{
auto int i = 1;
{
{
{
printf (“%d”, i);
}
printf (“%d”, i);
}
printf (“%d”, i);
}
return 0;
}
Output:
111

10 SECONDS 151
Automatic storage class cont..
# include <stdio.h>
int main ( )
{
auto int i = 1;
{
auto int i = 2;
{
auto int i = 3;
printf (“%d”, i);
}
printf (“%d”, i);
}
printf (“%d”, i);
return 0;
}
Output: 3 2 1

10 SECONDS 152
Automatic storage class cont..
Note:
In the above program, the compiler
treats the three i’s as totally different
variables, since they are defined in
different blocks.

10 SECONDS 153
Register storage class
 Storage: CPU registers
 Default initial value: Garbage value
 Scope: Local to the block in which the
variable is defined.
 Life: Till the control remains within
the block in which the variable is
defined.

10 SECONDS 154
Register storage class cont..
 Accessing register is always fast compared to
accessing memory.
Ex:
# include <stdio.h>
int main ( )
{
register int i;
for (i = 1; i <= 10; i++)
printf (“%d\n”, i);
return 0;
}

10 SECONDS 155
a – 1000 b – 2000 c – 3000
register int a, b, c;
register int c, b, a;
int a; register int b; volatile int c;

10 SECONDS 156
A – 1000 b – 2000 c - 3000
 Int a, b, c;
 Register int a, b,c;
 Register int c, b, a;

10 SECONDS 157
Register storage class cont..
 Even though we have declared the storage
class of i as register, we cannot say for sure
that the value of i would be stored in CPU
register.
 Because the number of CPU registers are
limited, and they may be busy doing some
other task.
 If registers are not available, the variable
works as if its storage class is auto.

10 SECONDS 158
void main () int add (int p, int q)
{ {
int a, b, c; int r;
int add (int, int); r = p + q;
a = 10; return r;
b = 20; }
c = add (a, b);
printf (“%d”, c);
}

10 SECONDS 159
Static Storage Class
 Storage: Memory
 Default Initial Value: Zero
 Scope: Local to the block in which the
variable is defined
 Life: Value of the variable persists
between different function calls.

10 SECONDS 160
Static Storage Class cont..
# include <stdio.h> # include <stdio.h>
void increment ( ); void increment ( );
void main ( ) void main ( )
{ {
increment ( ); increment ( );
increment ( ); increment ( );
increment ( ); increment ( );
} }
void increment ( ) void increment ( )
{ {
auto int i = 1; static int i = 1;
printf (“%d\n”, i); printf (“%d\n”, i);
i = i + 1; i = i + 1;
} }

10 SECONDS 161
a.C b.C c.c
int account; extern int account; static int account;
Void main () Void main () Void main ()
{ { {
account++; account++; account++;
} } }
int add () int fun1 ( )
{ {
account--; account--;
} }

10 SECONDS 162
Static Storage Class cont..
 If the storage class is static, then the
statement static int i = 1 is executed
only once, irrespective of how many
times the same function is called.

10 SECONDS 163
a.c b.c c.c

int account; extern int account; Static int account;


void main ( ) Void main () Void main ( )
{ { {
account ++; account--;
} } account++;
int add ( ) }
{ Void add ()
account --; {
} account--;
}

10 SECONDS 164
a.C b.C c.c

int account; Extern int account; Static int account;


Void main () Void main () Void main ()
{ { {
account ++; account--; account ++;
} } }
Int add ()
{
account--;
}

10 SECONDS 165
External storage class
 Storage: Memory
 Default initial value: zero
 Scope: Global
 Life: As long as the program’s
execution does not come to an end.

10 SECONDS 166
External storage class cont..
 External variables are declared
outside all functions, yet are available
to all functions.

10 SECONDS 167
External storage class cont..
# include <stdio.h> void increment ( )
int i; {
void increment ( ); int i = 5;
void decrement (); i = i + 1;
int main ( ) printf (“On incrementing
{ i = %d\n”, i);
printf (“i = %d\n”, i); }
increment ( ); void decrement ( )
increment ( ); {
decrement ( ); static int i = 3;
decrement ( ); i = i – 1;
return 0; printf (“On decrementing
} i = %d\n”, i);

10 SECONDS 168
External storage class cont..
# include <stdio.h>
int x = 21;
int main ( )
{
extern int y;
printf (“%d%d\n”, x, y);
return 0;
}
int y = 31;

10 SECONDS 169
External storage class cont..
 extern int y;
 int y = 31;
1. In the above program fragment first
statement is a declaration and second is
the definition.
2. When we declare a variable no space is
reserved for it, whereas, when we define it
space gets reserved in memory.
3. We had to declare y since it is being used
in printf ( ) before it is definition is
encountered.

10 SECONDS 170
External storage class cont..
#include <stdio.h>
int x = 10;
void display ( );
int main ( )
{
int x = 20;
extern int x;
printf (“%d\n”, x);
display ( );
return 0;
}
void display ( )
{
printf (“%d\n”, x);
}
10 SECONDS 171
Structures
# include <stdio.h> printf (“This is what you entered
int main ( ) \n”);
{ printf (“%c%f%d”, b1.name,
struct book b1.price, b1.pages);
{ printf (“%c%f%d”, b2.name,
b2.price, b2.pages);
char name; printf (“%c%f%d”, b3.name,
float price; b3.price, b3.pages);
int pages; return 0;
}; }
struct book b1, b2, b3;
printf (“Enter names, prices and
no of pages of 3 books\n”);
scanf (“%c%f%d”, &b1.name,
&b1.price, &b1.pages);
scanf (“%c%f%d”, &b2.name,
&b2.price, &b2.pages);
scanf (“%c%f%d”, &b3.name,
&b3.price, &b3.pages);

10 SECONDS 172
Structures cont..
struct book struct book
{ {
char name; char name;
float price; float price;
int pages; int pages;
}; }b1, b2, b3;
struct book b1, b2,
b3;

10 SECONDS 173
Structures cont..
struct
{
char name;
float price
int pages;
}b1, b2, b3;

10 SECONDS 174
Structures cont..
Initializing structures:
struct book
{
char name[10];
float price;
int pages;
};
struct book b1 = {“Basic”, 130.0, 550};
struct book b2 = {“Physics”, 150.80, 800};
struct book b3 = {0};

10 SECONDS 175
Functions

10 SECONDS 176
# include <stdio.h>
int main ( )
{
printf (“c to it that c survives \n”);
main ( );
return 0;
}

10 SECONDS 177
# include <stdio.h>
int i = 0;
void val ( );
int main ( )
{
printf (“main’s i = %d\n”, i);
i++;
val ( );
printf (“main’s i = %d\n”, i);
val ( );
return 0;
}
void val ( )
{
i = 100;
printf (“val’s i = %d\n”, i);
i++;
}
10 SECONDS 178
# include <stdio.h> int f (int a)
int f (int); {
int g (int); a += -5;
int main ( ) t -= 4;
{ return (a + t);
int x, y, s = 2; }
s*=3;
int g (int a)
y = f (s);
{
x = g (s);
a = 1;
printf (“%d%d%d”, s, y,
x); t += a;
return 0; return (a + t);
} }
int t = 8;
10 SECONDS 179
# include <stdio.h>
int main ( )
{
static int count = 5;
printf (“count = %d\n”, count--);
if (count != 0)
main ( );
return 0;
}

10 SECONDS 180
# include <stdio.h> int g (int x)
int g (int); {
int main ( ) static int v = 1;
{ int b = 3;
int i, j; v += x;
for (i = 1; i < 5; return (v + x +
i++) b);
{ }
j = g( i );
printf (“%d\n”,
j);
}
return 0; 10 SECONDS 181
# include <stdio.h> i++, j++, k++;
int main ( ) printf (“%d%d%d”,
{ i, j, k);
func ( ); }
func ( );
return 0;
}
void func ( )
{
auto int i = 0;
register int j = 0;
static int k = 0; 10 SECONDS 182
# include <stdio.h>
int x = 10;
int main ( )
{
int x = 20;
{
int x = 30;
printf (“%d”, x);
}
printf (“%d”, x);
return 0;
} 10 SECONDS 183
Unions
 Union offers a way for a section of
memory to be treated as a variable of
one type on one occasion, and as a
different variable of a different type
on another occasion

10 SECONDS 184
# include <stdio.h>
int main ( )
{
union student;
{
int age;
char grade;
float per;
};
union student s1;
printf (“Enter grade of student \n”);
scanf (“%c”, &s1.grade);
printf (“Grade is: %c”,s1. grade);
printf (“Enter age of a student \n”);
scanf (“%d”, &s1.age);
printf (“Age is: %d”, s1.age);
printf (“Enter percentage of student \n”);
scanf (“%f”, &s1.per);
printf (“Percentage is %f\n”, s1.per);
} 10 SECONDS 185
Unions cont..
In the above program, at any point of
time, one can store age or grade or
percentage. At a time one cannot
store all the details. This is the major
difference between structure and
union.

10 SECONDS 186

You might also like