100% found this document useful (1 vote)
522 views192 pages

C Language Introduction

This document is an introduction to the C programming language. It covers basic C concepts like data types, variables, operators, and control structures. It includes examples of using various operators like arithmetic, relational, logical, and bitwise operators. It also demonstrates if/else statements, switch cases, and different loop constructs like while, do-while, and for loops. Examples are provided for printing patterns, numbers, factors, and sequences like Fibonacci. Overall, the document serves as a tutorial to teach the fundamentals of the C language.

Uploaded by

ArunKumar A
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
100% found this document useful (1 vote)
522 views192 pages

C Language Introduction

This document is an introduction to the C programming language. It covers basic C concepts like data types, variables, operators, and control structures. It includes examples of using various operators like arithmetic, relational, logical, and bitwise operators. It also demonstrates if/else statements, switch cases, and different loop constructs like while, do-while, and for loops. Examples are provided for printing patterns, numbers, factors, and sequences like Fibonacci. Overall, the document serves as a tutorial to teach the fundamentals of the C language.

Uploaded by

ArunKumar A
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 192

C

Programmin
g
Online Tutorials

Arun Kumar
Introduction to c

Contents
1. Introduction to c................................................................................................................................4
2. Structure of C.....................................................................................................................................6
3. Keywords and Identifiers...................................................................................................................7
Data Types.............................................................................................................................................7
4.Data Types..........................................................................................................................................8
5.Format Specifiers................................................................................................................................9
6.Variables In c....................................................................................................................................10
What is local variable.......................................................................................................................11
What is the default value of local variable..........................................................................................11
Global variable.....................................................................................................................................11
What is global variable?...................................................................................................................11
7.Operators In C..................................................................................................................................13
How to print the range of values of each and every data type............................................................14
7.1Arithmetic Operator...................................................................................................................14
Division........................................................................................................................................15
Modulus.......................................................................................................................................16
7.2Relational Operators...................................................................................................................17
When to use relational operator?.......................................................................................................17
Relational operator returns true or false.............................................................................................17
Now while comparing float with float or double be cautious..............................................................18
What is the associativity of relational operator...................................................................................19
7.3Logical Operator.........................................................................................................................20
Short circuited operation.....................................................................................................................20
7.4BitWise Operator -> &,|,^,>>,<<,~..............................................................................................23
How to swap two numbers using bit wise operator............................................................................24
7.5Assignment Operator.................................................................................................................25
What is the associativity of assignment operartor..............................................................................25
7.5Ternary Operator........................................................................................................................27
Find largest of two numbers................................................................................................................27
Find the largest of three numbers.......................................................................................................27
Difference between logical and and bitwise and.................................................................................27
7.6Unary Operator..........................................................................................................................28

2
Introduction to c

Decrement -> pre decr ->--a -> decrement first assign next................................................................28
Comma operator.............................................................................................................................30
Example 5............................................................................................................................................31
7.7Operator Precedence.................................................................................................................32
30 | 135 ( 4 months.............................................................................................................................34
How to convert celcius to farenheat...................................................................................................35
#include <stdio.h>...............................................................................................................................35
#include <stdio.h>...............................................................................................................................36
8.Constructs or Control Statements....................................................................................................37
8.1If Statements..............................................................................................................................37
How to check the eligibility for vote....................................................................................................38
We will work with characters..............................................................................................................41
While working with characters we should know its ascii values..........................................................41
How to check whether a year is leap year or not................................................................................49
8.2Switch Case.................................................................................................................................52
8.2Loops..........................................................................................................................................57
Example 1: print natural numbers between 1 to 10............................................................................57
Example 2: print factorial of 5 using all three loops............................................................................58
8.2.1While...................................................................................................................................59
Find the first digit and last digit of a number.......................................................................................59
Example of pow function.....................................................................................................................61
How to print the digits of a number in reverse....................................................................................62
How to print the digits of a number in words......................................................................................62
Print along with place value................................................................................................................63
8.2.2do while...............................................................................................................................65
8.2.3for........................................................................................................................................67
We can use characters also inside for loop.........................................................................................68
How to print the factors of a number..................................................................................................70
Example 7: Fibonnoci series................................................................................................................71
How to get inverted half pyramid........................................................................................................72
How to print full pyramid....................................................................................................................73
How to print the given pattern............................................................................................................74
How to print the following pattern......................................................................................................76

3
Introduction to c

1. Introduction to c

NEXT

4
Introduction to c

5
Structure of C

2. Structure of C

While using print function we will use some of the escape sequences or backslash character to
format our output

Escape sequences or backslash character

\n -> new line

\t -> tab space

\v -> vertical tab

\b -> backspace

\r -> carriage return

\a -> alert bell sound

\’ -> print single quotes

NEXT

6
Keywords and Identifiers

3. Keywords and Identifiers

Data Types

NEXT

7
Data Types

4.Data Types

NEXT

8
Format Specifiers

5.Format Specifiers

Example 1:

#include <stdio.h>

int main()

char ch;

int a;//declaration

float b;

double d;

printf("Input a character,integer,float and double : ");

scanf("%c%d%f%lf",&ch,&a,&b,&d);

printf("ch = %c\na = %d\nb = %3.2f\nd = %3.2lf\n",ch,a,b,d);

return 0;

NEXT

9
Variables in C

6.Variables In c
What are variables in c?

A variable is one whose values can change at any time so we are going to store some data in the
variables and use in our progam

What are the types of variables

Local variable

Example 1:

#include <stdio.h>

int main()

int a = 10;//local variable

printf("a = %d\n",a);

return 0;

Example 2:

#include <stdio.h>

int a = 10;//global variable

int main()

int b = 20;

int c = 30;//local variable

printf("c = %d\n",c);

printf("a = %d\nb = %d\n",a,b);

return 0;

10
Variables in C

NEXT

What is local variable


Anything declared within the function or within the block we call it as local variable

Scope -> its scope is local to the function in which it is defined ie available only within the function or
block

What is the default value of local variable

It will be garbage value so local variable if uninitalized takes garbage value so only when we find sum
and if it is local variable sum=0, why?

Global variable

Example 3:

#include <stdio.h>

int a = 10;//global variable

int main()

printf("a = %d\n",a);

return 0;

What is global variable?


Anything declared outside all functions and outside main become global

Scope -> its scope is till the program exits

What is the default value of gloable variable

It will be assigned default values of the data type

-int -> 0

-flaot -> 0.0

-double -> 0.0

-char ->’\0’

NEXT

11
Variables in C

Example 4:

#include <stdio.h>

int a = 10;

int main()

int a = 20;

int a = 30;

printf("a = %d\n",a);

printf("a = %d\n",a);

return 0;

So if local variable and global variable has same name then local variable will be given priority ie
local variable preceeds over the global variable

Example 5:

#include <stdio.h>

int main()

int a = printf("Hello world\n");//Hello world

printf("a = %d\n",a); //a = 12

return 0;//printf returns number of successfult characters printed

NEXT

12
Operators in C

7.Operators In C

Example 1:

#include <stdio.h>

int main()

int a;

char ch;

float f;

double d;

printf("Size of integer is %d\n",sizeof(a));//4 bytes

printf("Size of float is %d\n",sizeof(f));//4 bytes

printf("Size of character is %d\n",sizeof(ch));//1 bytes

printf("Size of double is %d\n",sizeof(d));//8 bytes

return 0;

13
Operators in C

NEXT

14
Relational Operators in C

How to print the range of values of each and every data type

Example 7:

#include <stdio.h>

#include <limits.h>

#include <float.h>

int main()

printf("Minimum value of character is %d and maximum value is %d\n",CHAR_MIN,CHAR_MAX);

printf("Minimum value of Integer is %d and maximum value is %d\n",INT_MIN,INT_MAX);

printf("Minimum value of float is %g and maximum value is %g\n",FLT_MIN,FLT_MAX);

return 0;

7.1Arithmetic Operator

NEXT

15
Relational Operators in C

Example 1:

#include <stdio.h>

int main()

int a,b,c;

printf("Input the two values : ");

scanf("%d%d",&a,&b);

c = a * b;

printf("c = %d\n",c);

return 0;

Division
Example 2:

#include <stdio.h>

int main()

int a,b;

float c;

printf("Input the two values : ");

scanf("%d%d",&a,&b);

c = a / b;//5.0/2.0 -> 2.5

printf("c = %f\n",c);

return 0;

NEXT

16
Relational Operators in C

Modulus
#include <stdio.h>

int main()

int a,b,c;

printf("Input the two values : ");

scanf("%d%d",&a,&b);

c = a % b;//-5%2 -> -1

printf("c = %d\n",c);

return 0;

Now modulus operator does not work on float data types now how to get remainder for float values
For this we have function called fmod() in math.h this returns remainder for float values
So directly using modulus operator on float values not allowed so we can call the function fmod from
math.h to get remainder of float values
Example 4:

#include <stdio.h>

#include <math.h>

int main()

float a,b,c;

printf("Input the two values : ");

scanf("%f%f",&a,&b);

c = fmod(a,b);

printf("c = %f\n",c);

return 0;

}
In arithmetic operator highest precedence will be given to * / % next precedence will be given to + -
If all of same precedence occurs we have to go for associativity for arithmetic operator associativity
is from L->R
NEXT

17
Relational Operators in C

7.2Relational Operators
>,<,>=,<=,==,!=

When to use relational operator?

When you want to compare two things or test a condition we go for relational operator

Relational operator returns true or false

In c language anything zero is false and anything other than zero is true

-5,-4,-0.2,0.2,3,10,20 all are true

0 -> false

Returns 1 if condition is true else it returns 0 ie false

Int a =20,b=20

a>b -> 0

a<b -> 0

a>=b -> 1

a<=b -> 1

a==b -> 1

a!=b -> 0

“abc”==”abc” when we write character within double quotes it becomes string and don’t use == for
comparing two strings there is a separate way of comparing two strings

Example 1:

#include <stdio.h>

int main()

int a=20,b=20;

printf("a>b = %d\n",(a>b));//0

printf("a<b = %d\n",(a<b));//0

printf("a>=b = %d\n",(a>=b));//1

printf("a<=b = %d\n",(a<=b));//1

printf("a==b = %d\n",(a==b));//1 NEXT

18
Relational Operators in C

printf("a!=b = %d\n",(a!=b));//0

return 0;

Now while comparing float with float or double be cautious


Default data type for float and double is double float is single precision and double is double
precision
So when we give 0.2 compiler considers this as double and left value is float so it is comparing with
float and double so we get undesired result so make 0.2 and 0.5 as float how? 0.2f and 0.5f so it is
comparing float with float

#include <stdio.h>

int main()

float a = 0.2,b = 0.5;

if(a==0.2f){printf("EQUAL\n");}

else{printf("NOT EQUAL\n");}

if(b==0.5f){printf("EQUAL\n");}

else{printf("NOT EQUAL\n");}

return 0;

} NEXT

19
Relational Operators in C

What is the associativity of relational operator

It is left to right

Example 3:

#include <stdio.h>

int main()

int a = 9,b=10,c=1;

int d = a>b==c;//L->R a>b(1)1==1 d=1

printf("d = %d\n",d);

return 0;

Example 4:

#include <stdio.h>

int main()

int a = 10,b = 10,c = 10;

int d = a==b==c;//1st a==b performed 1 == c performed 1 == 10 (0)

printf("d = %d\n",d);

return 0;

NEXT

20
Logical Operators in C

7.3Logical Operator
&&,||,!

Example 1:

#include <stdio.h>

int main()

int a = 10,b = 15,c = 9;

int d = a<b && b>c;

int e = a>b || b>c;

int f = !a;

printf("d = %d\te = %d\t f = %d\t",d,e,f);

return 0;

Short circuited operation

NEXT

21
Logical Operators in C

Example 2:

#include <stdio.h>

int main()

int a =10,b = 10,c = 10;

int d = a==b&&a==c;

printf("d = %d\n",d);

return 0;

NEXT

22
BitWise Operators in C

7.4BitWise Operator -> &,|,^,>>,<<,~

Example 1:

#include <stdio.h>

int main()

int a = 20,b = 16;

printf("a&b = %d\n",(a&b));//16

printf("a|b = %d\n",(a|b));//20

printf("a^b = %d\n",(a^b));//4

printf("a>>3 = %d\n",(a>>3));//2

printf("31>>3 = %d\n",(31>>3));//3

printf("a<<3 = %d\n",(a<<3));//160

printf("~5 = %d\n",(~5));//-6

printf("~-5 = %d\n",(~-5));//4

return 0;

} NEXT

23
BitWise Operators in C

How to swap two numbers using bit wise operator

Example 2:

#include <stdio.h>

int main()

int a = 20,b = 16;

printf("Before swapping a = %d and b = %d\n",a,b);

a = a^b;//16

b = a^b;//20

a = a^b;//16

printf("After swapping a = %d and b = %d\n",a,b);

return 0;

NEXT

24
Assignment Operators in C

7.5Assignment Operator
It is called as compound assignment +=,-=,/=,%=,>>=

Int a = 10;

->a+=5;//a = a+5->a = 10+5->a=15

What is the advantage of assignment operator here the expression length gets reduced and also it is
faster in execution

Example 1:

#include <stdio.h>

int main()

int a = 10;

a/=5;

printf("a = %d\n",a);

return 0;

What is the associativity of assignment operartor


Assocciativity is Right to left
#include <stdio.h>
int main()

int a = 10,b = 15,c = 5;

a+=b-=c;

printf("a = %d\tb = %d\tc = %d\n",a,b,c);

return 0;

//c = 5

//1st b-=c -> b = b - c-> b = 15-5 -> b = 10

//a+=b -> a = a+b -> a = 10 + 10->a = 20

NEXT

25
Assignment Operators in C

Example 2:

#include <stdio.h>

int main()

int a = 10;

a+=a+=a-=5;

printf("a = %d\n",a);

return 0;

//a-=5 -> a = a - 5 -> a = 10-5 a->5

//a+=a -> a = a + a -> a = 5 + 5->10

//a+=a -> a = a + a -> a = 10 + 10 ->20

Example 3:

#include <stdio.h>

int main()

int a = 10,b = 15,c = 18;

int d = a<b && (b+=2)<c;//d = 0 b+=2 will not be executed

printf("d = %d\nb = %d\n",d,b);

return 0;

NEXT

26
Ternary Operators in C

7.5Ternary Operator
Ternary (or) conditional opearator -> ? :

->int a = 15,b = 12,c = 18;

Find largest of two numbers

->int d = a>b?a:b

->if(a>b){return a;}else{return b;}

Find the largest of three numbers

->int e = (a>b)? (a>c?a:c) : (b>c?b:c);

Example 1:

#include <stdio.h>

int main()

int a = 15,b = 12,c = 18;

int d = a>b?a:b;

int e = (a>b)?(a>c?a:c):(b>c?b:c);

printf("d = %d\ne = %d\n",d,e);

return 0;

Difference between logical and and bitwise and


#include <stdio.h>
int main()

int a = 3,b = 20;

(a&&b)?printf("TRUE\n"):printf("FALSE\n");

(a&b)?printf("TRUE\n"):printf("FALSE\n");

return 0;

//20 -> 0 0 0 1 0 1 0 0

27
Ternary Operators in C

//5 -> 0 0 0 0 0 0 1 1 result of 20&5 0 NEXT

28
Unary Operators in C

Example 3:

#include <stdio.h>

int main()

int num;

printf("Input a number : ");

scanf("%d",&num);

(num%2==0)?printf("EVEN\n"):printf("ODD\n");

((num&1)==0)?printf("EVEN\n"):printf("ODD\n");

return 0;

7.6Unary Operator
Increment -> pre incr -> ++a ->increment first assign next

Post incr -> a++ -> assign first increment next

Decrement -> pre decr ->--a -> decrement first assign next

Post decr -> a-- -> assign and then decrement

#include <stdio.h>

int main()

int a = 10,b = 20;//a -> 11//a->12 b=19 b=18

printf("a++ = %d\n",a++);//10

printf("++a = %d\n",++a);//12

printf("--b = %d\n",--b);//19

printf("b-- = %d\n",b--);//19

printf("a = %d\nb = %d\n",a,b);

return 0;

NEXT

29
Unary Operators in C

Example 2:

#include <stdio.h>

int main()

int a = 10,b = 20;

int c = a++ + a++ + ++a;

int d = --b + --b + b--;

printf("c = %d\na = %d\n",c,a);

printf("d = %d\nb = %d\n",d,b);

return 0;

//a->11->12->13

//a++ + a++ + ++a

//10 + 11 + 13 -> 34

//b->20->19->18 -> 17

//--b + --b + b--

//19 + 18 + 18

//54

Example 3:

#include <stdio.h>

int main()

int a = 10;

printf("%d\t%d\t%d\n",a++ + a++ + ++a,a++ + ++a,++a + ++a + a++);

printf("a = %d\n",a);

return 0;

} NEXT

30
Unary Operators in C

//In print expressions are valuated from right to left

//a 10->11->12->13->14->15->16->17->18

//++a + ++a + a++

//11 + 12 + 12

//35

//a++ + ++a

//13 + 15

//28

//a++ + a++ + ++a

//15 + 16 + 18

//49

Comma operator
Expressions valuated from left to right and right most value assigned

#include <stdio.h>

int main()

int a = 10;//a->10->11->12->13

int b = (a++,++a,a++);//(10,12,12)

printf("b = %d\ta = %d\n",b,a);

return 0;

Example 4:

#include <stdio.h>

int main()

int a,b,c,d;

a = printf("Hello world\n");//12

//print returns number of successfull character printed on console screen

b = scanf("%d%d",&c,&d);//2 NEXT

31
Unary Operators in C

//scanf returns number of successfull inputs read

printf("a = %d\nb = %d\n",a,b);

return 0;

Example 5

#include <stdio.h>

int main()

int a = (printf("%d",4556),printf("%d",846),printf("%d",57));

printf("\na = %d\n",a);

return 0;

//a=(4,3,2)

//455684657

//a = 2

Sizeof operator it does not valuate any expressions it just returns the size of argument passed

Example 1:

#include <stdio.h>

int main()

int a = 10;

int b = sizeof(printf("Hello world\n"));

//size of operator does not valuate any expressions

printf("a = %d\nb = %d\n",a,b);

return 0;

} NEXT

32
Operator Precedence in C

7.7Operator Precedence

#include <stdio.h>

int main()

int y=-2,x=1,z=0;

z += ~y==x;

printf("z = %d\n",z);

return 0;

//first it performs ~y -> ~y = -(y+1)->~-2 -> -(-2+1)->-(-1)->1

//1 == 1 ->true so it returns 1

//z+=1 -> z = z + 1 -> z = 0 + 1 -> z=1

Example 2:

#include <stdio.h>

int main()

int y=-2,x=10,z=5;

z += ~y+2>x>>3;

printf("z = %d\n",z); NEXT

33
Operator Precedence in C

return 0;

//~y -> ~-2 -> 1

//~y+2 -> 1 + 2 -> 3

//x>>3 -> 10>>3 -> 10/2->5/2->2/2->1

//3>1 -> 1

//z += 1 -> z = 0+1->1

Example 2:

#include <stdio.h>

int main()

int z = 5;

z += 4*6+2%3>>2+1+~-2;

printf("z = %d\n",z);

return 0;

//~-2 -> -(-2+1)->1

//z = 4*6+2%3>>2+1+1

//z = 24+2%3>>2+1+1

//z = 24+2>>2+1+1

//z = 26>>2+1+1

//z = 26>>4

//z += 26/2->13/2->6/2->3/2->1

//z = z+1->5+1->6

NEXT

34
Operator Precedence in C

Example 3:

#include <stdio.h>

int main()

int i=10;

int j = ++i++;//throw error

printf("j = %d\ni = %d\n",j,i);

return 0;

//we can assign a = 10 it is correct

//can we write 10 = a not possible

//increment operator throwing lvalue required

//i++ it will increment i and returns rvalue

Input is babies age in number of days we have to calculate babies age in number of years months
and days

Banod = 500, y=500/365, m= 500%365/30, d=500%365%30

1 year = 365days, 1month = 30 days

365 | 500 ( 1 year

365

30 | 135 ( 4 months

120

15 days

Example 1:

#include <stdio.h>

int main()

int banod,y,m,d;

printf("Input the babies age in number of days : "); NEXT

35
Operator Precedence in C

scanf("%d",&banod);

y = banod/365;

m = banod%365/30;

d = banod%365%30;

printf("Babies age is %d years %d months and %d days\n",y,m,d);

return 0;

How to convert celcius to farenheat

Fh = (1.8*c)+32

Example 3:

#include <stdio.h>

int main()

float cel,fh;

printf("Input the celcius : ");

scanf("%f",&cel);

fh = (1.8*cel)+32;

printf("%.2f%cC = %.2f%cF\n",cel,248,fh,248);

return 0;

Area of circle here we are going to use macros or pre-processor directives or we can also call it as
symbolic constants

Example 4:

#include <stdio.h>

#define PI 3.14//macro or preprocessor directive or symbolic constant

int main()

float rad,area; NEXT

36
Operator Precedence in C

printf("Input the radius : ");

scanf("%f",&rad);

area = PI * rad * rad;

printf("Area = %.2f\n",area);

return 0;

Example 5:

#include <stdio.h>

#define PI 3.14//macro or preprocessor directive or symbolic constant

#define area(r) PI*rad*rad

int main()

float rad,area;

printf("Input the radius : ");

scanf("%f",&rad);

printf("Area = %.2f\n",area(rad));

return 0;

NEXT

37
Control Statements or Constructs in C

8.Constructs or Control Statements

8.1If Statements
#include <stdio.h>

int main()

int num;

printf("Input a number : ");

scanf("%d",&num);

if(num>=0){printf("Positive number\n");}

return 0;

NEXT

38
if statement in C

Example 2:

#include <stdio.h>

int main()

int num;

printf("Input a number : ");

scanf("%d",&num);

if(num%2==0){printf("EVEN\n");}

else{printf("ODD\n");}

if((num&1)==0){printf("EVEN\n");}

else{printf("ODD\n");}

return 0;

How to check the eligibility for vote

#include <stdio.h>

int main()

int age;

printf("Input the age : ");

scanf("%d",&age);

if(age>=18){printf("Elgible to vote\n");}

else{printf("Not eligible to vote\n");}

return 0;

NEXT

39
if statement in C

Example 4:

#include <stdio.h>

int main()

int y = -1,x=0;

if(~y==x){printf("Hai");}

else{printf("Bye");}

return 0;

//`y -> ~(-1)->-(-1+1)->0

//0 == 2 false Bye

//0 < 2 true hai

Example 5:

#include <stdio.h>

int main()

if(printf("%d",4556),printf("%d",768),printf("%d",0)){printf("Hai");}

else{printf("Bye");}

return 0;

//(4,3,1)right most value assigned

//45567680Hai

NEXT

40
if statement in C

Example 6:

#include <stdio.h>

int main()

int y = 3;

if(y--,--y,--y){printf("Hai");}

else{printf("Bye");}

return 0;

//y = 3->2->1->0

//(3,1,0)if(0)

//y--,--y,--y

Input is 3 sides of a triangle and we have to print whether the triangle is isoceles scalene or
equilateral

Equilateral -> all 3 sides equal

Isoceles -> any 2 sides equal

Scalene -> none of the sides equal

Three sides are sa,sb,sc

Equilateral -> sa==sb==sc(not possible)

 (sa==sb)&&(sb==sc) -|> codition to test equilateral

Isoclees -> (sa==sb)||(sa==sc)||(sb==sc)

Scalene

Here we are going to use if else if when ever we test more than one condition we go for if else if else

Example 5:

#include <stdio.h>

int main()

int sa,sb,sc; NEXT

41
if statement in C

printf("Inupt the three sides : ");

scanf("%d%d%d",&sa,&sb,&sc);

if(sa==sb&&sa==sc){printf("EQUILATERAL\n");}

else if(sa==sb||sa==sc||sb==sc){printf("ISOCELES\n");}

else{printf("SCALENE\n");}

return 0;

We will work with characters

While working with characters we should know its ascii values

‘A’ - >65 ‘Z’ -> 90

‘a’ -> 97 ‘z’->122

‘0’->48 ‘9’->57

Example 5:

#include <stdio.h>

int main()

{ char lch1='a',lch2='z',uch1='A',uch2='Z',dch1='0',dch2='9';

printf("'A' = %d\t'Z' = %d\n",uch1,uch2);

printf("'a' = %d\t'z' = %d\n",lch1,lch2);

printf("'0' = %d\t'9' = %d\n",dch1,dch2);

return 0;

Example 6:

How to convert the case of character

#include <stdio.h>

int main()

char ch; NEXT

42
if statement in C

printf("Input a character : ");

scanf("%c",&ch);

if(ch>='a'&&ch<='z'){ch = ch - 32;}

else{ch = ch + 32;}

printf("Coverted character is %c\n",ch);

return 0;

How to check whether a character is vowel or not

Example 7:

#include <stdio.h>

int main()

char ch;

printf("Input a character : ");

ch = getchar();//scanf("%c",&ch);

if(ch=='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u'){printf("Vowels\n");}

else{printf("Not a vowel\n");}

return 0;

How to check whether the character is digit, lowercase, upper case or special character

Example 8:

#include <stdio.h>

int main()

char ch; NEXT

43
if statement in C

printf("Input a character : ");

ch = getchar();//scanf("%c",&ch);

if(ch>='a'&&ch<='z'){printf("Lower case\n");}

else if(ch>='A'&&ch<='Z'){printf("Upper case\n");}

else if(ch>='0'&&ch<='9'){printf("Digit\n");}

else{printf("Special character\n");}

return 0;

There is a special header file called ctype.h specially for characters it contains built in function to
work with characters

->isalpha(ch) if ch is alphabet it returns true else false

->isalnum(ch)

->isdigit(ch)

->ispunt(ch)

->islower(ch)

->isupper(ch)

->tolower(ch)

->toupper(ch)

Example 9:

#include <stdio.h>

#include <ctype.h>

int main()

{ char ch;

printf("Input a character : ");

ch = getchar();//scanf("%c",&ch);

if(isalpha(ch)&&islower(ch)){ch=toupper(ch);}

else{ch=tolower(ch);}

printf("Converted character is %c\n",ch); NEXT

44
if statement in C

return 0;

Example 10

Check whether the character is lower , upper or digit or special character

#include <stdio.h>

#include <ctype.h>

int main()

char ch;

printf("Input a character : ");

ch = getchar();//scanf("%c",&ch);

if(isalpha(ch)&&islower(ch)){printf("Lower case\n");}

else if(isalpha(ch)&&isupper(ch)){printf("Upper case\n");}

else if(isalnum(ch)&&isdigit(ch)){printf("Digit\n");}

else{printf("Special character\n");}

return 0;

Input is age and gender of the employee if age is greater than 30 and gender is male then print he
needs insurance else if age is greater than 25 and gender is female then print she needs insurance

Else print no need insurance

NEXT

45
if statement in C

#include <stdio.h>

int main()

int age;

char gen;

printf("Input the gender(m/f) : ");

scanf("%c",&gen);

printf("Input the age : ");

scanf("%d",&age)

if(age>=30&&gen=='m'){printf("He needs insurance\n");}

else if(age>=25&&gen=='f'){printf("She needs insurance\n");}

else{printf("No need insurance\n");}

return 0;

NEXT

46
if statement in C

How to find the roots of quadratic equaiton

#include <stdio.h>

#include <math.h>

int main()

int a,b,c,d;

float x1,x2;

printf("Input the coefficients a,b and c : ");

scanf("%d%d%d",&a,&b,&c);

d = b*b-4*a*c;

if(d==0){

printf("Roots are real and equal\n");

x1=x2=-b/(2*a);

printf("Roots are x1 = %.2f and x2 = %.2f\n",x1,x2);

else if(d>0){

47
if statement in C

printf("Roots are real and different\n"); NEXT

x1 = -b+sqrt(d)/(2*a);

x2 = -b-sqrt(d)/(2*a);

printf("Roots are x1 = %.2f and x2 = %.2f\n",x1,x2);

else{

printf("Roots are imaginary\n");

return 0;

Calculate the electricity bill

Units<200 Charges = units*0.50f


Units>200 and units<400 Charges = 150+(units-200)*0.65f
Units>400 and units<600 Charges =350 + (untis-400)*0.75f
Units>600 Charges = 550 + (units-400)*0.95f
#include <stdio.h>
#include <math.h>
int main()
{
int units;

float charges;

printf("Input the units consumed : ");

scanf("%d",&units);

if(units<200){charges = units*0.50f;}

else if(units>200&&units<400){charges = 150+(units-200)*0.65f;}

else if(units>400&&units<600){charges = 350+(units-400)*0.75f;}

else{charges = 550+(units-600)*0.95f;}

printf("Charges are %.2f for %d units consumed\n",charges,units);

return 0;

48
if statement in C

NEXT

Get 6 subjeccts mark of the student and find the average and if avg is greater than 90 then print gold
medal else if avg is greater than 75 and less than 90 the print first cclass with distinction else if avg is
greater than 60 and avg less than 75 print first class else if avg greater than 45 and less than 60 print
second class else print fail

Nested if

How to find the largest of three numbers

#include <stdio.h>

int main()

int a,b,c,d,e;

printf("Input the three numbers : ");

scanf("%d%d%d",&a,&b,&c);

d = (a>b)?(a>c?a:c):(b>c?b:c);

printf("Largest of three numbers is %d\n",d);

if(a>b){

if(a>c){

printf("Largest of three numbers is %d\n",a);

}else{

printf("Largest of three numbers is %d\n",c);

}else{

if(b>c){

printf("Largest of three numbers is %d\n",b);

}else{

printf("Largest of three numbers is %d\n",c);

return 0;

49
if statement in C

} NEXT

How to check whether a year is leap year or not

#include <stdio.h>

int main()

int year;

printf("Input the year : ");

scanf("%d",&year);

if(year%4==0){

if(year%100==0){

if(year%400==0){

printf("It is a leap year\n");

}else{

printf("Not a leap year\n");

}else{

printf("It is a leap year\n");

}else{

printf("Not a leap year\n");

return 0;

NEXT

50
if statement in C

Input is pin number of an ATM validate the pin number if it is correct then print authorized entry and
get the amount else print unauthorized entry if amount is in multiples of 100 then print amount
withdrawn else print unable to dispense cash

#include <stdio.h>

int main()

int amount,pinNum;

printf("Input the pin Number : ");

scanf("%d",&pinNum);

if(pinNum>=1111&&pinNum<=9999){

printf("Authorized entry\n");

printf("Input the amount : ");

scanf("%d",&amount);

if(amount%100==0){

printf("%d withdrawn\n",amount);

}else{

printf("Unable to dispense cash\n");

}else{

printf("UnAuthroized entry\n");

return 0;

Input is three sides of a triangle find the largest side and if largest side is greater than addition of
other two sides then print sides form a triangle else print sides do nor form a triangle

#include <stdio.h>

int main()

51
if statement in C

int sa,sb,sc,ls,aots; NEXT

printf("Input the three sides of a triangle : ");

scanf("%d%d%d",&sa,&sb,&sc);

ls = (sa>sb)?(sa>sc?sa:sc):(sb>sc?sb:sc);

if(ls==sa){

aots = sb+sc;

if(ls>aots){

printf("Sides form a triangle\n");

}else{

printf("Sides do not form a triangle\n");

}else if(ls==sb){

aots = sa+sc;

if(ls>aots){

printf("Sides form a triangle\n");

}else{

printf("Sides do not form a triangle\n");

}else{

aots = sa+sb;

if(ls>aots){

printf("Sides form a triangle\n");

}else{

printf("Sides do not form a triangle\n");

return 0;

52
if statement in C

} NEXT

53
switch case statement in C

8.2Switch Case

#include <stdio.h>

int main()

int day;

printf("Input a day (1-7) : ");

scanf("%d",&day);

switch(day){

printf("Inside swith case\n");

case 1:

printf("Monday\n");

break;

case 4+1:

printf("Friday\n");

break;

case 2+1:

printf("Wednesday\n"); NEXT

54
switch case statement in C

break;

case 4:

printf("Thursday\n");

break;

case 2:

printf("Tuesday\n");

break;

default:

printf("None of case matches input (1-7)\n");

break;

case 6:

printf("Saturday\n");

break;

case 7:

printf("Sunday\n");

break;

return 0;

Example 2:
#include <stdio.h>
#define MAX 4
int main()
{

int a = 3;

switch(MAX>>1+~-1){//MAX>>1+~-1->4>>1+~-1->~-1->-(-1+1)->0->MAX>>1+0->MAX>>1->4/2->2

NEXT

55
switch case statement in C

case MAX>>1+~-3:

printf("ZERO\n");

break;

case 1:

printf("ONE\n");

break;

case MAX>>1:

printf("TWO\n");

break;

case (MAX>>1+~-3)+3://~-3->-(-3+1)->2->MAX>>1+2->MAX>>3->4/2->2/2->1/2->0

printf("THREE\n");

break;

case MAX:

printf("FOUR\n");

break;

case 5:

printf("FIVE\n");

break;

case 6:

printf("SIX\n");

break;

return 0;

NEXT

56
switch case statement in C

Example 3:

#include <stdio.h>

int main()

char ch;

printf("Input a character : ");

ch = getchar();

switch(ch){

case 'a':

case 'e':

case 'i':

case 'o':

case 'u':

printf("Vowels\n");

break;

case '0':

case '1':

case '2':

case '3':

case '4':

case '5':

case '6':

case '7':

case '8':

case '9':

printf("Digit\n");

break; NEXT

57
switch case statement in C

default:

printf("Input only vowels and digits\n");

return 0;

NEXT

58
Loops in C

8.2Loops

Example 1: print natural numbers between 1 to 10

#include <stdio.h>

int main()

int i=1;

while(i<=10){

printf("%d\t",i);

i++;

i=1;

printf("\n");

do{

printf("%d\t",i);

i++;

}while(i<=10);

printf("\n"); NEXT

59
Loops in C

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

printf("%d\t",i);

return 0;

}
Example 2: print factorial of 5 using all three loops
5! = 5*4*3*2*1 = 120
6! = 6 * 5! = 6 * 120 = 720
#include <stdio.h>
int main()

int num=6,fact=1;

while(num>=1){

fact *= num;//1 * 5->5*4->20 * 3->60 * 2->120 * 1->120

num--;

printf("Factorial = %d\n",fact);

num = 6,fact = 1;

do{

fact *= num;

num--;

}while(num>=1);

printf("Factorail = %d\n",fact);

for(num=6,fact=1;num>=1;num--){

fact *= num;

printf("Factorail = %d\n",fact); NEXT

60
While Loop in C

return 0;

8.2.1While
Find the first digit and last digit of a number

#include <stdio.h>

int main()

int num,fd,ld;

printf("Input any digit number greater than 2 : ");

scanf("%d",&num);

ld = num%10;

while(num>=10){

num/=10;//num = num / 10->456/10 -> 45(num)45>=10(t)->45/10->4 4>=10(f) come out of loop

fd = num;

printf("First digit = %d\nLast digit = %d\n",fd,ld);

return 0; NEXT

61
While Loop in C

Example 4:

#include <stdio.h>

int main()

int i = 20;

while(i){//in c we know anything zero is false and other than zero is true

//i -> 20 i->10 i->5 i->2 i->1 i->0 false exits the loop

printf("%d\t",i);//20 10 5 2 1

i>>=1;//i = i/2->20/2->10(i)->10/2->5(i)->5/2->2(i)->2/2->1(i)->1/2->0(i)

return 0;

Example 5:

How to find the count of digits of a number

How to find the sum and product of digits of a number

How to check whether a number is Armstrong or not

#include <stdio.h>

#include <math.h>

int main()

int num,rem,anum=0,count=0,sum=0,prod=1,onum;

printf("Input any digit number : ");

scanf("%d",&num);

onum = num;

while(num!=0){

count++; NEXT

62
While Loop in C

num/=10;

printf("Count = %d\n",count);

num = onum;

while(num!=0){

rem = num%10;

sum += rem;

prod *=rem;

anum += pow(rem,count);

num/=10;

printf("Sum = %d\tProdcut = %d\n",sum,prod);

if(anum==onum){printf("It is an armstrong number\n");}

else{printf("It is not an arsmtrong number\n");}

return 0;

Example of pow function

#include <stdio.h>

#include <math.h>

int main()

int a = 5,b = 2;

int c = (pow(a,b)+0.5);//pow(5,2)->24.567 so when we store in int rounding happens it gives

//24 instead of 25

printf("c = %d\n",c); NEXT

63
While Loop in C

return 0;

How to print the digits of a number in reverse

Input -> 5698

Output -> 8965

How to check whether the number is palindrome or not

Forward and reverse should be same

#include <stdio.h>

int main()

int num,rnum=0,rem,onum;//num = 4598

printf("Input a number : ");

scanf("%d",&num);

onum = num;

while(num!=0){//459!=0(t) 45!=0(t) 4!=0(t) 0 !=0 (f)

rem = num%10;//this gives each time last digit of num 8 9 5 4

rnum = rnum*10+rem;// 0 * 10+8->8 -> 8*10+9->89 ->89*10+5->895->895*10+4->8954

num/=10;//num = num/10 this removes last digit from num 459 45 4 0

printf("Reverse of the number is %d\n",rnum);

if(rnum==onum){printf("It is a palindrome number\n");}

else{printf("Not a palindrome number\n");}

return 0;

How to print the digits of a number in words

Input : 87564

Output : EIGHT SEVEN FIVE SIX FOUR NEXT

64
While Loop in C

STEP 1: Find reverse of the number rnum=46578 count = 5

STEP 2: Find the count of digits of a number

STEP 3: create a loop get each digit and print in words while printing in words decrement count
depending on count place the place value

Print along with place value

Output: EIGHTY SEVEN THOUSAND FIVE HUNDRED SIXTY FOUR

Count ->5 and count ->2 then print TY

Count ->4 -> print thousand

Count->3->print hundered

Count->1 -> print “ “

#include <stdio.h>

int main()

int num,rnum=0,rem,onum,count=0;//num = 4598

printf("Input a number : ");

scanf("%d",&num);

onum = num;

while(num!=0){

rem = num%10;

count++;

rnum = rnum*10+rem;

num/=10;

while(rnum!=0){

switch(rnum%10){

case 0: NEXT

65
While Loop in C

printf(" ZERO");

break;

case 1:

printf(" ONE");

break;

case 2:

printf(" TWO");

break;

case 3:

printf(" THREE");

break;

case 4:

printf(" FOUR");

break;

case 5:

printf(" FIVE");

break;

case 6:

printf(" SIX");

break;

case 7:

printf(" SEVEN");

break;

case 8:

printf(" EIGHT");

break;

case 9: NEXT

66
While Loop in C

printf(" NINE");

switch(count){

case 5:

case 2:

printf("TY");

break;

case 4:

printf(" THOUSAND");

break;

case 3:

printf(" HUNDRED");

break;

case 1:

printf(" ");

count--;

rnum/=10;

return 0;

8.2.2do while
Even when condition is false loop gets executed atleast once so we use do while loop for menu
driven application where menu has to be displayed atleast once and then the user can select the
menu or exit the application

#include <stdio.h>

int main()

{ NEXT

67
Do while in C

int i = 20;

do{

printf("%d\t",i);//20 10 5 2 1

i>>=1;//i = i >> 1;//20>>1->20/2->10(i)->10/2->5 -> 5/2-> 2 -> 2/2->1->1/2->0

}while(i);//10(t) 5(t) 2(t) 1(t) 0(f) exits the loop

return 0;

Example 2:

#include <stdio.h>

int main()

char ch;

int a,b;

do{

fflush(stdin);

printf("\n\t1.Press '+' for addition ");

printf("\n\t2.Press '-' for subtraction ");

printf("\n\t3.Press '*' for multiplication ");

printf("\n\t3.Press '/' for division ");

printf("\n\t5.Press 'e' to exit the application ");

printf("\nSelect your choice");

ch = getchar();

switch(ch){

case '+':

printf("Input the two values : "); NEXT


Do while in C

scanf("%d%d",&a,&b);

printf("Addition = %d\n",(a+b));

break;

case '-':

printf("Input the two values : ");

scanf("%d%d",&a,&b);

printf("Subtraction = %d\n",(a-b));

break;

case '*':

printf("Input the two values : ");

scanf("%d%d",&a,&b);

printf("Multiplication = %d\n",(a*b));

break;

case '/':

printf("Input the two values : ");

scanf("%d%d",&a,&b);

printf("Divison = %.2f\n",((float)a/b));

default:

printf("\nPresss e to exit the application");

}while(ch!='e');

return 0;

8.2.3for
How to get this output only one for loop to be used

1 10
2 9
3 8
4 7 NEXT
For loop in C

5 6
6 5
7 4
8 3
9 2
10 1
Example 1:
#include <stdio.h>

int main()
{
int i,j;
for(i=1,j=10;i<=10&&j>=1;i++,j--){//for(;;)->infinte loop
printf("%d\t%d\n",i,j);
}
return 0;
}

We can use characters also inside for loop

Example 2:

#include <stdio.h>

int main()

char ch;

for(ch='a';ch<='z';ch++){

printf("%c\n",ch);

return 0;

Example 3:

Print the multiplication table of any given number

Num = 5

5*1=5

5 * 2 = 10 NEXT
For loop in C

5 * 3 = 15

...

...

5 * 10 = 50

#include <stdio.h>

int main()

int num,i;

printf("Input a number : ");

scanf("%d",&num);

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

printf("%d * %d = %d\n",num,i,(num*i));

return 0;

Example 4:

#include <stdio.h>

int main()

int i;

for(i=20;i;i>>=1){

printf("%d\t",i);

return 0;

} NEXT
For loop in C

How to print the factors of a number

Example 5:

24 -> 1,2,3,4,6,8,12,24

36 -> 1,2,3,4,6,9,12,18,36

How to find count of number of factors

How to check whether it is prime or not

Prime numbers factors are 1 and itself so for prime numbers count of number of factors should be 2

#include <stdio.h>

int main()

int num,i,count=0;

printf("Input a number : ");

scanf("%d",&num);

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

if(num%i==0){count++;printf("%d\t",i);}

printf("\nCount of number of factors is %d\n",count);

if(count==2){printf("It is a prime number\n");}

else{printf("Not a prime number\n");}

return 0;

Example 6:

How to find the GCD of two numbers

24-> 1,2,3,4,6,8,12,24

36-> 1,2,3,4,6,9,12,18,36

GCD->12 NEXT
For loop in C

#include <stdio.h>

int main()

int num1,num2,i,gcd;

printf("Input num1 and num2 : ");

scanf("%d%d",&num1,&num2);

for(i=1;i<=num1&&i<=num2;i++){

if(num1%i==0&&num2%i==0){gcd=i;}

printf("GCD = %d\n",gcd);

return 0;

Example 7: Fibonnoci series


1 1 2 3 5 8 13 21 34 55
#include <stdio.h>
int main()

int nos,i,t1=1,t2=1,nt;

printf("Input the number of series to be printed : ");

scanf("%d",&nos);

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

printf("%d\t",t1);

nt = t1 + t2;

t1 = t2;

t2 = nt;

return 0;

} NEXT
For loop in C

Pattern printing

How to print half pyramid

* *

* * *

* * * *

* * * * *

#include <stdio.h>

int main()

int rows,i,j;

printf("Input the number of rows : ");

scanf("%d",&rows);

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

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

printf("*");

printf("\n");

return 0;

How to get inverted half pyramid

#include <stdio.h>

int main()

int rows,i,j; NEXT


For loop in C

printf("Input the number of rows : ");

scanf("%d",&rows);

for(i=rows;i>=1;i--){

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

printf("*");

printf("\n");

return 0;

How to print full pyramid

* * *

* * * * *

* * * * * * *

NEXT
For loop in C

#include <stdio.h>

int main()

int rows,i,j,k=0,sp;

printf("Input the number of rows : ");

scanf("%d",&rows);

for(i=rows;i>=1;i--,k=0){

for(sp=1;sp<=rows-i;sp++){

printf(" ");

while(k!=2*i-1){

printf("*");

k++;

printf("\n");

return 0;

NEXT
For loop in C

How to print the given pattern

#include <stdio.h>

int main()

int rows,i,j,k=0,l;

printf("Input the number of rows : ");

scanf("%d",&rows);

for(i=rows,l=0;i>=1;i--,l++,k=0){

for(j=1;j<=2*i;j++){

printf("*");

while(i==j&&k!=2*l){

printf(" ");

k++;

printf("\n");

} NEXT
For loop in C

for(i=1,l=rows-1;i<=rows;i++,l--,k=0){

for(j=1;j<=2*i;j++){

printf("*");

while(i==j&&k!=2*l){

printf(" ");

k++;

printf("\n");

return 0;

How to print the following pattern

2 6

3 7 10

4 8 11 13

5 9 12 14 15

NEXT
For loop in C

#include <stdio.h>

int main()

int rows,i,j,n,af=0;

printf("Input the number of rows : ");

scanf("%d",&rows);

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

for(j=1,n=rows;j<=i;j++,n--){

if(j==1){af=0;}

if(j>=2){af+=n;}

printf("%d\t",(i+af));

printf("\n");

return 0;

}
Statements in C

Statements in C language
1) –break -> it takes control out of the loop ie it breaks the loop
2) –continue -> it skips particular iteration but will be within the loop
3) –goto -> Unconditional transfer developers will avoid using goto since it may create infinite
loop or may cause bugs in the code it is advisable not to use goto since it branches from one
location to another location without any condition

How to use break and continue


Example 1:

#include <stdio.h>

int main()

int i=1;

for(;;){//infinite loop

if(i>30){break;}

if(i>=11&&i<=20){i++;continue;}

printf("%d\n",i);

i++;

return 0;

Pronic number

12 = 3*4

20 = 4*5

30 = 5*6

Example 2:

#include <stdio.h>

int main()
Statements in C

int num,pnum,i=1;

printf("Input a number : ");

scanf("%d",&num);

while(1){

pnum = i * (i+1);

if(pnum==num){printf("It is a pronic number\n");break;}

else if(pnum<num){i++;continue;}

else{printf("It is not a pronic number\n");break;}

return 0;

How to use goto


Without loop get 5 numbers find the sum and print it now if any number is negative then stop
getting the number and print its sum

Example 3:

#include <stdio.h>

int main()

int num,sum=0,i=1;

Loop1: printf("Input a number : ");

scanf("%d",&num);

if(num<0){goto Loop2;}

sum+=num;

if(++i<=5){goto Loop1;}

Loop2: printf("Sum = %d\n",sum);

return 0;

}
Arrays in C

Arrays in C language

What is an array and how to declare and initialize an array?

Example 1:

#include <stdio.h>

int main()

int arr[5]={10,20};

//when we intialize an array to less than its size rest of the elements

//will be intialized to zero

//there in no bound checking for arrays in c we can exceed the limits

//of array in c

int i;

for(i=0;i<8;i++){

printf("%d\t",i[arr]);

return 0;
Arrays in C

83
Arrays in C

Example 2: finding size of an array

#include <stdio.h>

int main()

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

//when we intialize an array to less than its size rest of the elements

//will be intialized to zero

//there in no bound checking for arrays in c we can exceed the limits

//of array in c

int i;

int size = sizeof(arr)/sizeof(arr[0]);

printf("Size of an array is %d\n",size);

for(i=0;i<size;i++){

printf("%d\t",i[arr]);

return 0;

Example 3:

#include <stdio.h>

int main()

int arr[]={1,2,3,4,5};//arr[0]-2 arr[1]-3

int l;

int i = arr[0]++;//assign and then increment i = 1->i=2

int j = ++arr[1];//increment first assign next arr[1]=2 j=3

int k = arr[i++];//arr[1] k = 3

printf("i = %d\nj = %d\nk = %d\n",i,j,k);//i=2,j=3,k=3


Strings in c

for(l=0;l<5;l++){

printf("%d\t",l[arr]);//2 3 3 4 5

return 0;

Example 3

#include <stdio.h>

int main()

int arr[]={10,20,30,40,50};

int i;

int size = sizeof(arr)/sizeof(arr[0]);

for(i=0;i<size;i++){

arr[i]+=5;

printf("\n-------DISPLAYING ARRAY ELEMENTS---------\n");

for(i=0;i<size;i++){

printf("%d\t",arr[i]);

return 0;

How to find the sum and average of elements of an array

#include <stdio.h>

int main()

int arr[100],noe,i,sum=0;

float avg;
Arrays in C

printf("Input the number of elements of the array : ");

scanf("%d",&noe);

printf("Input the %d array elements : ",noe);

for(i=0;i<noe;i++){

scanf("%d",&arr[i]);

for(i=0;i<noe;i++){

sum+=arr[i];

avg = (float)sum/noe;//5/2->2 (float)5/2->2.5

printf("Sum = %d\nAverage = %.2f\n",sum,avg);

return 0;

How to find largest element and smallest element in an array

#include <stdio.h>

int main()

int arr[100],noe,i,le,se;

printf("Input the number of elements of the array : ");

scanf("%d",&noe);

printf("Input the %d elements of the array : ",noe);

for(i=0;i<noe;i++){

scanf("%d",&arr[i]);

le = arr[0];

se = arr[0];

86
Arrays in C

for(i=0;i<noe;i++){

if(arr[i]>le){le = arr[i];}

if(arr[i]<se){se = arr[i];}

printf("Largest element = %d\nSmallest element = %d\n",le,se);

return 0;

How to copy array elements

#include <stdio.h>

int main()

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

int i,arr2[5];

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

arr2[i]=arr1[i];

printf("--------COPIED ARRAY IS--------\n");

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

printf("%d\t",arr2[i]);

return 0;

How to print only prime numbers of an element of an array

#include <stdio.h>

int main()

87
Arrays in C

int arr[100],noe,i,j,count=0;

printf("Input the number of elements of the array : ");

scanf("%d",&noe);

printf("Input %d elements of the array : ",noe);

for(i=0;i<noe;i++){

scanf("%d",&arr[i]);

printf("\n----------PRIME NUMBERS IN ARRAY IS---------\n");

for(i=0;i<noe;i++){

for(j=1;j<=arr[i];j++){

if(arr[i]%j==0){count++;}

if(count==2){printf("%d\t",arr[i]);count=0;}

else{count=0;continue;}

return 0;

How to store separately even numbers and odd numbers of an array and display it

#include <stdio.h>

int main()

int arr[100],noe,earr[100],oarr[100],coen=0,coon=0,i;

printf("Input the number of elements of the array : ");

scanf("%d",&noe);

printf("Input the %d elements of the array : ",noe);

for(i=0;i<noe;i++){

88
Arrays in C

scanf("%d",&arr[i]);

for(i=0;i<noe;i++){

if(arr[i]%2==0){earr[coen]=arr[i];coen++;}

else{oarr[coon]=arr[i];coon++;}

printf("\n---------DISPLAYING EVEN ELEMENTS OF ARRAY----------\n");

for(i=0;i<coen;i++){

printf("%d\t",earr[i]);

printf("\n---------DISPLAYING ODD ELEMENTS OF ARRAY----------\n");

for(i=0;i<coon;i++){

printf("%d\t",oarr[i]);

return 0;

89
Arrays in C

How to insert an element into an array


#include <stdio.h>
int main()
{
int arr[100],noe,pos,ele,i;
printf("Input the array elements : ");

scanf("%d",&noe);

printf("Input the %d elements of the array : ",noe);

for(i=0;i<noe;i++){

scanf("%d",&arr[i]);

printf("----------DISPLAYING ARRAY ELEMENTS-------------\n");

for(i=0;i<noe;i++){

printf("%d\t",arr[i]);

printf("\nInput the position where to insert : ");


scanf("%d",&pos);
printf("Input the element to be inserted : ");
scanf("%d",&ele);
for(i=noe-1;i>=pos-1;i--){
arr[i+1]=arr[i];
}
arr[pos-1]=ele;

printf("\n--------ARRAY AFTER INSERTION IS-----------\n");

for(i=0;i<=noe;i++){

printf("%d\t",arr[i]);

return 0;

90
Arrays in C

How to delete an element in array


#include <stdio.h>

int main()

int arr[100],noe,pos,i;

printf("Input the array elements : ");

scanf("%d",&noe);

printf("Input the %d elements of the array : ",noe);

for(i=0;i<noe;i++){

scanf("%d",&arr[i]);

printf("----------DISPLAYING ARRAY ELEMENTS-------------\n");

for(i=0;i<noe;i++){

printf("%d\t",arr[i]);

printf("\nInput the position where to delete : ");

scanf("%d",&pos);

for(i=pos-1;i<noe;i++){

arr[i]=arr[i+1];

printf("\n--------ARRAY AFTER DELETION IS-----------\n");

for(i=0;i<noe-1;i++){

printf("%d\t",arr[i]);

return 0;

91
Arrays in C

How to sort an element in an array ?


So for this we go for bubble sort it is the easiest sorting technique and effective also

#include <stdio.h>

int main()

int arr[6]={11,13,15,14,17,16};

int noe=6,i,j,flag=0;

for(i=0;i<noe-1;i++){

printf("\n%d pass\n",(i+1));

for(j=0;j<noe-1;j++){

if(arr[j]>arr[j+1]){

int temp = arr[j];

arr[j]=arr[j+1];

arr[j+1]=temp;

flag=1;

92
Arrays in C

if(flag){flag=0;continue;}

else{break;}

printf("\n------ARRAY AFTER SORTING----------\n");

for(i=0;i<noe;i++){

printf("%d\t",arr[i]);

return 0;

Linear search technique


#include <stdio.h>

int main()

int arr[10]={10,17,18,13,16,14},noe=6,i,se;

printf("Input the element to be searched : ");

scanf("%d",&se);

for(i=0;i<noe;i++){

if(arr[i]==se){printf("%d found at location %d\n",se,(i+1));break;}

if(i==noe){printf("%d not found in array\n",se);}

return 0;

93
Arrays in C

Two dimensional array


How to declare and initialize a two dimensional array and work with it

#include <stdio.h>

int main()

int arr[3][4]={

{1,2,3,4},

{5,6,7,8},

{9,10,11,12}

};

int i,j;

printf("---------DISPLAYING ARRAY ELMENTS--------\n");

for(i=0;i<3;i++){

for(j=0;j<4;j++){

printf("%d\t",arr[i][j]);

printf("\n");

94
Arrays in C

return 0;

How to record two cities weekly temperature and display it

#include <stdio.h>

#define CITY 2

#define WEEK 7

int main()

int temp[CITY][WEEK];

int i,j;

for(i=0;i<CITY;i++){

printf("Input City %d weekly temperature : ",(i+1));

for(j=0;j<WEEK;j++){

scanf("%d",&temp[i][j]);

printf("\n---------DISPLAYING WEEKLY TEMPERATURE-----------\n");

for(i=0;i<CITY;i++){

printf("CITY %d Temp : ",(i+1));

for(j=0;j<WEEK;j++){

printf("%d\t",temp[i][j]);

printf("\n");

return 0;

95
Arrays in C

Two dimensional array we can all it as matrix or table

How to add two matrix, transpose of matrix and multiplication of matrix

#include <stdio.h>

int main()

int arr1[3][3],arr2[3][3],rarr[3][3],tarr[3][3],mofa[3][3]={0};

int i,j,k;

printf("Input the array 1 elements : ");

for(i=0;i<3;i++){

for(j=0;j<3;j++){

scanf("%d",&arr1[i][j]);

printf("Input the array 2 elements : ");

for(i=0;i<3;i++){

for(j=0;j<3;j++){

scanf("%d",&arr2[i][j]);

for(i=0;i<3;i++){

for(j=0;j<3;j++){

rarr[i][j]=arr1[i][j]+arr2[i][j];

printf("\n--------ARRAY AFTER ADDITION IS-----------\n");

for(i=0;i<3;i++){

96
Arrays in C

for(j=0;j<3;j++){

printf("%d\t",rarr[i][j]);

printf("\n");

printf("\n-----------TRASPOSE OF ADDITION ARRAY IS----------\n");

for(i=0;i<3;i++){

for(j=0;j<3;j++){

tarr[i][j]=rarr[j][i];

for(i=0;i<3;i++){

for(j=0;j<3;j++){

printf("%d\t",tarr[i][j]);

printf("\n");

for(i=0;i<3;i++){

for(j=0;j<3;j++){

for(k=0;k<3;k++){

mofa[i][j]+=arr1[i][k]*arr2[k][j];

printf("\n--------ARRAY AFTER MULTIPLICATION------------\n");

for(i=0;i<3;i++){

for(j=0;j<3;j++){

97
Arrays in C

printf("%d\t",mofa[i][j]);

printf("\n");

return 0;

Three dimensional array


#include <stdio.h>

int main()

int arr[2][3][3]={

{{1,2,3},{4,5,6},{7,8,9}},

{{10,11,12},{13,14,15},{16,17,18}},

};

int i,j,k;

printf("\n------DISPLAYING ARRAY----------\n");

for(i=0;i<2;i++){

for(j=0;j<3;j++){

for(k=0;k<3;k++){

printf("%d\t",arr[i][j][k]);

printf("\n");

printf("\n");

return 0;

98
Arrays in C

}
There are 2 departments with 2 students and 3 subjects find the total of marks of each student in
each department
#include <stdio.h>
#define DEPT 2
#define STUD 2
#define SUBJ 3
int main()
{

int arr[DEPT][STUD][SUBJ]={

{{67,78,65},{86,78,83}},

{{87,76,79},{94,78,95}}

};

int i,j,k,total=0;

printf("\n------DISPLAYING ARRAY----------\n");

for(i=0;i<DEPT;i++){

printf("DEPARTMENT %d : ",(i+1));

for(j=0;j<STUD;j++){

printf("STUDENT %d :",(j+1));

for(k=0;k<SUBJ;k++){

total += arr[i][j][k];

printf("TOTAL : %d\n",total);

total = 0;

printf("\n\t\t");

return 0;

99
Strings in c

Strings in c

Example 1:

#include <stdio.h>

int main()

char str1[]="Hello world";

char *str2="Hello world";

char str3[12]={'H','e','l','l','o',' ','w','o','r','l','d'};

char str4[12],*str5;

str5 = str2;

printf("String 1 is %s\n",str1);

printf("String 2 is %s\n",str2);

printf("String 3 is %s\n",str3);

printf("String 5 is %s\n",str5);

return 0;

}
Strings in c

How to read strings

Using scanf we can read a string but any white space will be marked as end of string in scanf

Then how to read a line of string using scanf so for this we go for width specifier

#include <stdio.h>

int main()

char str[50];

printf("Input a string : ");

scanf("%[^\n]s",str);

printf("String inputted is %s\n",str);

return 0;

There is a function called gets() and puts() which can read and print the string on the console screen

What is the difference between gets() and scanf()

We know scanf can be used to read any type of data gets is specially to read a string

Difference between puts and printf

Puts is used to print strings on console screen where as print to print any type of data

-puts will print and go to next line by default printf will print and wait in same line

How to read a string character by character

#include <stdio.h>

int main()

char str[50];
Strings in c

char ch;

int i=0;

printf("Input a string : ");

while((ch=getchar())!='\n'){

str[i]=ch;

i++;

str[i]='\0';

printf("String inputted is %s\n",str);

return 0;

How to print the length of the string with built in function and without built in function

-string.h and its built in function strlen(str)

#include <stdio.h>

#include <string.h>

int main()

char str1[50];

char str2[40];

int len;

printf("Input string 1 : ");

gets(str1);

printf("Length of string 1 is %d\n",strlen(str1));

printf("Input string 2 : ");

gets(str2);

printf("Length of string 2 is %d\n",strlen(str2));

//without built in function how to find the length


Strings in c

for(len=0;str1[len]!='\0';len++);

printf("Length of string 1 without built in funcntion is %d\n",len);

len=0;

while(str2[len]!='\0'){len++;}

printf("Length of string 2 without built in function is %d\n",len);

return 0;

How to copy one string into another string

-string.h has built in function strcpy(dest,src)

#include <stdio.h>

#include <string.h>

int main()

char str1[50];

char str2[40],str3[40];

int i;

printf("Input string 1 : ");

gets(str1);

strcpy(str2,str1);

printf("Copied string is %s\n",str2);

for(i=0;str1[i]!='\0';i++){

str3[i]=str1[i];

str3[i]='\0';

printf("Copied string is %s\n",str3);

return 0;

}
Strings in c

Whenever it is a pointer to character the string is stored in read only memory so modifications not
allowed

But when it is an array of character it is store in read write shared memory where modifications
allowed

#include <stdio.h>

#include <string.h>

int main()

{//3,0 right most value assigned

if(printf("%d",456),printf("%s","\0")){//456

printf("\nHai");

}else{

printf("\nBye");

return 0;

Example 5:

#include <stdio.h>

#include <string.h>

int main()

char str1[20]="Hello world";

*(str1+5)='\0';

printf("%s",str1);

return 0;

How to reverse the string how to check palindrome or not

-malayalam

-madam
Strings in c

-radar

#include <stdio.h>

#include <string.h>

int main()

char str1[40],rstr[40];

int begin=0,len=0,end;

printf("Input a string :");

gets(str1);

while(str1[len]!='\0'){

len++;

}//end points to end f string 1

end = len-1;

for(begin=0;begin<len;begin++,end--){

rstr[begin]=str1[end];

rstr[begin]='\0';

printf("Reverse of string 1 is %s\n",rstr);

for(begin=0;begin<len;begin++){

if(rstr[begin]!=str1[begin]){printf("It is not a palindrome\n");break;}

if(begin==len){printf("It is a palindrome\n");}

return 0;

With built in function

#include <stdio.h>

#include <string.h>
Strings in c

int main()

char str1[40],rstr[40];

printf("Input a string : ");

gets(str1);

strcpy(rstr,str1);

strrev(rstr);

if(strcmp(rstr,str1)==0){printf("It is a palindrome\n");}

else{printf("Not a palindrome\n");}

return 0;

How to concatenate two strings

-char str1=”arun”;

-chat str2 =”kumar”;

-strcat(str1,str2)->pf(str1)->arunkumar as output

With built in function and without built in function

Here in concatenation destination size should be large enough to store both the strings

#include <stdio.h>

int main()

char str1[40],str2[20],str3[20];

int len=0,i;

printf("Input string 1 : ");

gets(str1);

printf("Input string 2 : ");

gets(str2);
Strings in c

printf("Input strinng 3 : ");

gets(str3);

strcat(str1,str2);

printf("Concatentaed string is %s\n",str1);

while(str2[len]!='\0'){len++;}

for(i=0;str3[i]!='\0';i++,len++){

str2[len]=str3[i];

str2[len]='\0';

printf("Concatenated string with out built in function is %s\n",str2);

return 0;

Find the frequency of occurrence of a character in a given string

-string str1 – “sachin is a sports person and was awarded”

-find frequency of occurrence of s ouput – 6

#include <stdio.h>

int main()

char str1[60],ch;

int i,foc=0;

printf("Input a string : ");

gets(str1);

printf("Input a character to find its frequency of occurence : ");

ch = getchar();

for(i=0;str1[i]!='\0';i++){

if(str1[i]==ch){foc++;}
Strings in c

printf("Frequency of occurence of %c is %d\n",ch,foc);

return 0;

How to find the count of vowels, digits, spaces and consonants in a given string

#include <stdio.h>

int main()

char str1[60];

int i,cov=0,cod=0,cosp=0,coc=0;

printf("Input a string : ");

gets(str1);

for(i=0;str1[i]!='\0';i++){

if(str1[i]=='a'||str1[i]=='e'||str1[i]=='i'||str1[i]=='o'||str1[i]=='u'){cov++;}

if(str1[i]>='0'&&str1[i]<='9'){cod++;}

if(str1[i]>='a'&&str1[i]<='z'){coc++;}

if(str1[i]==' '){cosp++;}

printf("Count of vowels is %d\n",cov);

printf("Count of digits is %d\n",cod);

printf("Count of spaces is %d\n",cosp);

printf("Count of cosonants is %d\n",coc);

return 0;

}
Functions in c

Functions
What is a function?

We divide the main task into subtask and achieve it individually and finally called so as to complete
the main task

When there are any repetitive codes we write it as function and call it as many times required

Need for function?

Number of lines of code is reduced and also easy to maintain

What is a function signature?

-returnvalue funname(arglist)

Based on signature we can classify the function into 4 types

1) function with return values and with arguments


2) function without return values and without arguments
3) function with return values and without arguments
4) function without return values and with arguments
function call?
What is function call?
Two types
1) call by value
2) call by reference
1) int add(int,int)
2) void add()
3) int add()
4) void add(int,int)

function with return values and with arguments


#include <stdio.h>
int add(int,int);//function prototype or function declaration
//it will be helpful in debugging the errors
int main()
{
int a,b,c;
printf("Input the two values : ");
scanf("%d%d",&a,&b);
c=add(a,b);//call by value
printf("C = %d\n",c);
return 0;
}
int add(int a,int b){
Arrays in C

return a+b;

110
Functions in c

function without return values and without arguments

#include <stdio.h>

void add();//function prototype or function declaration

//it will be helpful in debugging the errors

int main()

add();//call by value

return 0;

void add(){

int a,b,c;

printf("Input the two values : ");

scanf("%d%d",&a,&b);

c=a+b;

printf("c = %d\n",c);

function with return values and without arguments

#include <stdio.h>

int add();//function prototype or function declaration

//it will be helpful in debugging the errors

int main()

int c;

c=add();//call by value

printf("c = %d\n",c);
Functions in c

return 0;

int add(){

int a,b;

printf("Input the two values : ");

scanf("%d%d",&a,&b);

return a+b;

function without return values and with arguments

#include <stdio.h>
void add(int,int);//function prototype or function declaration
//it will be helpful in debugging the errors
int main()
{
int a,b;
printf("Input the two values : ");
scanf("%d%d",&a,&b);
add(a,b);//call by value
return 0;
}
void add(int a,int b){
int c = a+b;
printf("c = %d\n",c);
}

Using call by value a function can return only one value


#include <stdio.h>
int display();
int main()
{
printf("%d\n",display());
return 0;
}
int display(){
int a=10;//11,12,13
return a++,++a,++a;//10,12,13
}
Functions in c

We can declare and call the function at the same place

#include <stdio.h>

int main()

void display();//function declaration

display();//call by value

printf("return to main\n");

return 0;

void display()

printf("Inside display function\n");

We cannot define one function within another function

call by value
Swap two numbers
#include <stdio.h>
void swap(int,int);
int main()
{
int a,b;
printf("Input the two values : ");
scanf("%d%d",&a,&b);
printf("Before swapping a = %d and b = %d\n",a,b);
swap(a,b);
printf("After swapping a = %d and b = %d\n",a,b);
return 0;
}
void swap(int a,int b){
int temp = a;
a = b;
b = temp;
}
In call by value we pass the values directly so main does not get reflected with modifications
Functions in c

call by reference
we should know about pointers
#include <stdio.h>

int main()
{
int *ip;
char *cp;
float *fp;
double *dp;
printf("Size of integer pointer is %d\n",sizeof(ip));
printf("Size of char pointer is %d\n",sizeof(cp));
printf("Size of float pointer is %d\n",sizeof(fp));
printf("Size of double pointer is %d\n",sizeof(dp));
return 0;
}
Pointers
#include <stdio.h>
int main()
{
int a = 10;
int *ip;
ip = &a;
printf("Value of a is %d\n",a);
printf("Value of a is %d\n",*ip);
printf("Value of a is %d\n",*(&a));
printf("Address of a is %u\n",ip);
printf("Address of a is %u\n",&a);
return 0;
}
In call by reference changes get reflected on main
#include <stdio.h>
void swap(int *,int *);
int main()
{
int a,b;
printf("Input the two values : ");
scanf("%d%d",&a,&b);
printf("Before swapping a = %d and b = %d\n",a,b);
swap(&a,&b);//call by reference
printf("After swapping a = %d and b = %d\n",a,b);
return 0;
}
Arrays in C

void swap(int *a,int *b){

115
Functions in c

int temp = *a;


*a = *b;
*b = temp;
}
Pointers
#include <stdio.h>

int main()
{
int a = 20;
int *ip;
ip = &a;
printf("value of a is %d\n",a);
printf("value of a is %d\n",*ip);
printf("value of a is %d\n",*(&a));
*ip += 30;
printf("value of a is %d\n",a);
printf("value of a is %d\n",*ip);
printf("value of a is %d\n",*(&a));
return 0;
}

A function can return only one value using return keyword but a function can return multiple
values by call by reference or pointers
#include <stdio.h>
void mathOperation(int,int,int *,int *);
int main()
{
int a,b,sum,diff;
printf("Input the two values : ");
scanf("%d%d",&a,&b);
mathOperation(a,b,&sum,&diff);
printf("Sum = %d\nDifference = %d\n",sum,diff);
return 0;
}
void mathOperation(int x,int y,int *s,int *d){
*s = x + y;
*d = x - y;
}
Example 5:
#include <stdio.h>
float divide(int,int);
int checkZero(int);
int main()
{
Functions in c

int a,b;
printf("Input the two values : ");
scanf("%d%d",&a,&b);
printf("Divison = %.2f\n",divide(a,b));
return 0;
}
float divide(int a,int b){
if(checkZero(b)){return 0;}
else{return (float)a/b;}
}
int checkZero(int x){
if(x==0){return 1;}
else{return 0;}
}
Example 6:
How to print prime numbers between 1 to 100
#include <stdio.h>
void printPrime();
int isPrime(int);
int main()
{
printPrime();
return 0;
}
void printPrime(){
int i;
for(i=1;i<=100;i++){
if(isPrime(i)){printf("%d\n",i);}
}
}
int isPrime(int num){
int i;
for(i=2;i<num;i++){
if(num%i==0){return 0;}
}
return 1;
}
How to print Armstrong numbers from 10 to 10000
153 -> 1^3 + 5^3 + 3^3 -> 1 + 125 + 27 -> 153 armstrong number
#include <stdio.h>
#include <math.h>
void printArmstrong();
int isArsmtrong(int);
int main()
{
Functions in c

printArmstrong();
return 0;
}
void printArmstrong(){
int i;
for(i=10;i<=10000;i++){
if(isArsmtrong(i)){printf("%d\t",i);}
}
}
int isArsmtrong(int num){
int rem,onum,count=0,anum=0;
onum = num;
while(num!=0){
count++;
num/=10;
}
num = onum;
while(num!=0){
rem = num%10;
anum += pow(rem,count);
num/=10;
}
if(anum==onum){return 1;}
else{return 0;}
}

Recursive function
A recursive function is a function which calls itself again and again so u wont see the real
usage of recursive function in c for ordinary cases we can implement using loops itself rather
than having recursive function and also it is slower in execution recursive function requires a
condition when to stop
#include <math.h>
int WithOutRecursion(int);
int WithRecursion(int);
int main()
{
int num;
printf("Input a number : ");
scanf("%d",&num);
printf("With out recursion factorial is %d\n",WithOutRecursion(num));
printf("With recursion factorial is %d\n",WithRecursion(num));
return 0;
}
int WithOutRecursion(int num){
int fact=1;
Arrays in C

while(num>=1){ fact *= num;//5! = 5*4*3*2*1 ->120


num--;
}
return fact;
}
int WithRecursion(int num){
if(num>=1){return num*WithRecursion(num-
1);}//5*WithRecursion(4)//5*4*WithRecursion(3)
else{return 1;}//20*3*WithRecursion(2)->60*2*WithRecursion(1)->120*1
}
Without using semicolon how to print 1 to 10
#include <stdio.h>
#include <math.h>
#define NUM 10//preprecessor directives
int main(int n)
{
if(n<=NUM&&printf("%d\t",n)&&main(n+1)){}
}
How to work with arrays in function
#include <stdio.h>
void display(int);
int main()
{
int arr[]={10,20,30,40,50};
int i;
for(i=0;i<5;i++){
display(arr[i]);
}
return 0;
}
void display(int num){
printf("%d\t",num);
}

Arrays by default are pass by reference


#include <stdio.h>
void display(int []);
void increment(int []);
float average(int []);
int main()
{
int arr[]={10,20,30,40,50};
increment(arr);
display(arr);
printf("\nAverage of elements of array is %.2f\n",average(arr));

119
Functions in c

return 0;
}
void display(int num[]){
int i;
for(i=0;i<5;i++){
printf("%d\t",i[num]);
}
}
void increment(int num[]){
int i;
for(i=0;i<5;i++){
num[i]+=5;
}
}
float average(int num[]){
int i,sum=0;
for(i=0;i<5;i++){
sum+=num[i];
}
return (float)sum/5;
}
How to find the standard deviation of an array of elements
#include <stdio.h>
#include <math.h>
void getData(float []);
float standardDeviation(float []);
int main()
{
float arr[6];
getData(arr);
printf("Standard Deviation = %.2f\n",standardDeviation(arr));
return 0;
}
void getData(float arr[]){
int i;
printf("Input array elements : ");
for(i=0;i<6;i++){
scanf("%f",&arr[i]);
}
}
float standardDeviation(float arr[]){
int i;
float sum=0,mean,sd=0;
for(i=0;i<6;i++){
sum+=arr[i];
Functions in c

}
mean = sum/6;
for(i=0;i<6;i++){
sd+=pow(arr[i]-mean,2);
}
return sqrt(sd/6);
}
How to work with two dimensional array
#include <stdio.h>
void getData(int [][4]);
void display(int [][4]);
int main()
{
int arr[3][4];
getData(arr);
display(arr);
return 0;
}
void getData(int arr[][4]){
int i,j;
printf("Input the array elements : ");
for(i=0;i<3;i++){
for(j=0;j<4;j++){
scanf("%d",&arr[i][j]);
}
}
}
void display(int arr[][4]){
int i,j;
printf("\n-------DISPLAYING ARRAY ELEMENTS----------\n");
for(i=0;i<3;i++){
for(j=0;j<4;j++){
printf("%d\t",arr[i][j]);
}
printf("\n");
}
}
How to work with strings
#include <stdio.h>
void upperString(char []);
void lowerString(char []);
void subString(int,int,char [],char []);
int main()
{
char str[40],sstr[40];
Functions in c

int bi,ei;
printf("Input a string : ");
gets(str);
upperString(str);
printf("String in upper case is %s\n",str);
lowerString(str);
printf("String in lower case is %s\n",str);
printf("Input the beginning index and ending index to get a substtring : ");
scanf("%d%d",&bi,&ei);
subString(bi,ei,str,sstr);
printf("Substring from the string is %s\n",sstr);
return 0;
}
void upperString(char str[]){//a-97 A-65 -32
int i;
for(i=0;str[i]!='\0';i++){
if(str[i]>='a'&&str[i]<='z'){str[i]=str[i]-32;}
}
}
void lowerString(char str[]){//A-65 a-97 +32
int i;
for(i=0;str[i]!='\0';i++){
if(str[i]>='A'&&str[i]<='Z'){str[i]=str[i]+32;}
}
}
void subString(int bi,int ei,char str[],char sstr[]){
int i,j=0;
for(i=bi;i<=ei;i++,j++){
sstr[j]=str[i];
}
}

Storage classes in c
1) auto -> by default all local variables are auto so no need to use auto keyword
2) static -> 1) one time initialization only
2)reinitilaization not possible it maintains its state between different function
calls
3) extern
4) register

static keyword

#include <stdio.h>

void increment();
Storage class in c

int main()

int i;

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

increment();

return 0;

void increment(){

static int j=0;

printf("%d\t",j);

j++;//1 2 3 4

Extern

#include <stdio.h>

int a=10;

int main()

int a = 20;

extern int a;

printf("a = %d\n",a);

return 0;

#include <stdio.h>

extern int a;
Storage class in c

int main()

printf("a = %d\n",a);

return 0;

int a = 20;

register

register keyword stores the variable in cpu registers since we access the hardware it is faster in
execution and it is compiler dependent when we use a variable for more number of times we can
declare such a variable as register

we cannot use register variables for pointers

#include <stdio.h>

int main()

register int a = 20;

//int *ip=&a; not possible

printf("a = %d\n",a);

return 0;

How to use recursion and get five numbers as input and print its sum

#include <stdio.h>

int main()

static int i=1,sum=0;

int num;

printf("Input a number : ");


Storage class in c

scanf("%d",&num);

sum+=num;

if(++i<=5){main();}

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

return 0;

}
Structures in c

Strucuture in C

#include <stdio.h>

struct Employee{

char name[40];//40 bytes

int id;//4 bytes

float sal;//4 bytes

}e1={"arunkumar",145,5678.89f};//in order initialization

int main()

struct Employee e2={.id=146,.name="ravikrishna",.sal=6789.98f};//designated intialization

struct Employee e3;

printf("Input the name,id and salary of the employee : ");

scanf("%s%d%f",e3.name,&e3.id,&e3.sal);

printf("Size of strucutre employee is %d\n",sizeof(e1));

printf("Name of Employee : %s\n",e1.name);

printf("Id of Employee : %d\n",e1.id);


Arrays in C

printf("Salary of Employee : %f\n",e1.sal);

127
Structures in c

printf("Name of Employee : %s\n",e2.name);

printf("Id of Employee : %d\n",e2.id);

printf("Salary of Employee : %f\n",e2.sal);

printf("Name of Employee : %s\n",e3.name);

printf("Id of Employee : %d\n",e3.id);

printf("Salary of Employee : %f\n",e3.sal);

return 0;

For structures assignment operator is possible ie we can initialize a structure to another directly

->typedef is a keyword which creates alias name for existing name

#include <stdio.h>

int main()

typedef int age;

age x;

printf("Input the age : ");

scanf("%d",&x);

printf("Age is %d\n",x);

return 0;

Instead of using fully qualified name for structure we can create an alias name using typedef and use
it

#include <stdio.h>

typedef struct Employee{

char name[40];

int id;

}Emp;

int main()
Structures in c

Emp e2,e3;

printf("Input the name,id of the employee : ");

scanf("%s%d",e2.name,&e2.id);

printf("Name of Employee : %s\n",e2.name);

printf("Id of Employee : %d\n",e2.id);

e3 = e2;

printf("Name of Employee : %s\n",e3.name);

printf("Id of Employee : %d\n",e3.id);

return 0;

How to pass structure as argument to a function

#include <stdio.h>

typedef struct Employee{

char name[40];

int id;

}Emp;

Emp getRecord();

void display(Emp);

int main()

Emp e3;

e3 = getRecord();

display(e3);

return 0;

Emp getRecord(){
Structures in c

Emp e2;

printf("Input the name,id of the employee : ");

scanf("%s%d",e2.name,&e2.id);

return e2;

void display(Emp e3){

printf("Name of Employee : %s\n",e3.name);

printf("Id of Employee : %d\n",e3.id);

Array of structure

#include <stdio.h>

typedef struct Employee{

char name[40];

int id;

}Emp;

Emp getRecord();

void display(Emp);

int main()

Emp e1[3];

int i;

for(i=0;i<3;i++){

e1[i] = getRecord();

for(i=0;i<3;i++){

display(e1[i]);

}
Structures in c

return 0;

Emp getRecord(){

Emp e2;

printf("Input the name,id of the employee : ");

scanf("%s%d",e2.name,&e2.id);

return e2;

void display(Emp e3){

printf("Name of Employee : %s\n",e3.name);

printf("Id of Employee : %d\n",e3.id);

#include <stdio.h>

struct{int a[2];int b}arr[]={{{1},2},{{2},3}};

int main()

printf("%d\t%d\t%d\n",arr[0].a[0],arr[0].a[1],arr[0].b);//1 0 2

printf("%d\t%d\t%d\n",arr[1].a[0],arr[1].a[1],arr[1].b);//2 0 3

return 0;

//we know when array is intialized to less than its size rest of the elements initialzied

//to zero

How to pass structure as reference

#include <stdio.h>

typedef struct Calculate{

int num1,num2;

}Cal;
Structures in c

void addStrucutre(Cal,Cal,Cal *);

int main()

Cal c1={110,130};

Cal c2={.num2=10,.num1=30};

Cal c3;

addStrucutre(c1,c2,&c3);

printf("After addition structure is num1 = %d and num2 = %d\n",c3.num1,c3.num2);

return 0;

void addStrucutre(Cal c1,Cal c2,Cal * c3){

c3->num1 = c1.num1+c2.num1;

c3->num2 = c1.num2+c2.num2;

We pass the distance as argument and we add two distances in feets and inches if inches is greater
than 12 then increment feet by 1 and decrement inches by 12

#include <stdio.h>

typedef struct Distance{

float feet;

float inches

}Dist;

void addStrucutre(Dist,Dist,Dist *);

int main()

Dist c1={7,24};

Dist c2,c3;

printf("Input Distance 2 in feet and inches : ");

scanf("%f%f",&c2.feet,&c2.inches);
Structures in c

addStrucutre(c1,c2,&c3);

printf("After addition structure is %.2f feet and %.2f inches\n",c3.feet,c3.inches);

return 0;

void addStrucutre(Dist c1,Dist c2,Dist *c3){

c3->feet = c1.feet+c2.feet;

c3->inches = c1.inches+c2.inches;

while(c3->inches>=12){

c3->feet++;

c3->inches-=12;

Nested structure

A structure within another structure

#include <stdio.h>

struct CollegeDetails{

char collName[50];

int collId;

};

struct StudentDetails{

char studName[60];

int studId;

struct CollegeDetails cd;

};

int main()

struct StudentDetails sd={"arunkumar",202023,"Naresh",1456};


Pointers in c

printf("College Name : %s\n",sd.cd.collName);

printf("College Id : %d\n",sd.cd.collId);

printf("Stundet Name : %s\n",sd.studName);

printf("Student Id : %d\n",sd.studId);

return 0;

Union
What are union?

It is also data type similar to structure but here which is the largest data type memory gets allocated
only for it.

#include <stdio.h>

union Sample{

int x;//4

double y;//8

float z;//4

}s1;

int main()

union Sample s2;

printf("Size of union sample is %d\n",sizeof(s1));

return 0;

#include <stdio.h>

#include <string.h>

union Employee{

char name[50];

int id;
Arrays in C

float sal;

135
Pointers in c

}e1;

int main()

strcpy(e1.name,"arun kumar");

e1.id = 145;

e1.sal = 5678.98;

printf("Name : %s\n",e1.name);

printf("Id : %d\n",e1.id);

printf("Salary : %.3f\n",e1.sal);

return 0;

Enumerated data type


What is enum?

It is a named memory constant where each name will be assigned some integer value by default it
starts from zero if we think of reinitializing value any where within enum it is possible next names
value will be one increment of the previous value.

No two enums can have same name

Enums can be passed as argument to functions and can be returned since it is also a data type

In for loop and switch case we use enums ie with names

#include <stdio.h>

#include <string.h>

enum week{mon=1,tue,wed,thur,fri,sat,sun};

int main()

enum week day,i;

printf("Size of enum is %d\n",sizeof(day));


Pointers in c

printf("Input a day : ");

scanf("%d",&day);

switch(day){

case mon:

printf("Monday\n");

break;

case tue:

printf("Tuesday\n");

break;

case wed:

printf("Wednesday\n");

break;

case thur:

printf("Thursday\n");

break;

case fri:

printf("Friday\n");

break;

case sat:

printf("Saturday\n");

break;

case sun:

printf("Sunday\n");

break;

for(i=mon;i<=sun;i++){

printf("%d\t",i);
Pointers in c

return 0;

#include <stdio.h>

#include <string.h>

enum state{freezed,working};

typedef enum state est;

est func(est);

int main()

est e1=0;

(func(e1))?printf("Working\n"):printf("Freezed\n");

return 0;

est func(est s1){

return s1;

Pointers
What is pointer?

It is initialized to address of another variable or any address

Size of pointer is constant and it depends on machine so if it is 16 bit compiler size of pointer is 2
bytes if it is 32 bit compiler then size is 4 bytes

#include <stdio.h>

#include <string.h>

int main()

{
Arrays in C

int a = 10;

139
Pointers in c

int *ip;

ip = &a;

printf("Value of a is %d\n",a);

printf("Value of a is %d\n",*ip);

printf("Value of a is %d\n",*(&a));

printf("Address of a is %p\n",ip);

printf("Address of a is %p\n",&a);

*ip+=10;

printf("Value of a is %d\n",a);

printf("Value of a is %d\n",*ip);

printf("Value of a is %d\n",*(&a));

return 0;

Types of pointers

1) wild or bad pointer -> when a pointer is declared and not initialized it is initialized to random
memory location such a pointer we call it as wild or bad pointer
2) NULL pointer -> to avoid wild/bad pointer we initialize pointer to null values such a pointer
we call it as null pointer
#include <stdio.h>
#include <string.h>

int main()
{
int *ip1,*ip2,*ip3=NULL,*ip4=NULL;
if(ip1==ip2){printf("EQUAL\n");}
else{printf("NOT EQUAL\n");}
if(ip3==ip4){printf("EQUAL\n");}
else{printf("NOT EQUAL\n");}
return 0;
}
3) Dangling pointer -> when a pointer is initialized to another variable and if the variable is no
longer is referenced but still pointer points to same memory location such a kind of pointer
we call it as dangling pointer
#include <stdio.h>
#include <string.h>
Pointers in c

int main()
{
int *ip;
{
int a = 10;
ip = &a;
printf("a = %d\n",a);
}
printf("a = %d\n",*ip);
return 0;
}
4) Void or generic pointer
#include <stdio.h>
#include <string.h>

int main()
{
int a = 10;
float b = 45.56;
char ch = 't';
double c = 678.897;
void *vp;//this vp is generic pointer it can be intialized to any of the data type
//and get its value by casting
vp = &a;
printf("Value of integer is %d\n",*(int *)vp);
vp = &b;
printf("Value of float is %.2f\n",*(float *)vp);
vp = &ch;
printf("Value of character is %c\n",*(char *)vp);
vp = &c;
printf("Value of double is %.2lf\n",*(double *)vp);
return 0;
}
Double pointer how to declare and initialize a double pointer
#include <stdio.h>

int main()
{
int a = 10;
int *ip1,**ip2;
ip1 = &a;
ip2 = &ip1;
printf("Value of a is %d\n",a);
printf("Value of a using pointer is %d\n",*ip1);
printf("Value of a using double pointer is %d\n",**ip2);
Pointers in c

printf("Address of a is %u\n",&a);
printf("Address of a is %u\n",ip1);
printf("Address of a is %u\n",*ip2);
**ip2+=5;
printf("Value of a is %d\n",a);
printf("Value of a using pointer is %d\n",*ip1);
printf("Value of a using double pointer is %d\n",**ip2);
return 0;
}
How to work with arrays with array
#include <stdio.h>

int main()
{
int arr[]={10,20,30,40,50};
int *ip1;
int (*ip2)[5];
ip1 = arr;//arr referes base address &arr
ip2 = arr;
printf("Size of array is %d\n",sizeof(arr));
printf("size of ip1 is %d\n",sizeof(ip1));
printf("Size of ip2 is %d\n",sizeof(ip2));
printf("Address of ip1 is %u\n",ip1);
printf("Address of ip2 is %u\n",ip2);
ip1++;
ip2++;
printf("Address of ip1 is %u\n",ip1);
printf("Address of ip2 is %u\n",ip2);

return 0;
}
Arrays with pointers
#include <stdio.h>

int main()
{
int arr[]={10,20,30,40,50};
int *ip1,*ip2,noea;
ip1 = arr;
ip2 = arr;
while(ip1<&arr[5]){
printf("%d\t",*ip1);
ip1++;
}
Pointers in c

noea = ip1 - ip2;


printf("\nsize of array is %d\n",noea);
printf("third element of array is %d\n",*(ip2+2));
while(ip1>=&arr[0]){
printf("%d\t",*ip1);
ip1--;
}
return 0;
}
Pointer to pointer
#include <stdio.h>

int main()
{
int arr[]={10,20,30,40,50};
int *ip1,**ip2;
ip1 = arr;
ip2 = &ip1;
printf("Second element in array is %d\n",++*++*ip2);
printf("arr[1] = %d\n",arr[1]);
return 0;
}
What is the relationship between pointer and array

address
&arr[0] -> (arr+0)
&arr[1] ->(arr+1)
Value
->arr[0]->*(arr+0)
Pointers in c

->arr[1] -> *(arr+1)


#include <stdio.h>

int main()
{
int arr[5];
int i;
printf("Input the array elements : ");
for(i=0;i<5;i++){
scanf("%d",(arr+i));
}
printf("-------DISPLAYING ARRAY ELEMENTS---------\n");
for(i=0;i<5;i++){
printf("%d\t",*(arr+i));
}
return 0;
}
Two dimensional array
#include <stdio.h>

int main()
{
int arr[3][4];
int i,j;
printf("Input the array elements : ");
for(i=0;i<3;i++){
for(j=0;j<4;j++){
scanf("%d",(*(arr+i)+j));
}
}
printf("-------DISPLAYING ARRAY ELEMENTS---------\n");
for(i=0;i<3;i++){
for(j=0;j<4;j++){
printf("%d\t",*(*(arr+i)+j));
}
printf("\n");
}
return 0;
}
Function pointer
#include <stdio.h>
int sum(int,int);
int (*fp)(int,int);
int main()
{
Pointers in c

int a,b;
printf("Input the two values : ");
scanf("%d%d",&a,&b);
fp = sum;
printf("Addition of two numbers using ordinary function is %d\n",sum(a,b));
printf("Addition of two numbers using function pointer is %d\n",fp(a,b));
return 0;
}
int sum(int a,int b){
return a+b;
}
Function returning a pointer
#include <stdio.h>
char* func(char []);
int main()
{
char str[]="Hello world";
char *x;
x=func(str);
printf("String is %s\n",x);
return 0;
}
char* func(char str[]){
*(str+5)='\0';
return str;
}
Working with strings in pointers
#include <stdio.h>

int main()
{
char *str1="Welcome to c tutorials";
char *str2;
int len;
str2 = str1;
while(*str1!='\0'){
printf("%c",*str1);
str1++;
}
len = str1-str2;
printf("Length of the string is %d\n",len);
return 0;
}
Fucntion returning integers
#include <stdio.h>
Pointers in c

int* func(int,int,int *);


int main()
{
int a,b,c,*d;
printf("Input the two values : ");
scanf("%d%d",&a,&b);
d=func(a,b,&c);
printf("d = %d\n",*d);
return 0;
}
int* func(int a,int b,int *c){
*c = a+b;
return c;
}
How to work with pointer
#include <stdio.h>

int main()
{
char str[]="Hello world";
char *ptr;
ptr=str;
printf("%c\n",*&*&*&*ptr);
return 0;
}
#include <stdio.h>

int main()
{
int arr[]={1,2,3};
int (*ip)[3];
ip = arr;
printf("%d\n",(*ip)[1]);
return 0;
}
#include <stdio.h>
void change(int []);
int main()
{
int arr[]={1,2,3,4,5};
change(arr);
printf("%d\t%d\n",*arr,arr[0]);
return 0;
}
void change(int arr[]){
Arrays in C

arr[0]=10;
}
#include <stdio.h>

int main()
{
int arr[]={10,20,30,40,50,60};
int i = (arr+1)[3];
printf("i = %d\n",i);
return 0;
}
#include <stdio.h>
char *func(char []);
int main()
{
char str[]="Hello world";
char *x;
x=func(str);
printf("%s\n",x);
return 0;
}
char* func(char str[]){
*(str+5)='\0';
return str;
}

Dynamic memory allocation


Memory will be allocated at run time previous what ever we saw with arrays are static
allocation or compile time allocation where size of array is fixed at compile time itself
Here memory will be allocated at run time
For this we use header file called stdlib.h
And it contains function for memory allocation

-malloc() Malloc allocates required amount of memory and returns starting address as
void pointer which can be casted to any of the data type and if memory
allocation fails it returns null and here default memory is initialized with
garbage value
-calloc() Calloc allocates required amount of memory and returns starting address as
void pointer which can be casted to any of the data type and if allocation fails
returns null and in this case memory is initialized with zeros
-realloc() Increases or decreases the size of already allocated memory
-free() Once our work is over we will release the memory to operating system for
further use using free

Malloc takes one argument and it is initialized with garbage value

147
Dynamic memory allocation in c

Calloc takes two arguments and allocates memory in chunks and it is initialized with zeros
for structures and other data types we can go for calloc
Where this memory will be allocated
Dynamic memory allocation in c

Example 1: give noe as -1 and check for values of malloc and calloc
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *ptr,noe,i;
printf("Input the number of elements : ");
scanf("%d",&noe);
ptr=(int *)calloc(noe,sizeof(int));
if(ptr==NULL){
printf("Unable to allocate memory\n");
exit(0);
}
for(i=0;i<noe;i++){
printf("%d\t",*(ptr+i));
}
return 0;
}
Example 2: how to allocate memory dynamically and find the sum and average of elements
of an array

#include <stdio.h>

int main()
{
int *ptr,noe,i,sum=0;
float avg;
printf("Input the number of elements : ");
Dynamic memory allocation in c

scanf("%d",&noe);
ptr=(int *)malloc(noe*sizeof(int));
if(ptr==NULL){
printf("Unable to allocate memory\n");
exit(0);
}
printf("Input the %d elements of array : ",noe);
for(i=0;i<noe;i++){
scanf("%d",ptr+i);
}
printf("----------DISPLAYING ARRAY ELEMENTS------------\n");
for(i=0;i<noe;i++){
printf("%d\t",*(ptr+i));
}
for(i=0;i<noe;i++){
sum+=*(ptr+i);
}
avg = (float)sum/noe;
printf("Sum = %d\tAverage = %.2f\n",sum,avg);
return 0;
}
Example 3: Allocate memory dynamically and find the largest and smallest element in an
array
#include <stdio.h>

int main()
{
int *ptr,noe,i,le,se;
printf("Input the number of elements of an array : ");
scanf("%d",&noe);
ptr=(int *)calloc(noe,sizeof(int));
if(ptr==NULL){
printf("Unable to allocate memory\n");
exit(0);
}
printf("Input the %d elements of the array : ",noe);
for(i=0;i<noe;i++){
scanf("%d",ptr+i);
}
le=*(ptr+0);
se=*(ptr+0);
for(i=0;i<noe;i++){
if(*(ptr+i)>le){le=*(ptr+i);}
if(*(ptr+i)<se){se=*(ptr+i);}
}
Dynamic memory allocation in c

printf("Largest element = %d\nSmallest element = %d\n",le,se);


return 0;
}
Example 4: how to allocate memory for structured data

#include <stdio.h>
typedef struct Employee{
char name[50];
int id;
float sal;
}Emp;
int main()
{
Emp *e1;
int nor,i;
printf("Input the number of employee records : ");
scanf("%d",&nor);
e1=(Emp *)calloc(nor,sizeof(Emp));
if(e1==NULL){
printf("Unable to allocate memory\n");
exit(0);
}
for(i=0;i<nor;i++){
printf("Input Empoyee %d name,id and salary : ",(i+1));
scanf("%s%d%f",(e1+i)->name,&(e1+i)->id,&(e1+i)->sal);
}
printf("\n-----------DISPLAYING EMPLOYEE RECORD-----------\n");
for(i=0;i<nor;i++){
printf("Employee %d Record\n",(i+1));
printf("Employee Name : %s\n",(e1+i)->name);
printf("Employee Id : %d\n",(e1+i)->id);
printf("Employee Salary : %.2f\n",(e1+i)->sal);
}
return 0;
}
Exmaple 5: how to use realloc
#include <stdio.h>

int main()
{
int *ptr1,*ptr2,i;
ptr1 = (int *)malloc(2*sizeof(int));
*(ptr1+0)=10;
*(ptr1+1)=20;
ptr2 = (int *)realloc(ptr1,5*sizeof(int));
Dynamic memory allocation in c

*(ptr2+2)=30;
*(ptr2+3)=40;
*(ptr2+4)=50;
printf("----------DISPLAYING ARRAY ELEMENTS----------\n");
for(i=0;i<5;i++){
printf("%d\t",*(ptr2+i));
}
free(ptr2);
return 0;
}
Example 6: Linked List data structure

#include <stdio.h>
typedef struct Node{
int data;
struct Node *next;
}Nod;
void printNode(Nod *);
void push(Nod **head_ref,int new_data);
int main()
{
Nod *head,*first,*second,*third;
head = (Nod *)malloc(sizeof(Nod));
first = (Nod *)malloc(sizeof(Nod));
second = (Nod *)malloc(sizeof(Nod));
third = (Nod *)malloc(sizeof(Nod));
head->data=10;
first->data=20;
second->data=30;
third->data=40;
head->next=first;
first->next=second;
second->next=third;
third->next=NULL;
printNode(head);
push(&head,5);
printf("\n");
printNode(head);
return 0;
}
void printNode(Nod *head){
while(head!=NULL){
printf("%d\t",head->data);
head=head->next;
}
Dynamic memory allocation in c

}
void push(Nod **head_ref,int new_data){
Nod *new_node=(Nod *)malloc(sizeof(Nod));
new_node->data=new_data;
new_node->next = (*head_ref);
(*head_ref)=new_node;
}

Graphics programming
Here we use the header file graphics.h and use its built in function for graphics programming
What ever we did till now are text based programming so for graphics we have to change
the mode from text mode to graphics mode
Text mode screen will 80*25 where we use stdio.h
We change to graphics mode here we will have 640*480 pixels and we use graphics.h
How to change the mode there is a function called initgraph(&gd,&gm,”c:\\truboc3”)

0,0 640,0

0,480
#include <graphics.h>

#include <conio.h>

#include <dos.h>

#include <stdlib.h>

void main()

int i,rad=10,gd=DETECT,gm;

clrscr();

initgraph(&gd,&gm,"c:\\turboc3\\bgi");

setcolor(11);

line(0,0,640,480);
Graphics in c

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

setbkcolor(random(16));

setcolor(random(16));

circle(320,240,rad);

sound(random(1600));

delay(500);

rad+=5;

nosound();

setcolor(14);

line(640,0,0,480);

rectangle(400,400,200,200);

ellipse(320,240,0,45,100,50);

line(300,100,300,500);

line(300,500,400,400);

line(300,100,400,400);

getch();

Command line arguments

Example 1:

#include <stdio.h>

#include <stdlib.h>

int main(int argc,char *argv[])

int i;

float sum=0;

printf("%s\n",argv[0]);
Command line arguments in c

printf("Number of arguments is %d\n",argc); for(i=1;i<argc;i++){

sum+=atof(argv[i]);

printf("Sum = %.2f\n",sum);

return 0;

Example 2:

#include <stdio.h>

#include <stdlib.h>

int main(int argc,char *argv[])

int i,fact=1,num;

num = atoi(argv[1]);

while(num>=1){

fact *= num;

num--;

printf("Factorial is %d\n",fact);

return 0;

We are going to see assert.h header file it contains one function called assert() this will assert us
when ever the condition fails

#include <stdio.h>

#include <assert.h>

int main(int argc,char *argv[])

int num;

printf("Input a nummber : ");


Excercise in c

scanf("%d",&num);

assert(num>=0);

printf("Number is %d\n",num);

return 0;

File Handling
File is permanent storage on the disk even if u exit the application the data stored in file is
permanent and u can see the data so we go for file handling

There are two types of file 1) text file 2) binary file

For this no special header file we use stdio.h and its built in function

For working with file there is a special data structure which has to be used FILE

FILE *fp;

->fopen() It opens the file in the mode given if file exits it will open if it does not exist it can
create the file
->fclose() Closes the opened file and makes it ready for usage
->getc() It reads character by character from file
->putc() Writes character by character into file
->fprintf() Writes data into file in formatted manner
-fscanf() Reads data from file in formatted manner
->fread() Used for binary file to read it
->fwrite() Used for binary file to write into it
->rewind() Takes the cursor to the beginning of the file
->ftell() Tells the current position of the cursor
->fseek() Places the cursor at desired position

->fopen(const char *filename,const char *mode)

->fp = fopen(“c:\\turboc3\\arun\\text.txt”,”w”);

What are the modes to work with file

->w If file exits it open the file and erases the content and writes new content
If file does not exist it will create the file for us
->r It opens the file and returns the starting address here we cannot write any data
If it does not exist it will return null
->a It will open the file in append mode ie we can add contents to already exisiting
data
->w+
->r+
->a+
Arrays in C

->wb These are for binary files


->rb
->ab
->wb+
->rb+
->ab+

There is macro called EOF which can be used to read the file this is a special character where we can
use ctrl+z to mark end of file

How to read and write character by character into the file

Example 1:

#include <stdio.h>

int main()

FILE *fp;

char ch;

fp = fopen("D:\\file\\test.txt","a");

if(fp==NULL){

printf("Unable to open the file\n");

exit(0);

printf("Enter some data....");

while((ch=getchar())!=EOF){

putc(ch,fp);

fclose(fp);

fp = fopen("D:\\file\\test.txt","r");

while((ch=getc(fp))!=EOF){

printf("%c",ch);

157
Excercise in c

fclose(fp);

return 0;

How to read and write formatted data

#include <stdio.h>

int main()

char name[50],name1[50];

int id,id1;

FILE *fp;

fp = fopen("D:\\file\\person.txt","w");

if(fp==NULL){

printf("Unable to open the file\n");

exit(0);

printf("Input the name and id of the person : ");

scanf("%s%d",name,&id);

fprintf(fp,"%s\t%d",name,id);

fclose(fp);

fp = fopen("D:\\file\\person.txt","r");

fscanf(fp,"%s\t%d",name1,&id1);

printf("Name of the person : %s\n",name1);

printf("Id of the person : %d\n",id1);

return 0;

How to read and write into binary file

#include<stdio.h>
Excercise in c

int main()

int arr[]={10,20,30,40,50};

int i,arr1[5];

FILE *fp;

fp = fopen("D:\\file\\sample.bin","w");

if(fp==NULL){

printf("Unable to open the file\n");

exit(0);

fwrite(&arr,sizeof(arr),1,fp);

fclose(fp);

fp = fopen("D:\\file\\sample.bin","r");

fread(&arr1,sizeof(arr1),1,fp);

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

printf("%d\t",i[arr1]);

return 0;

How to use rewind ftell and fseek

#include <stdio.h>

int main()

FILE *fp;

int size;

fp = fopen("D:\\file\\test.txt","r");

if(fp==NULL){
Excercise in c

printf("Unable to open the file\n");

exit(0);

fseek(fp,0,SEEK_END);

size = ftell(fp);

printf("Size of the file is %d bytes\n",size);

rewind(fp);

size = ftell(fp);

printf("Cursor is at %d position\n",size);

return 0;

How to write structured data into file

#include <stdio.h>

#include <string.h>

typedef struct Employee{

char name[50];

int id;

float sal;

}Emp;

void write();

void read();

void serachById();

Emp e1,e2;

FILE *fp;

int main()

int choice;
Excercise in c

do{

printf("\n\t1.Press 1 to write employee record");

printf("\n\t2.Press 2 to read employee record");

printf("\n\t3.Press 3 to search employee record by id");

printf("\n\t4.Press 4 to search employee record by name");

printf("\n\t5.Press 0 to exit the application");

printf("\nSelect your choice");

scanf("%d",&choice);

switch(choice){

case 1:

write();

break;

case 2:

read();

break;

case 3:

searchById();

break;

case 4:

searchByName();

break;

}while(choice!=0);

return 0;

void write()

{
Excercise in c

fp = fopen("D:\\file\\Employee.dat","ab");

if(fp==NULL){

printf("Unable to open the file\n");

exit(0);

printf("Input the employee name,id and sal : ");

scanf("%s%d%f",e1.name,&e1.id,&e1.sal);

fwrite(&e1,sizeof(e1),1,fp);

fclose(fp);

void read()

fp = fopen("D:\\file\\Employee.dat","rb");

while((fread(&e2,sizeof(e2),1,fp))==1){

printf("Name of the Employee : %s\n",e2.name);

printf("Id of the Employee : %d\n",e2.id);

printf("Salary of the Employee : %.2f\n",e2.sal);

void searchById()

int id;

printf("Input the employee id to display : ");

scanf("%d",&id);

fp = fopen("D:\\file\\Employee.dat","rb");

while((fread(&e2,sizeof(e2),1,fp))==1){

if(id==e2.id){
Excercise in c

printf("Name of the Employee : %s\n",e2.name);

printf("Id of the Employee : %d\n",e2.id);

printf("Salary of the Employee : %.2f\n",e2.sal);

void searchByName()

char name[50];

printf("Input the employee name to display : ");

scanf("%s",name);

fp = fopen("D:\\file\\Employee.dat","rb");

while((fread(&e2,sizeof(e2),1,fp))==1){

if(strcmp(name,e2.name)==0){

printf("Name of the Employee : %s\n",e2.name);

printf("Id of the Employee : %d\n",e2.id);

printf("Salary of the Employee : %.2f\n",e2.sal);

Now input is 12345 output should be 12354


Excercise in c

Application in c

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

#define QUESTIONS 50

#define RESULT 10

int main()

FILE *fprq,*fpra,*fpw;

char str[QUESTIONS][RESULT];

int i,j=0;

char ch,ans,c,val;

static int res=0;

fprq = fopen("..//ques.txt","r");

if(fprq==NULL){

printf("Unable to open the file\n");

exit(0);

while((ch=getc(fprq))!= EOF){

//putc(ch,fpw);

printf("%c",ch);

if(ch=='@'){

ch=getc(fprq);

fflush(stdin);

printf("\nInput the answer : ");

scanf("%c",&ans);

if(ch==ans){res++;strcpy(str[j],"correct");j++;}
Excercise in c

else{strcpy(str[j],"wrong");j++;printf("Correct Answer : %c\n",ch);}

printf("Result is %d\n",res);

fflush(stdin);

printf("Do want valuation (y/n) : ");

scanf("%c",&val);

if(val=='y'){

for(i=0;i<=j;i++){

printf("%d) %s\n",i,str[i]);

fclose(fprq);

return 0;

}
Excercise in c

What is the output of this C code?

    int main()
    {
        int i = -5;
        int k = i %4;//-5%4->-1
        printf("%d\n", k);
    }

 A. Compile time error

 B. -1

 C. 1

 D. None

2.
What is the output of this C code?

    int main()
    {
        int i = 5;
        int l = i / -4; // 5/-4->-1
        int k = i % -4; // 5%-4->1
        printf("%d %d\n", l, k);
        return 0;
    }

 A. Compile time error

 B. -1  1

 C. 1  -1

 D. Run time error

3. What is the output of this C code?

    int main()
    {
        int i = 7;
        i = i / 4;//7/4->1
        printf("%d\n", i);
       return 0;
    }

 A. Run time error

 B. 1
Excercise in c

 C. 3

 D. Compile time error

4. What is the value of x in this C code?

    void main()
    {
        int x = 4 *5 / 2 + 9;//x = 20/2+9->10+9->19
    }

 A. 6.75

 B. 1.85

 C. 19

 D. 3

5. What is the output of this C code?

    void main()
    {
        int x = 4.3 % 2;
        printf("Value of x is %d", x);
    }

 A. Value of x is 1.3

 B. Value of x is 2

 C. Value of x is 0.3

 D. Compile time error

6.
What is the output of this C code?

    void main()
    {
        int y = 3;
        int x = 7 % 4 * 3 / 2;//3*3/2->9/2->4
        printf("Value of x is %d", x);
    }

 A. Value of x is 1

 B. Value of x is 2

 C. Value of x is 4
Arrays in C

 D. Compile time error

168
Excercise in c

8. The precedence of arithmetic operators is (from highest to lowest)?

 A. %, *, /, +, -

 B. %, +, /, *, -

 C. +, -, %, *, /

 D. %, +, -, *, /

9. Which of the following is not an arithmetic operation?

 A. a *= 20;

 B. a /= 30;

 C. a %= 40;

 D. a != 50;

10. Which of the following data type will throw an error on modulus operation(%)?

 A. char

 B. short

 C. float

 D. int

11. What is the output of this C code?

    int main()
    {
        int a = 20;
        double b = 15.6;
        int c;
        c = a + b;
        printf("%d", c);
    }

 A. 35(c)

 B. 36

 C. 35.6

 D. 30

12. What is the output of this C code?

    int main()
    {
        int a = 20, b = 15, c = 5;
Arrays in C

        int d;
        d = a == (b + c);

170
Excercise in c

        printf("%d", d);


    }

 A. 1

 B. 40

 C. 10

 D. 5

13.
What is the output of this C code?

    void main()
    {
        int x = 0;
        if (x = 0)
            printf("Its zero\n");
        else
            printf("Its not zero\n");
    }

 A. Its not zero(C)

 B. Its zero

 C. Run time error

 D. None

14. What is the output of this C code?

    void main()
    {
        int k = 8;
        int x = 0 == 1 && k++;
        printf("%d%d\n", x, k);
    }

 A. 0   9

 B. 0   8(c)

 C. 1   9

 D. 1   8

15. What is the output of this C code?


Arrays in C

    void main()
    {

172
Excercise in c

        char a = 'a';
        int x = (a % 10)++;
        printf("%d\n", x);
    }

 A. 6

 B. Junk value

 C. Compile time error(c)

 D. 7

16. What is the output of this C code?

    void main()

    {
        1 < 2 ? return 1: return 2;
    }

 A. returns 1

 B. returns 2

 C. varies

 D. Compile time error(c)

19. What is the output of this C code?

    int main()
    {
        int x = 2, y = 2;
        x /= x / y;
        printf("%d\n", x);
        return 0;
    }

 A. 2(c)

 B. 1

 C. 0.5

 D. Undefined behaviour

21. What is the type of the below assignment expression if x is of type float, y is of type
int?
        y = x + y;

 A. Int(c)

 B. float
Excercise in c

 C. There is no type for an assignment expression

 D. double

22. What is the value of the below assignment expression


      (x = foo())!= 1 considering foo() returns 2

 A. 2

 B. true

 C. 1(c)

 D. 0

24. for c = 2, value of c after c <<= 1;

 A. c = 1;

 B. c = 2;

 C. c = 3;

 D. c = 4;(c)filed

25. What is the output of this C code?

    int main()
    {
        int a = 1, b = 2;
        a += b -= a;
        printf("%d %d", a, b);
    }

 A. 1   1

 B. 1   2

 C. 2   1

 D. 2   2

26.
What is the output of this C code?

    int main()
    {
        int a = 4, n, i, result = 0;
        scanf("%d", &n);
        for (i = 0;i < n; i++)
Arrays in C

        result += a;
    }

175
Excercise in c

 A. Addition of a and n.

 B. Subtraction of a and n.

 C. Multiplication of a and n.(c)

 D. Division of a and n.

27. Which of the following is an invalid assignment operator?

 A. a %= 10;

 B. a /= 10;

 C. a |= 10;

 D. None of the mentioned(c)

28. What is the output of this C code?

    int main()
    {
        int c = 2 ^ 3;
        printf("%d\n", c);
    }

 A. 1

 B. 8

 C. 9

 D. 0

29. What is the output of this C code?

    int main()
    {
        unsigned int a = 10;
        a = ~a;
        printf("%d\n", a);
    }

 A. -9

 B. -10

 C. -11

 D. 10

31. What is the output of this C code?


Arrays in C

    int main()
    {

177
Excercise in c

        int a = 2;
        if (a >> 1)
           printf("%d\n", a);
    }

 A. 0

 B. 1

 C. 2

 D. No output

32. Comment on the output of this C code?

    int main()
    {
        int i, n, a = 4;
        scanf("%d", &n);
        for (i = 0; i < n; i++)
            a = a * 2;
    }

 A. Logical Shift left

 B. No output(c)

 C. Arithmetic Shift right

 D. bitwise exclusive OR

33. What is the output of this C code?

    void main()
    {
        int x = 97;
        int y = sizeof(x++);
        printf("x is %d", x);
    }

 A. x is 97(c)

 B. x is 98

 C. x is 99

 D. Run time error

34.
What is the output of this C code?

    void main()
Arrays in C

    {
        int x = 4, y, z;

179
Excercise in c

        y = --x;//3
        z = x--;//3 2
        printf("%d%d%d", x, y, z);
    }

 A. 3  2  3

 B. 2  2  3

 C. 3  2  2

 D. 2  3  3(c)

35. What is the output of this C code?

    void main()
    {
        int x = 4;
        int *p = &x;
        int *k = p++;
        int r = p - k;
        printf("%d", r);
    }

 A. 4

 B. 8

 C. 1(c)

 D. Run time error

36. What is the output of this C code?

    void main()
    {
        int a = 5, b = -7, c = 0, d;
        d = ++a && ++b || ++c;
        printf("\n%d%d%d%d", a, b, c, d);
    }

 A. 6  -6  0  0

 B. 6  -5  0  1

 C. -6  -6  0  1

 D. 6  -6  0  1@c

37. What is the output of this C code?

    void main()
Arrays in C

    {
        int a = -5;

181
Excercise in c

        int k = (a++, ++a); -5,-3


        printf("%d\n", k);
    }

 A. -3(c)

 B. -5

 C. 4

 D. Undefined

38. What is the output of this C code?

    int main()
    {
        int x = 2;
        x = x << 1;
        printf("%d\n", x);
    }

 A. 4(c)

 B. 1

 C. Depends on the compiler

 D. Depends on the endianness of the machine

9. What is the output of this C code?

    int main()
    {
        int x = -2;
        x = x >> 1;
        printf("%d\n", x);
    }

 A. 1

 B. -1(c)

 C. 2 ^ 31 – 1 considering int to be 4 bytes

 D. Either (b) or (c)

40. What is the output of this C code?

    int main()
    {
        if (~0 == 1)
            printf("yes\n");
        else
            printf("no\n");
    }
Excercise in c

 A. Yes

 B. No(c)

 C. Compile time error

 D. Undefined

41. What is the output of this C code?

    int main()
    {
        int x = -2;
        if (!0 == 1)
            printf("yes\n");
        else
            printf("no\n");
    }

 A. Yes

 B. No

 C. Run time error

 D. Undefined

42. What is the output of this C code?

    int main()
    {
        int y = 0;
        if (1 |(y = 1))
            printf("y is %d\n", y);
        else
            printf("%d\n", y);
 
    }

 A. 1

 B. 0

 C. Run time error

 D. Y is 1(c)

#include <stdio.h>

int main()

{
Excercise in c

int y = 1;

if(y & (y=2))printf("true %d\n",y);

else printf("false %d\n",y);

return 0;

 A. true 2(c)

 B. false 2

 C. Either option a or option b

 D. true 1

45. What is the output of this C code?

    int main()
    {
        int a = 1, b = 1, c;
        c = a++ + b;//1 + 1 =2 a=2
        printf("%d, %d", a, b);
    }

 A. a = 1, b = 1

 B. a = 2, b = 1

 C. a = 1, b = 2

 D. a = 2, b = 2

46. What is the output of this C code?

    int main()
    {
        int a = 1, b = 1, d = 1;
        printf("%d, %d, %d", ++a + ++a+a++, a++ + ++b, ++d + d++ + a++);
    }

 A. 15, 4, 5(c)

 B. 9, 6, 9

 C. 9, 3, 5

 D. 6, 4, 6

48.
Arrays in C

What is the output of this C code?

    int main()

185
Excercise in c

    {
        int a = 10, b = 10;
        if (a = 5)
        b--;
        printf("%d, %d", a, b--);
    }

 A. a = 10, b = 9

 B. a = 10, b = 8

 C. a = 5, b = 9(c)

 D. a = 5, b = 8

49. What is the output of this C code?

    int main()
    {
        int i = 0;
        int j = i++ + i;
        printf("%d\n", j);
    }

 A. 0

 B. 1(c)

 C. 2

 D. Compile time error

50. What is the output of this C code?

    int main()
    {
        int i = 2;
        int j = ++i + i;
        printf("%d\n", j);
    }

 A. 6(c)

 B. 5

 C. 4

 D. Compile time error


Arrays in C

1) find whether a number is perfect number or not?

2) Write a program in C to calculate the sum of the series (1*1) + (2*2) + (3*3) + (4*4) +
(5*5) + ... + (n*n).

3) Write a program in C to print a square pattern with # character

####

####

####

####

4) Write a program in C to display the cube of the number upto given an integer

5) Write a program in C to display the n terms of odd natural number and their sum.

6) Write a program in C to display the n terms of even natural number and their sum.

7) Write a program in C to find the sum of the series 1 +11 + 111 + 1111 + .. n terms.

8) Write a program in C to find the number and sum of all integer between 100 and 200
which are divisible by 9

9) Write a program in C to display the pattern like right angle triangle with number.

12

123

1234

12345

10) Write a program in C to make such a pattern like a pyramid with numbers increased
by 1.

23

456

7 8 9 10

ARRAYS

11) Write a program in C to read n number of values in an array and display it in reverse
order.

187
Arrays in C

12) Write a program in C to count a total number of duplicate elements in an array

13) Write a program in C to print all unique elements in an array.

14) Write a program in C to find the maximum and minimum element in an array.

15) Write a program in C to calculate determinant of a 3 x 3 matrix.

16) Write a program in C to accept two matrices and check whether they are equal.

17) Write a program in C to find the missing number from a given array. There are no
duplicates in list.

18) Write a program in C to rearrange an array such that even index elements are
smaller and odd index elements are greater than their next.

Expected Output:

The array given is:

642183

The new array after rearranging:

461823

19) Write a program in C to update every array element with multiplication of previous
and next numbers in array.

Expected Output:

The given array is:

123456

The new array is:

2 3 8 15 24 30

20) Write a program in C to rearrange positive and negative numbers alternatively in a


given array

Strings

21) Write a C program to sort a string array in ascending order.

22) Write a program in C to read a string through keyboard and sort it using bubble sort.

23) Write a program in C to split string by space into words.

24) Write a C programming to convert vowels into upper case character in a given string.

188
Arrays in C

Checking whether date is valid by reading from file and if valid stroing in another file

#include <stdio.h>

#include <stdlib.h>

int main()

FILE *fp1,*fp2;

int dd,mm,yy,i=0,j=0,k=0,flag=1;

char ch,date[11],num[4][10];

fp1 = fopen("D:\\arun\\file\\arun.txt","r");

fp2 = fopen("D:\\arun\\file\\wrarun.txt","a");

if(fp1==NULL){

printf("Unable to open the file\n");

exit(0);

printf("Successfully opened the file\n");

while((ch=getc(fp1))!=EOF){

if(ch=='\n'||ch=='-'){num[j][k]='\0';j++;k=0;}

else{num[j][k]=ch;k++;}

if(j==3){

dd = atoi(num[0]);

mm = atoi(num[1]);

yy = atoi(num[2]);

if(yy>=1900 && yy<=9999)

//check month

if(mm>=1 && mm<=12)

//check days

189
Arrays in C

if((dd>=1 && dd<=31) && (mm==1 || mm==3 || mm==5 || mm==7 || mm==8 ||


mm==10 || mm==12))

flag=1;

else if((dd>=1 && dd<=30) && (mm==4 || mm==6 || mm==9 || mm==11))

flag=1;

else if((dd>=1 && dd<=28) && (mm==2))

flag=1;

else if(dd==29 && mm==2 && (yy%400==0 ||(yy%4==0 && yy%100!=0)))

flag=1;

else

flag=0;

else

flag=0;

else

flag=0;

if(flag==1){fprintf(fp2,"%d-%d-%d\n",dd,mm,yy);}

j=0;k=0;

fclose(fp1);

fclose(fp2);

return 0;

190
Arrays in C

Creating a quiz application in c

/*#include <stdio.h>

#include <stdlib.h>

#include <string.h>

#define QUESTIONS 50

#define RESULT 10

int main()

FILE *fprq,*fpra,*fpw;

char str[QUESTIONS][RESULT];

int i,j=0;

char ch,ans,c,val;

static int res=0;

fprq = fopen("..//ques.txt","r");

if(fprq==NULL){

printf("Unable to open the file\n");

exit(0);

while((ch=getc(fprq))!= EOF){

//putc(ch,fpw);

printf("%c",ch);

if(ch=='@'){

ch=getc(fprq);

fflush(stdin);

printf("\nInput the answer : ");

scanf("%c",&ans);

if(ch==ans){res++;strcpy(str[j],"correct");j++;}

else{strcpy(str[j],"wrong");j++;printf("Correct Answer : %c\n",ch);}

191
Arrays in C

printf("Result is %d\n",res);

fflush(stdin);

printf("Do want valuation (y/n) : ");

scanf("%c",&val);

if(val=='y'){

for(i=0;i<=j;i++){

printf("%d) %s\n",i,str[i]);

fclose(fprq);

return 0;

192

You might also like