0% found this document useful (0 votes)
727 views138 pages

C Programming

C is a procedural programming language developed in the early 1970s. It has since become a popular and widely used language. Key features of C include being procedural, having built-in data types and functions, and being portable and extensible. C code is typically structured with sections for documentation, definitions, declarations, and subroutines. Decision making in C can be done through if/else statements, switch cases, and relational operators.

Uploaded by

arunkumar_a8131
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
727 views138 pages

C Programming

C is a procedural programming language developed in the early 1970s. It has since become a popular and widely used language. Key features of C include being procedural, having built-in data types and functions, and being portable and extensible. C code is typically structured with sections for documentation, definitions, declarations, and subroutines. Decision making in C can be done through if/else statements, switch cases, and relational operators.

Uploaded by

arunkumar_a8131
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/ 138

C Programming

C was not the first programming language

Before this we had

ALGOL

BCPL

C-Kernihen and Ritchie 1970

K&Rc

ANSI C

C99

mainly for your Unix operating system

this is used widely in networking applications

Types of Programming language

Assembly level programming language - Instructions in the form mnemonics Mov A,B

ADD B-opcode

Low Level Programming language-Writing directly in the machine language

High level programming language - C,C++,Java etc

Translators ---> Compiler-based

We convert the code into intermediate code

in C language we call it as objective code

In java we call it as byte code

objective code ---> Linker ---> executable code-->loader-->memory-->execution starts

Faster in execution
If there are any errors that will be indicated only at the end

Interpretor-Based - Python and LISP

Line by Line execution happens

Writing an Interpretor is easy

Slower in execution

feature of C Programming

C is procedural oriented or structured oriented programming language

C is also genreal purpose progamming language

C is rich in built in data types

c is rich in built in functions

c follows top down approach

c is also middle level programming language

c is extensible

c is portable

Structure of the C Programming

Documentation section

Link Section

Definition

Global declaration

main()

declaration section

execution section
}

Subroutines

Definition

Documenation section

This contains what is called as comments

//single line comment

/* multi

line

Comments*/

These comments are usually ignore by the compiler

These are meant only for program readability

These will not occupy any space in memory

Link section

#include<header file> predefined functions or built in functions or library functions

Definition

#define preprocessor directives

Symbolic constants

int i;

main()

int j;//declaration

clrscr();

subroutines

Turbo c/C++ compiler


Dev c/c++

Borland C/C++

Code blocks

void main()

int main()

return 0;

void main(void)

command line arguments

#include<stdio.h>

int main()

printf("Hello world!");

return 0;

C programming

Keywords - only 32 keywords in c Programming it is simple and easy to learn

These keywords are reserved words meant specific for your c Programming

These words cannot be used for anyother purpose

all keywords will be in lower case only

identifiers

names given to functions variables or anything we call it as identifiers


Rules which should be followed while naming an identifer

1) it should start with letters either lowercase or uppercase it cannot start with numbers

2) it accepts alphanumeric i.e you can have numbers but only thing it should not start with numbers

3) special character such as underscore (_) is allowed

4) only first 32 characters are identified

5) No keywords are to be used as identifiers

6) _int this is also not allowed

Variables

Variables are nothing but named memory locations

naming for variable u have to follow the rules of identifiers

values that can change

123age not allowed

age123 allowed

account number not allowed

accountnumber allowed

C is case sensitive programming language

Name and name are considered different variables

meanigful names should be given to variables

constants

int a=5;

const keyword

printf funciton

Here we format the strings

Format specifier

%d - integer
%f - float

%c - character

%s - String

%u - pointer address

%x - hexadecimal values

%o - octal values

%p - pointers

Escape sequences or backslash characters

Which is written using \

\n - new line

\r - carriage return

\b - backspace

\t - tab space

\a - alert sound (bell sound)

\v - horizontal tab

\' - single quotes

Global variable - Anything that is declared outside all functions we call it as global variable

local variable - Anything that is declared within a block or within a function we call it as local variable

if global variable and local variable has the same name then local variable will precede over the

global variable

scope of variable

global variable till the program ends

local variable local to the functions

how to get input from the user

for this we have a function called scanf


scanf("Format",addres of the variable)

int i;//declaration

i=5;//initialization 50.64654545555thnt

Operators in c programming

binary operator -> it works on two operands ex: a*b

unary operator -> it works with only one operand ex: a++ = incrementing the value of a

classification of operator

1) Arithmetic operator -> * / % ()->it will be performed first

-> + -

-> = associativity association is from left to right

z= ((a*b)+(c/d))-5

2) Relational operator -> >,<,>=,<=,==,!=

3) Logical operator -> &&,||,! And,Or and not

4) Bitwise operator -> &,|,^,>>,<<,~ and,or,ex-or,rightshift,leftshift,negate

5) Increment/Decrement operator -> a++ postfix or ++a prefix a-- --a

6) Conditional operator-> ?: Ternary operator

7) Assignment operator -> +=,-=,*=,/=

8) Special operator -> * & -> sizeof

Different data types in c programming language

1) int - 2 bytes -32768 to +32767 1 byte -8 bit 2 byte -16bit 0-lsb 15-msb -2^15 to 2^15-1

2) char - 1 bytes - ASCII -Americal standard code for information interchage A-65 a-97 -2^7 to 2^7-1

-128 to +127

3) float - 4 bytes single precision only first 6 decimal points will be identified -2^31 to 2^31-1

4) double - 8 bytes double precision first 15 decimal places will be identified

default is double
float f=0.5f;

Type modifiers

change the size of the datatype

signed

unsigned

long

short

long int - 4 bytes long int i=1200l;

unsigned int - 4bytes allows onlypositive number

unsigned long int - 8 bytes

long double - 12 bytes

Arithmetic operator

Type casting

Implicit casting - > Automatic conversion

Explicit casting -> (float) done by users

2|5(2->quotient (/)

1->remainder (%)

division can be performed on float values

but modulus cannot operate on float values

float x=(float)5/2;

Relational Operator

>,<,>=,<=,==,!=

Are used to check the condition


10>5 -> 1

In c programming anything 0 is considered false and anything other than 0 is considered as true

-5,0.2,5,-14,`12 all are considered as true in c programmming

18<=10 -> 0

8!=3 ->1

"ab"=="ab" this is also not allowed compiler will throw error i cant compare two strings

'a' == 'a' ->1 single character

'a' == 97

single character comparison allowed

int a=0.9

if(a==0.9f)

4>3>2 -> 0 false

associativity will be from left to right

4>3 is performed it returns 1>2 is performed it returns o

while using relational operator for float u should be taking care

f=0.5

f==0.5 it returns true

but in second case

f=0.9

f==0.9 it is returning false here 0.9 is considered as double data type and it compares with

a float

0.5 * 2= 1.0
0.0 * 2= 0.0

0.0 * 2= 0.0

0.0 * 2= 0.0 0.100000000000000=0.10000000

0.9 * 2 =1.8

0.8 * 2 =1.6

0.6 * 2 =1.2

0.2 * 2 =0.4

0.4 * 2 =0.8

0.8 * 2 =1.6

0.6 * 2 =1.2

0.2 * 2 =0.4 0.1110010000 = 0.11100110

Logical operator

&& -> logical and

|| -> logical or

! -> not

A B A&&B A B A||B A !A

00 0 00 0 0 1

01 0 01 1 1 0

10 0 10 1

11 1 11 1

These operators are usually used to combine more than one relational operator

4==4 && 9>3 -> 1

bitwise operator
& | ^ >> << ~

20 & 16

2|20

2|10 - 0

2|5 - 0

2|2 - 1

2|1 - 0

20 -> 0001 0100 i->20 -> 0001 0100

16 -> 0001 0000 j->16 -> 0001 0000

0001 0000 -> 16 i^j 0000 0100 -> i

0001 0100 -> j -> 20

2|16 0001 0000 -> i -> 16

2|8 - 0

2|4 - 0

2|2 - 0

1-0

20>>2 -> 0000 0101 -> 5 right shift dividing the number repeatedly by 2

20<<2 -> equivalent to multiplying by 2 80

~(-4) -> -(n+1) -> -(-4+1) -> 3

~(4) -> -(4+1) = -5

Ternary or conditional operator

?:

a>b?a:b

short circuited operation


Logical and-> if first condition is false then second condition will not be evaluated

Logical or -> if first condition is true then second condition will not be evaluated

Modify operator -> increment and decrement operator

a++ -> postfix

a--

++a -> prefix

--a

steps followed are

1) preincrement or predecrement

2) substitution

3) evluation

4) assignment

5) post increment or post decrement

precedence of operator

*/%

+-

<< >>

< <= > >=

== !=

&

&&

||

?:
+=,-=

comma operator ,

a=20 , b=10

a>b&&(a+2)<b&20

20>10&&(20+2)<10&20

20>10&&22<10&20

1&&22<10&20

1&&0&20

1&&0

Write a program to get total days of a babys age and convert it into years months and days

365|500(

totaldays = 500

arunkumar.a1981@hotmail.com

y=?

m=?

d=?

365|500(1 -> number of years (/)

365

30|135(4 -> number of months (/)

15 -> no of days (%)

Year=500/365

Months=(500%365)/30

Days=(500%365)%30;

char lch='a',lch1='z';
char uch='A',uch1='Z';

char dch='0',dch1='9';

printf("a=%d & z=%d\n",lch,lch1);

printf("A=%d & Z=%d\n",uch,uch1);

printf("0=%d & 9=%d\n",dch,dch1);

Write a program to find the area of a circle

Write a program to convert celcius to farenheat

f=(c*1.8)+32 %c -> 248

write a program to calcualte the area of a triangle

write a program to calculate the area of a rectangle

Decision making statements

1) Simple if
2) If else
3) If else if else if else
4) Nested if
5) Switch case break default

If(condition==true){statements within if will be executed}

If(condition==true){statements within if will be executed}else{statements within else will be executed}

Number%2==0 even

Number%2!=0 odd

#include <stdio.h>

int main()

int num;

printf("enter a number\n");

scanf("%d",&num);
if(num%2==0)

printf("It is an even number\n");

else{

printf("It is an odd number\n");

return 0;

#include <stdio.h>

int main()

char ch;

printf("Enter a character\n");

scanf("%c",&ch);

if(ch==97)

printf("a is a character");

}else{

printf("The ascii value of the character is %d",ch);

}
return 0;

#include <stdio.h>

int main()

int i=5,j=6,k=7;

if(i>j==k){

printf("%d%d%d",i++,++j,--k);

}else{

printf("%d\t%d\t%d\n",i,j,k);

return 0;

#include <stdio.h>

int main()

int i=2;

if(i==(1,2)){

printf("Inside if block");

}else{

printf("Outside if block");

return 0;
}

#include <stdio.h>

int main()

int i=5;

if(i=i-5>4){

printf("Inside if block");

}else{

printf("Outside if block");

return 0;

#include <stdio.h>

int main()

if(sizeof('\0')){

printf("Inside if block");

}else{

printf("Outside if block");

return 0;

Write a program to convert lower case to upper case and upper case to lower case
97-32=65

65+32=97

#include <stdio.h>

int main()

char ch;

printf("Enter a character\n");

scanf("%c",&ch);

if(ch>='a'&& ch<='z'){

ch=ch-32;

}else{

ch=ch+32;

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

return 0;

Write a program to check whether a character is a vowel or not

Vowels = a,e,I,o,u;

#include <stdio.h>

int main()

char ch;

printf("Enter a character\n");
scanf("%c",&ch);

if(ch=='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u'){

printf("It is vowel");

}else{

printf("It is not a vowel");

return 0;

Write a program to get 6 subjects marks of a student and calculate the average and display the division

#include <stdio.h>

int main()

int phy,che,maths,eng,his,lang;

int average;

printf("Enter the physics marks\n");

scanf("%d",&phy);

printf("Enter the chemistry marks\n");

scanf("%d",&che);

printf("Enter the maths marks\n");

scanf("%d",&maths);

printf("Enter the english marks\n");

scanf("%d",&eng);

printf("Enter the history marks\n");

scanf("%d",&his);
printf("Enter the language marks\n");

scanf("%d",&lang);

average=(phy+che+maths+eng+his+lang)/6;

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

if(average>=75&&average<=90){printf("First class with distinction\n");}

else if(average>=60&&average<=74){printf("First class");}

else if(average>=45&&average<=59){printf("Second class");}

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

Write a program to read a persons gender and age and display whether he or she needs to be insured or
not

If age is greater than 30 and gender is male then he needs to be insured

If age is greater than 25 and gender is female she needs to be insured

Else no need insurance

#include <stdio.h>

int main()

int age;

char gender;

printf("Enter the age of the person\n");

scanf("%d",&age);

fflush(stdin);

printf("Enter the gender of the person\n");

scanf("%c",&gender);

if(age>=30&&(gender=='m'||gender=='M')){
printf("He needs to be insured\n");

}else if(age>=25&&(gender=='f'||gender=='F')){

printf("she needs to be insured\n");

}else{

printf("No need insurence\n");

(++i)++ preincrement occurs and it stores the value as rvalue not as lvalue

But postincrement requires lvalue not rvalue in that case compiler is thowing

Error telling lvalue required

Understand that inside sizeof operator none of the expressions are evaluated

#include <stdio.h>

int main()

int i=5,j=10,k=15;

printf("%d",sizeof(k/=i+j));

printf("%d",k);

return 0;

#include <stdio.h>

int main()

{
int y=0;

int x=(~y==1);

printf("%d",x);

return 0;

#include <stdio.h>

int main()

int x=10;

int y=20;

x+=y+=10;

printf("%d%d",x,y);

return 0;

#include <stdio.h>

int main()

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

if(c>b>a)printf("inside if block");

else printf("inside else block");

return 0;

}
#include <stdio.h>

int main()

int x=2,y=5;

(x&y)?printf("true"):printf("false");

(x&&y)?printf("true"):printf("false");

return 0;

Don’t use negative number for shift operation >> << it will give undesired behaviour

#include <stdio.h>

int main()

int x=19;

(x&1)?printf("odd"):printf("even");

return 0;

#include <stdio.h>

int main()

int num1,num2;

printf("Enter the values of two numbers\n");

scanf("%d%d",&num1,&num2);
if(num1==num2)printf("%d is equal to %d\n",num1,num2);

else if(num1>num2)printf("%d is greater than %d\n",num1,num2);

else printf("%d is less than %d\n",num1,num2);

return 0;

Write a program to find whether a triangle is equilateral,isosceles and scalene

#include <stdio.h>

int main()

int sidea,sideb,sidec;

printf("Enter the three sides\n");

scanf("%d%d%d",&sidea,&sideb,&sidec);

if(sidea==sideb&&sidea==sidec)printf("Equilateral traiangle");

else if(sidea==sideb||sidea==sidec||sideb==sidec)printf("Isoceles triangle");

else printf("Scalene triangle");

return 0;

Write a program to get a character as input and find whether it is digit or character of special character

All variables has to be declared before its usage in c program

#include <stdio.h>

int main()

{
char ch;//declaration always at the top in c program

printf("Enter the character\n");

scanf("%c",&ch);

if(ch>=97&&ch<=122)

printf("lower case\n");

}else if(ch>=65&&ch<=90){

printf("Upper case\n");

}else if(ch>=48&&ch<=57){

printf("It is a Digit\n");

}else{

printf("IT is a special character\n");

return 0;

Write a program to get customer number and units consumed & print the amount to be given by the
customer

#include <stdio.h>

int main()

int units,custnum;

float charges;

printf("Enter the customer number\n");


scanf("%d",&custnum);

printf("Enter the units consumed\n");

scanf("%d",&units);

if(units<200)charges=0.5*units;

else if(units<=400)charges=100+0.65*(units-200);

else if(units<=600)charges=200+0.8*(units-400);

else charges=390+(units-600);

printf("\nCustomer number = %d\ncharges=%3.2f\n",custnum,charges);

return 0;

Write a program to find the roots of a quadratic equation

Fist step calculate b^2-4*a*c = d

d==0 then roots are real and equal x1=(-b/2a) x2=-b/(2a)

d>0 then roots are real and different x1=-b+(d)/(2a) x2=-b-d/(2a)

d<0 then roots are complex

#include <stdio.h>

#include<math.h>

int main()

int a,b,c,d;

float x1,x2;

printf("Enter the values of a,b and c\n");

scanf("%d%d%d",&a,&b,&c);
d=b*b-4*a*c;

if(d==0)

printf("The roots are real and equal");

x1=-b/(2*a);

x2=x1;

printf("The first root is x1=%f\n",x1);

printf("The second roots is x2=%f\n",x2);

}else if(d>0){

printf("The roots are real and different\n");

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

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

printf("The first root is x1=%f\n",x1);

printf("The second root is x2=%f\n",x2);

}else{

printf("The roots are imaginary\n");

return 0;

Write a program to get a character and display whether it is character or digit or special character

ctype.h

isalnum(c) – tests whether a character is alphanumeric or not

isalpha(c )- is c a alphabetic

isdigit( c)- checks whether c is a digit


islower( c) – c is of lower case

isupper(c )- c is upper case

#include <stdio.h>

#include<ctype.h>

int main()

char ch;

printf("Enter any type of character\n");

ch=getchar();

if(isalpha(ch)>0)printf("It is a character\n");

else if(isdigit(ch)>0)printf("It is a digit\n");

else printf("It is not alphanumeric character\n");

return 0;

nested if

write a program to get two numbers as input and find whether it is equal or greater or lesser

if(condition==true){

if(condition==true){

#include <stdio.h>

int main()

int num1,num2;
printf("Enter the values of num1 and num2\n");

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

if(num1>=num2){

if(num1==num2){

printf("%d is equal to %d\n",num1,num2);

}else{

printf("%d is greater than %d\n",num1,num2);

}else{

printf("%d is lesser than %d\n",num1,num2);

return 0;

Write a program to find largest of three numbers

#include <stdio.h>

int main()

float a,b,c;

printf("enter the values of a,b and c");

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

if(a>b){

if(a>c){

printf("%f is largest\n",a);

}else{
printf("%f is largest\n",c);

}else{

if(b>c){

printf("%f is largest\n",b);

}else{

printf("%f is largest\n",c);

return 0;

Swtich case

Switch(expression)

Case label1:

Set of statements

Break;

Case label2:

Set of statements

Break;

Case label3:

Set of statements

Break;

Default:
Set of statements

int main()

int x=2;

switch(x){

case 1:

printf("Inside case 1");

break;

case 2:

printf("Inside case 2");

break;

case 3:

printf("Inside case 3");

break;

default:

printf("Enter a value as 2");

return 0;

Rules for switch case

1) Case label must be unique


2) Case label must end with colon
3) Case labels must have constant expression
4) Case label must be of integral type(integer or character)
5) Case should not be floating point number
6) Switch case must have atmost one default label
7) Default label is optional
8) Break statement takes the control out of the switch
9) Break is also optional
10) Two or more cases can share the break
11) Nesting of switch is allowed
12) Relational operators not allowed in switch
13) Macro identifier are allowed in switch case label
14) No variables are allowed in switch case except constant variable
15) Case need not be in order
16) Default need not be the last statement it can come anywhere within switch
17) Between switch and case there should not be any statement if it is there it will be ignored

18) int main()


19) {
20) int x=2;
21) switch(x){
22) case 1:
23) printf("Inside case 1");
24) break;
25) case 2:
26) printf("Inside case 2");
27) break;
28) case 3:
29) printf("Inside case 3");
30) break;
31) default:
32) printf("Enter a value as 2");
33) }
34)
35) return 0;
36) }

#include <stdio.h>

int main()

{
int x=2;

switch(x){

case 1:

printf("Inside case 1");

break;

case 1+1:

printf("Inside case 2");

break;

case 3:

printf("Inside case 3");

default:

printf("Enter a valid number");

return 0;

#include <stdio.h>

int main()

int day;

printf("Enter the day in integer value");

scanf("%d",&day);

switch(day){

case 2:
printf("sunday");

break;

case 1:

printf("Monday");

break;

case 3:

printf("Tuesday");

break;

case 6:

printf("Wednesday");

break;

case 5:

printf("Thursday");

break;

case 4:

printf("Friday");

break;

case 7:

printf("saturday");

break;

default:

printf("Enter values 1-7");

return 0;
}these are the rules for switch case

#include <stdio.h>

#define VAR 3

int main()

int x=3;

switch(x){

case 1:

printf("Inside case 1");

break;

case 2:

printf("Inside case 2");

break;

case VAR:

printf("Inside case 3");

break;

return 0;

#include <stdio.h>

#include <ctype.h>

int main()

char ch;

printf("Enter a character\n");
scanf("%c",&ch);

if(isalpha(ch)){

switch(tolower(ch)){

case 'a':

case 'e':

case 'i':

case 'o':

case 'u':

printf("It is a vowel");

break;

default:

printf("It is a consonant");

}else if(isdigit(ch))printf("IT is a digit");

else printf("It is a special character");

return 0;

Write a program for a user to select a choice the choice will be

1)Area of circle

2)Area of triangle

3)Area of rectangle

#include <stdio.h>

int main()

{
int choice,r,b,h,l,w;

float area;

printf("\n1.Area of Circle");

printf("\n2.Area of Triangle");

printf("\n3.Area of Rectangle");

printf("\nEnter the choice from display");

scanf("%d",&choice);

switch(choice){

case 1:

printf("Enter the radius of the circle\n");

scanf("%d",&r);

area=3.14*r*r;

break;

case 2:

printf("Enter the base and height of the triangle\n");

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

area=0.5*b*h;

break;

case 3:

printf("Enter the length and width of the reactangle\n");

scanf("%d%d",&l,&w);

area=l*w;

break;

default:

printf("Enter a valid choice\n");


}

printf("Area=%f",area);

return 0;

Loops

1)I=0;

while(condition){ -Entry controlled loop

Set of statements

2) do{ -Exit controlled loop

Set of statements

}while(condition);

3)for(initialization;condition;counter variable) - Entry controlled loop

Set of statements

In for loop all the three are optional in that case we can write for loop as

For(;;)

Initialization in the for loop will happen only once upon entry

For(i=0,j=5;i>5&&j>=1;i++,j--)

We will print natural numbers using all the three loops

#include <stdio.h>

int main()

{
int i,num;

printf("Enter a number\n");

scanf("%d",&num);

i=0;

while(i<=num){

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

i++;

return 0;

0/p

01

In this case we first initialize i=0;

0<=8 true

1<=8 true

#include <stdio.h>

int main()

int i,num;

printf("Enter a number\n");

scanf("%d",&num);

i=0;

do{

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

}while(i<=num);

return 0;

#include <stdio.h>

int main()

int i,num;

printf("Enter a number\n");

scanf("%d",&num);

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

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

return 0;

Write a program to find the factors of a number

#include <stdio.h>

int main()

int num,i;

printf("Enter a number\n");

scanf("%d",&num);
printf("The factors of the numbers are\n");

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

if(num%i==0)

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

return 0;

Now calculating the sum of first n natural numbers

#include <stdio.h>

int main()

int num,i,sum=0;

printf("Enter a positive integer:\n");

scanf("%d",&num);

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

sum+=i;//sum=sum+i

printf("sum=%d",sum);

return 0;

}
Factorial of anumber

4! = 4*3*2*1

#include <stdio.h>

int main()

int n,i;

unsigned long long factorial=1;

printf("Enter a positive integer\n");

scanf("%d",&n);

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

factorial *= i;//factorial=factorial*i;

printf("Factorial of the number is %llu\n",factorial);

return 0;

While loop

And use modulus operator

We will get the firstDigit and lastDigit of a number

2345

firstDigit = 2

lastDigit = 5

num as input = 12345

firstDigit=num;
lastDigit = num%10

10|12345(1234

12340

While(firstDigit>10)

firstDigit = firstDigit/10;

Step 1:

10|2345(234

2340

firstDigit = 1234 as value

firstDigit>10 true

step2

firstDigit = firstDigit/10

10|1234(123

1230

firstDigit=123

firstDigit>10 true

step3

firstDigit = firstDigit/10

10|123(12

120
3

firstDigit =12

firstDigit>10 true

step 4

firstDigit = firstDigit/10

10|12(1

10

firstDigit =1

1>10 false

#include <stdio.h>

int main()

int num,lastDigit,firstDigit;

printf("Enter a four digit number\n");

scanf("%d",&num);

firstDigit=num;

lastDigit=num%10;

while(firstDigit>10){

firstDigit/=10;

printf("Last Digit=%d and First Digit=%d\n",lastDigit,firstDigit);

return 0;
}

Write a program to calculate the product of digits of a number

Num=2345

2*3*4*5=120

Product =1

Get the input from the user the number

While(num!=0)

Product =product *(num%10);

Num=num/10;

Step 1 : 2345 num!=0 true

Product = 1*5

Num=234

Step 2: 234!=0 true

Product = 5 * (234%10) = 5*4=20

Num = num/10; 23

Step 3: 23!=0 true

Product = 20*(23%10) = 20 * 3 =60

Num = num/10 2

Step 4: 2!=0 true

Product = 60 * 2 =120

Num = num/10 ;

Num=0

O!=0 false
Now I print the product

#include <stdio.h>

int main()

int n,product=1;

printf("Enter a number which is greater than 2 digit\n");

scanf("%d",&n);

while(n!=0){

product = product*(n%10);

n/=10;

printf("The product of the number is %d\n",product);

return 0;

Write a program to print the reverse of a number

2345

5432

reverseNumber=0;

Num = 2345

While(n!=0)

Remainder = n%10;

reverseNumber = reverseNumer*10+remainder;

n/=10;
}

Step 1:

2345 remainder = 5 reverseNumber = 0*10+ 5=5 n=n/10 (2345/10) q-234 n!=0 234!=0 true

Step 2:

234 remainder=4 reverseNumber = 5 * 10 + 4 =54 n=n/10 (234/10) q-23 n!=0 23!=0 true

Step 3:

23 remainder = 3 reverseNumber = 54*10+3 =543 n=n/10 (23/10) q-2 2!=0 true

Step 4:

2 remainder = 2 reverseNumber = 543*10+2 = 5432 n= 2/10 q-0 0!=0 false

While loop terminated

Print the reverseNumber 5432

#include <stdio.h>

int main()

int n,reverseNumber=0,remainder;

printf("Enter a four digit number\n");

scanf("%d",&n);

while(n!=0){

remainder = n%10;

reverseNumber = reverseNumber*10+remainder;

n/=10;

printf("The reverse of the digit is %d\n",reverseNumber);

return 0;
}

Enter a number and print it in words

2345

5432

Twothreefourfive

First I reverse the digit

While(n!=0)

reverseNumber=(reverseNumber*10)+(n%10);

n/=10;

While(reverseNumber!=0)

Switch(reverseNumber%10)

Case o:

Printf(“One”)

Break;

reverseNumber/=10;

#include <stdio.h>

int main()

int num,n=0;
printf("Enter any digit number to print in words\n");

scanf("%d",&num);

/*while(num!=0){

n=(n*10)+(num%10);

num/=10;

}*/

while(n!=0){

switch(n%10){

case 0:

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:

printf("Nine");

break;

n/=10;

return 0;

Write a program to check whether a number is palindrome or not

Reverse the number == OriginalNumber then it is a palindrome

Number=1234

Remainder = num%10 that is the last digit

reverseNumber = 0 *10+4 = 4

num = num/10; 123

Remainder = num%10 =123%10 =3


reverseNumber=4*10+3=43

num = num/10 = 12

remainder = num%10 = 12%10 = 2

reverseNumber = 43*10+2 =432

num = num/10 = 1

remainder = num%10 = 1

reverseNumber = 432*10+1 = 4321

num = num/10 = 0

num!=0 false it comes out of the loop

print reverseNumber

how to check a number is palindrome or not

reverse the number

if(originalNumber == reverseNumber) print(it is a palindrome)

else print(not a palindrome)

#include <stdio.h>

int main()

int num,reverseNumber=0,remainder,originalNumber;

printf("Enter a four digit number\n");

scanf("%d",&num);

originalNumber=num;

while(num!=0){

remainder=num%10;

reverseNumber=reverseNumber*10+remainder;
num/=10;

if(originalNumber==reverseNumber)printf("It is a palindrome");

else printf("It is not a palindrome");

return 0;

Write a program to count the number of digits of a number

#include <stdio.h>

int main()

long long num;

int count=0;

printf("Enter any digit number\n");

scanf("%lld",&num);

while(num!=0){

num/=10;

++count;

printf("Number of digits of the number is %d",count);

return 0;

With this write a program to check whether a number is Armstrong or not

Example
153 = 1^3+5^3+3^3 = 1+125+27 = 153

1634 = 1^4+6^4+3^4+4^4 = 1+1296+81+256=1634

Here first we have to calculate the number of digits

Math.h

Pow();

#include <stdio.h>

#include<math.h>

int main()

int num,num1,originalNumber,remainder,result=0,count=0;

printf("Enter any digit number\n");

scanf("%lld",&num);

originalNumber=num;

while(num!=0){

num/=10;

++count;

num1=originalNumber;

while(num1!=0){

remainder=num1%10;

result+=pow(remainder,count);//result=0 ->0+3^3+5^3+1^3 ->result have the value

num1/=10;//15//1

if(originalNumber==result)printf("It is an Armstron Number\n");


else printf("It is not an Armstrong Number\n");

return 0;

Write a program to find the prime numbers between two values

While loop

For loop

If condition

I get input from the user that is the two intervals

3 and 20

Num1=3 and num2=20

Flag=0

While(num1<num2){

Flag=0;

For(i=2;i<=num1/2;i++)

If(num1%i==0){flag=1;break;}

If(flag==0)printf(“%d”,num1);

++num1;

Step 1:

3<20

Flag=0

For(i=2;2<1(false){}
If(flag==0) true so it prints 3

Num1=4

Step2:

4<20 true

Flag=0

For(i=2;i<=2(true)

If(4%2==0)(true){flag=1;breaks the for loop}

If(flag==0)false

Not printing 4

Num1++ - >5

Step 3:

5<20 true{

Flag=0

For(i=2;i<=2(true)

If(5%2==0) false

If(flag==0) ->5

++num1; ->6

6<20 true

Flag=0;

For(i=2;i<=3;i++)

{
If(6%2==0)true(flag=1;break;)

If(flag==0)false

Num1++

#include <stdio.h>

int main()

int num1,num2,i,flag;

printf("Enter two integer number\n");

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

printf("Prime numbers between %d and %d are: ",num1,num2);

while(num1<num2){

flag=0;

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

if(num1%i==0){flag=1;break;}

if(flag==0)printf("%d",num1);

++num1;

return 0;

Write a menu driven program for a calculator

#include <stdio.h>

int main()

{
int num1,num2,i,flag;

printf("Enter two integer number\n");

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

printf("Prime numbers between %d and %d are: ",num1,num2);

while(num1<num2){

flag=0;

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

if(num1%i==0){flag=1;break;}

if(flag==0)printf("%d",num1);

++num1;

return 0;

Fibonacci series upto n number of terms

0 1 1 2 3 5 8 13

#include <stdio.h>

int main()

int i,n,d1=0,d2=1,nextTerm;

printf("Enter the number of terms\n");

scanf("%d",&n);

printf("Fibonacci series is:\n");

for(i=0;i<=n;i++){
printf("%d\t",d1);

nextTerm=d1+d2;

d1=d2;

d2=nextTerm;

return 0;

Inside the for loop

Step1: i= 0 ; 0<=5; { 0 nextTerm = 0+1 =1;d1=1;d2=1}

Step2:i=1;1<=5;{0 1 nextTerm =

Program to print half pyramid

**

***

****

#include <stdio.h>

int main()

int i,n,d1=0,d2=1,nextTerm;

printf("Enter the number of terms\n");

scanf("%d",&n);

printf("Fibonacci series is:\n");

for(i=0;i<=n;i++){
printf("%d\t",d1);

nextTerm=d1+d2;

d1=d2;

d2=nextTerm;

return 0;

Step1:

For(i=1;1<=4;

For(j=1;1<=1;j++ 2<=1(false)

\n

Step2:

For(i=2;2<=4

For(j=1;1<=2;j++ now j becomes 2 2<=2(true) j++ 3<=2(false

**

}
\n

Step3:

For(i=3;3<=4

For(j=1;1<=3;j++ 2<=3;j++ 3<=3;j++ 4<=3 false

\n

Stpe 4;

For(i=4;4<=4

For(j=1;1<=4;j++

\n

To print half pyramid numbers

#include <stdio.h>

int main()

int i,j,rows;

printf("Enter the number of rows\n");

scanf("%d",&rows);

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

for(j=1;j<=i;j++){
printf("%d",j);

printf("\n");

return 0;

Write a program to print inverted half pyramid

#include <stdio.h>

int main()

int i,j,rows;

printf("Enter the number of rows\n");

scanf("%d",&rows);

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

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

printf("%d",j);

printf("\n");

return 0;

Step1: i=4;i>=1;i—

J=1;j<=4;j++
Step2:i=3;3>=1

J=1;j<=3;j++

#include <stdio.h>

int main()

int i,space,rows,k=0;

printf("Enter the number of rows\n");

scanf("%d",&rows);

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

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

printf(" ");

while(k!=2*i-1)

printf("*");

++k;

printf("\n");

return 0;

}Step 1:

I=1; 1<=4(true)
{

Space=1;space<=4-1(3) space 2<=3 (space) 3<=3 (space)

While(0!=2*1-1) 0!=1 * 1!=1(false)

Step 2:

I=2; 2<=4

Space=1;space<=4-2(2)(true)(space) 2<=2(true)(space) 3<=2(false

While(0!=2*2-1)(0!=3)(*)(++k) (1!=3) (*) (2!=3) (*) (3!=3)(false)

This is how the pattern program works

Printing floyds triangle

#include <stdio.h>

int main()

int rows,i,j,number=1;

printf("Enter the number of rows");

scanf("%d",&rows);

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

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

printf("%d",number);

number++;

printf("\n");
}

return 0;

Multiplication table

#include <stdio.h>

int main()

int n,i;

printf("Enter an integer");

scanf("%d",n);

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

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

return 0;

Finding the GCD of two integers

#include <stdio.h>

int main()

int n1,n2,i,gcd;

printf("Enter the two integers\n");

scanf("%d%d",&n1,&n2);

for(i=1;i<=n1&&i<=n2;i++){
if(n1%i==0 && n2%i==0){

gcd=i;

printf("GCD of %d and %d is %d",n1,n2,gcd);

return 0;

Write a program to check whether a number is odd or even or prime

#include <stdio.h>

int main()

int i,n,r,count;

count=0;

printf("Enter the number\n");

scanf("%d",&n);

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

if(n%i==0)count++;

if(count==2)printf("%d is a prime number",n);

else printf("%d is not a prime number",n);

r=n%2;

r==0?printf("%d is even\n",n):printf("%d is odd\n",n);

return 0;

}
#include <stdio.h>

int main()

int a=3,b=4,c=3,d=4,x,y;

x=(a=5)&&(b=7); //x=1,a=5,b=7

y=(c=5)||(d=8);//y=1,c=5,d=4

printf("a=%d,b=%d,c=%d,d=%d,x=%d,y=%d\n",a,b,c,d,x,y);

x=(a==6)&&(b=9);//5==6(false)a=5,b=7,x=0

y=(c==6)||(d=10);//c=5,d=10,y=1

printf("a=%d,b=%d,c=%d,d=%d,x=%d,y=%d\n",a,b,c,d,x,y);

return 0;

#include <stdio.h>

int main()

int i;

for(i=20;i<60;i++){

gotoxy(i,5); // * *

printf("*");

gotoxy(i,20);

printf("*");
}

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

gotoxy(20,i);

printf("*");

gotoxy(60,i);

printf("*");

gotoxy(38,12);

printf("C Tutorials");

Statements in c Programming

Goto statement – unconditional transfer

Break – break statement is used to break the loop

Continue – to skip a particular iteration

Goto statement

Write a program to add only positive numbers if negative number is entered then we have to display the
sum till that negative numbers

#include <stdio.h>

int main()

int num,i,ele,sum=0,count=0;

float average;

printf("Enter the number of elements\n");

scanf("%d",&num);

for(i=0;i<num;i++){
printf("Enter the %d element\n",i+1);

scanf("%d",&ele);

if(ele<0)goto display;

sum+=ele;

count++;

display:average=(float)sum/count;

printf("The sum of numbers is %d\n",sum);

printf("The average of numbers is %f\n",average);

return 0;

Forward jump with goto statement

#include <stdio.h>

int main()

int a=10;

Loop: do{

if(a==15){

a=a+1;

goto Loop;

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

a++;

}while(a<20);
return 0;

2)Continue

#include <stdio.h>

int main()

int i;

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

if(i==5)continue;

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

return 0;

3)break

#include <stdio.h>

int main()

int i=0;

for(;;){//infinite loop

if(i>5)break;

i++;

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

}
return 0;

Arrays -> arrays are nothing but fixed size memory and it is going to store the elements in consecutive
memory locations and also only homogeneous datas( int array then it will store only int data)

Float array(it will store only float type data)

Arrays – one dimensional array

Multidimensional array(2D,3D)

Int arr[5];

Last element n-1

In c there is no bound checking for arrays u can exceed the limits of array size

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

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

For loop->for traversing the array & initializing the array

#include<stdio.h>

int main() {

int a[5];

int i;

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

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

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

printf("%d",a[i]);

If we are not initializing the array to full of its size rest will be initialized to zeros
#include<stdio.h>

int main() {

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

printf("%d%d%d%d%d%d",a[0],a[1],a[2],a[3],a[4],a[5]);

Finding the size of the array

#include<stdio.h>

int main() {

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

int size;

size=(sizeof(a)/sizeof(a[0]));

printf("%d",size);

Sizeof(a) assume u r working with 16 bit compiler in that case int is 2 bytes

A[0]=2 bytes

A[1]=2 bytes

12 bytes is the sizeof(a)

Sizeof(a[0]) – 2

Sizeof(a)/sizeof(a[0])

12/2 – 6

This is the program common to find the size of the array

Write a program to find the sum and average of the elements of the array

#include<stdio.h>
int main() {

int a[100];

int i,n,sum=0;

float average;

printf("Enter the number of elements\n");

scanf("%d",&n);//n=5

printf("Enter the %d elements\n",n);

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

scanf("%d",&a[i]);->a[0]=10,a[1]=10,a[2]=10,a[3]=10,a[4]=10

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

sum+=a[i]; 0+a[0] =
sum=10,sum=10+a[1]=10+10=20,sum=20+a[2]=30,sum=30+a[3]=40,sum=40+1[4]=50

average=(float)sum/n;

printf("The sum of %d elements is %d\n",n,sum);

printf("The average of %d elements is %f",n,average);

Multidimensional array -> 2D 3D

Int a[2][3]={ ->it has two rows and 3 coulmns number of elements will be number of rows*number of
columns=2*3=6

Int a[2][3]={

{10,20,30},

{40,50,60}

};
Int a[2][3][4] ={

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

{{13,14,15,16},{17,18,19,20},{21,22,23,24}}

};

2*3*4=24 elements

Write a program where we have cities its weekly temperature has to be recorded

#include<stdio.h>

#define CITY 2

#define WEEK 7

int main() {

int temp[CITY][WEEK];

int i,j;

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

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

printf("Enter the city %d day %d temperature\n",CITY,WEEK);

scanf("%d",&temp[i][j]);
temp[0][1]=32,temp[0][2]=33,temp[0][3]=32temp[0][4]=33,temp[0][5]=32,temp[0][6]=32

temp[1][0]33.temp[1][1]=32 temp[1][6]=32

printf("Displaying the weekly temperature\n");

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

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

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

printf("\n");
}

Write a program to find the duplicate elements in an array

#include<stdio.h>

int main() {

int a[]={4,2,4,5,2,3,1};

int i,j;

int a_size=sizeof(a)/sizeof(a[0]);

printf("Duplicate elements are \n");

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

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

if(a[i]==a[j])//a[0]==a[1](false),a[0]==a[2] 4==4(true) printfa[0]=4,a[0]==a[3]4==5(false)

a[1]==a[2]

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

Write a program to find the odd and even numbers in an array and store even numbers in one array and
store odd numbers in another array and display

Arr1[100],arr2[100],arr3[100]

(arr[i]%2==0) (true) then the number is even number

Else it is odd number


#include <stdio.h>

int main(void) {int arr1[10],arr2[10],arr3[10];


//arr2 for holding even numbers arr3 for odd numbers
int i,j=0,k=0,n;
//n-number of elements and j for even numbered array and k for odd numbered array
printf("Enter the number of elements\n");
scanf("%d",&n);//n=6
printf("Input the %d elements of the array\n",n);
for(i=0;i<n;i++){
scanf("%d",&arr1[i]);
//arr[0]=3,arr[1]=4,arr[2]=5,arr[3]=6,arr[4]=7,arr[5]=8
}
for(i=0;i<n;i++){
//i=0;0<6(t){arr1[0]=3%2==0(f)else{arr3[0]=3;k++;
//i=1;1<6(t){arr1[1]=4%2==0(t){arr2[0]=4;j++;
//i=2;2<6(t){arr1[2]=5%2==0(f){else{arr3[1]=5;k++;
//i=3;3<6(t){arr1[3]=6%2==0(t){arr2[1]=6;j++;
//i=4;4<6(t){arr1[4]=7%2==0(f){else arr3[2]=7;k++;
//i=5;5<6(t){arr1[5]=8%2==0(t){arr2[2]=8;j++;//note j holds number of even terms
//k holds number of odd terms
if(arr1[i]%2==0){
arr2[j]=arr1[i];
j++;
}else{
arr3[k]=arr1[i];
k++;
}
}
printf("The even numbers are\n");
for(i=0;i<j;i++){
printf("%d\t",arr2[i]);
}
printf("\nThe odd numbers are\n");
for(i=0;i<k;i++){
printf("%d\t",arr3[i]);
}
return 0;
}

Write a program to find the largest of the elements in the array

#include <stdio.h>
int main(void) {
int arr[100];
int i,n,temp;
printf("Enter the number of elements\n");
scanf("%d",&n);
printf("Enter the %d elements of the array\n",n);
for(i=0;i<n;i++){
scanf("%d",&arr[i]);
}
for(i=1;i<n;i++){
if(arr[0]<arr[i]){//11<12(t){arr[0]=12;12<11(f);12<14(t){arr[0]=14,arr[2]=12
temp=arr[0];
arr[0]=arr[i];
arr[i]=temp;
}
}
printf("The largest element of the array is %d\n",arr[0]);
for(i=0;i<n;i++){
printf("%d\t",arr[i]);
}
return 0;
}
Write a program to copy element by element from an array into another array
#include <stdio.h>

int main(void) {
int arr1[10],arr2[10];
int i,n;
printf("Enter the number of elements of the array\n");
scanf("%d",&n);//n=6
printf("Input the %d elements of the array\n");
for(i=0;i<n;i++){//arr1[0],arr1[1],arr1[2],arr1[3],arr1[4],arr1[5]
scanf("%d",&arr1[i]);
}
//copy element by element from arr1 into arr2
for(i=0;i<n;i++){//
arr2[i]=arr1[i];
}
printf("\n\nThe elements copied into the array are\n");
for(i=0;i<n;i++){
printf("%d\t",arr2[i]);
}
return 0;
}
Write a program to insert an element into an array
#include <stdio.h>

int main(void) {
int arr[100],n,c,value,position;
printf("Enter the number of elements\n");
scanf("%d",&n);//n=6
printf("Input the %d elements into the array\n",n);
for(c=0;c<n;c++){
scanf("%d",&arr[c]);//arr[0],arr[1],arr[2],…arr[5]
}
printf("Enter the position where to insert the elements\n");
scanf("%d",&position);
printf("Enter the value to be inserted\n");
scanf("%d",&value);
for(c=n-1;c>=position-1;c--){
arr[c+1]=arr[c];
//arr[5]=arr[4],arr[4]=arr[3],arr[3]=arr[2]arr[2]=arr[2]=value
}
arr[position-1]=value;
printf("Resultant array is\n");
for(c=0;c<=n;c++){
printf("%d\t",arr[c]);
}
return 0;
}
Write a program to delete an element from an array
#include <stdio.h>

int main(void) {
int arr[100],n,c,value,position;
printf("Enter the number of elements\n");
scanf("%d",&n);
printf("Input the %d elements into the array\n",n);
for(c=0;c<n;c++){
scanf("%d",&arr[c]);
}
printf("Enter the position where to delete the elements\n");
scanf("%d",&position);
if(position>(n+1)){
printf("Deletion not possible\n");
}
else{
for(c=position-1;c<n-1;c++){
arr[c]=arr[c+1];//arr[2]=arr[3],arr[3]=arr[4],arr[4]=arr[5]
}
printf("Resultant array is \n");
for(c=0;c<n-1;c++){
printf("%d\t",arr[c]);
}
}
return 0;
}

Linear search
#include <stdio.h>

int main()
{
int arr[100],search,c,n;
printf("Enter the number of elements\n");
scanf("%d",&n);
printf("Input the %d elements of the array\n",n);
for(c=0;c<n;c++){
scanf("%d",&arr[c]);
}
printf("enter the element to be searched\n");
scanf("%d",&search);
for(c=0;c<n;c++){
if(arr[c]==search){
printf("%d is present at location %d\n",search,(c+1));
break;
}
}
if(c==n){printf("%d is not present in the array\n",search);}
return 0;
}
Logic for linear search
for(c=0;c<n;c++){
if(arr[c]==search){
printf("%d is present at location %d\n",search,(c+1));
break;
}
Step 1:
C=0 ; 0<6(t)
Arr[0]=11==43(f)
C=1 ; 1<6(t)
Arr[0]=21==43(f)
C=2 ; 2<6(t){arr[2]=12==43(f)
C=3 ; 3<6(t){if(22==43(f)
C=4 ; 4<6(t){if(13==43(f)
C=5 ; 5<6(t){if(23==43)(f)
C=6 ; 6<6(f)
}
If(c==n) (6==6)(t){43 not present in the array

Sorting technique
How to sort the elements in the array

Bubble sorting
arr[]={11,12,21,13,22,23}

#include <stdio.h>

int main()
{
int arr[100],n,i,j,temp,flag=0;
printf("Enter the number of elements of the array\n");
scanf("%d",&n);
printf("Input the %d elements of the array\n",n);
for(i=0;i<n;i++){
scanf("%d",&arr[i]);
}
//Bubble sort
for(i=0;i<n-1;i++){
for(j=0;j<n-1;j++){
if(arr[j]>arr[j+1]){
temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
flag=1;
}
}
if(flag==0){break;}else{flag=0;printf("%d pass",i);}
}
printf("The array after sorting is \n");
for(i=0;i<n;i++){
printf("%d\t",arr[i]);
}
return 0;
}
Algorithm for bubble sort
for(i=0;i<n;i++){
for(j=0;j<n-1;j++){
if(arr[j]>arr[j+1]){
temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
11 21 12 22 13 23, 11 12 21 22 13 23, 11 12 21 13 22 23,
11 12 13 21 22 23

Step 1:i=0 1st pass

{ j=0;0<5(t){

if(arr[0]>arr[1])(11>21(f)

j++;j=1;1<5(t){if(arr[1]>arr[2])(21>12)(t){temp=21;arr[1]=12;arr[2]=21} arr[]={11,12,21,22,13,23}}

j++;j=2;2<5(t){if(arr[2]>arr[3])(21>22(f)

j++;j=3;3<5(t){if(arr[3]>arr[4])(22>13(t){temp=22;arr[3]=13,arr[4]=22}arr[]={11,12,21,13,22,23}

j++;j=4;4<5(t){if(22>23)(f)

j++;j=5;5<5(f)

Step 2:i++ i=1 1<5(t) 2nd pass arr[]={11,12,21,13,22,23}

{ j=0;0<5(t){

if(arr[0]>arr[1])(1>12(f)

j++;j=1;1<5(t){if(arr[1]>arr[2])(12>21)(f)

j++;j=2;2<5(t){if(arr[2]>arr[3])(21>13(t){arr[]={11,12,13,21,22,23}

j++;j=3;3<5(t){if(arr[3]>arr[4])(21>22)(f)

j++;j=4;4<5(t){if(22>23(f)

j++;5<5(f)
}

Step 3: 3rd pass

Decimal to binary

#include <stdio.h>

int main()

int arr[10],num,i=0,c;

printf("Enter a number\n");

scanf("%d",&num);

while(num>0){

arr[i]=num%2;

num=num/2;

i++;

for(c=i-1;c>=0;c--)printf("%d\t",arr[c]);

return 0;

We were discussing one dimensional array in that we saw

How to declare an array and how to initialize an array

We got the array as input and found the sum and average of the numbers

When ever an array is initialized to less than its size rest will be initialized to zeros

How to find the size of array

Largest element in an array

Smallest element in an array


Duplicate elements in an array

Even & odd elements in an array for which we used three arrays one for initializing

And one for storing even numbers and another for storing odd numbers and printed the arrays

How to insert an element into an array

How to delete an element from an array

Copy element by element from one array into another array

Linear serach

Bubble sort

2D array

Int a[2][3]={

{ 10,20,30},

{40,50,60}

Table or matrix -> columns

Rows a[0][0] a[0][1] a[0][2]

a[1][0] a[1][1] a[1][2]

write a program to get 2 cities weekly temperature and print it in table or matrix form

#include <stdio.h>
#define CITY 2
#define WEEK 7//macros or preprocessor directives symbolic //constant
int main(void) {
int temp[CITY][WEEK];
int i,j;
printf("Enter the two cities weekly temperature\n");
for(i=0;i<CITY;i++){
printf("Enter city %d weekly temperature\n",i+1);
for(j=0;j<WEEK;j++){
scanf("%d",&temp[i][j]);
}
}
printf("Displaying the weekly temperature in table or matrix form\n");
for(i=0;i<CITY;i++){
for(j=0;j<WEEK;j++){
printf("%d\t",temp[i][j]);
}
printf("\n");
}
return 0;
}
How to find the addition of two matrices and display it

#include <stdio.h>

int main(void) {
int a[2][2],b[2][2],c[2][2];
int i,j;
printf("Input the first 2*2 matrix\n");
for(i=0;i<2;i++){
for(j=0;j<2;j++){
scanf("%d",&b[i][j]);
}
}
printf("Input the second 2*2 matrices\n");
for(i=0;i<2;i++){
for(j=0;j<2;j++){
scanf("%d",&c[i][j]);
}
}
for(i=0;i<2;i++){
for(j=0;j<2;j++){
a[i][j]=b[i][j]+c[i][j];//a[0][0]=b[0][0]+c[0][0],a[0][1]=b[0][1]+c[0][1]
a[1][0]=b[1][0]+c[1][0],a[1][1]=b[1][1]+c[1][1]
}
}
printf("The addition of two matrices are\n");
for(i=0;i<2;i++){
for(j=0;j<2;j++){
printf("%d\t",a[i][j]);
}
printf("\n");
}
return 0;
}
Write a program to find the transpose of a matrix
#include <stdio.h>

int main(void) {
int a[3][3],arrt[3][3];
int i,j;
printf("Input the 3*3 matrices\n");
for(i=0;i<3;i++){
for(j=0;j<3;j++){
scanf("%d",&a[i][j]);//a[0][0] a[0][1] a[0][2]
a[1][0] a[1][1] a[1][2]
a[2][0] a[2][1] a[2][2]
}
}
printf("Before transpose the matrix is \n");
for(i=0;i<3;i++){
for(j=0;j<3;j++){
printf("%d\t",a[i][j]);
}
printf("\n");
}
printf("Transposing the matrix\n");
for(i=0;i<3;i++){
for(j=0;j<3;j++){
arrt[i][j]=a[j][i];
// arrt[0][0] = a[0][0] arrt[0][1]=a[1][0] arrt[0][2]=a[2][0]
// arrt[1][0] = a[0][1] arrt[1][1] =a[1][1]
}
}
printf("Transponse of the matrix is\n");
for(i=0;i<3;i++){
for(j=0;j<3;j++){
printf("%d\t",arrt[i][j]);
}
printf("\n");
}
return 0;
}

Int a[2][3][4]={

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

{{13,14,15,16},{17,18,19,20},{21,22,23,24}}

Number of elements = 2*3*4 = 24 elements

How to initialize 3D array and print it


#include <stdio.h>

int main(void) {
int a[2][3][4]={
{{1,2,3,4},{5,6,7,8},{9,10,11,12}},
{{13,14,15,16},{17,18,19,20},{21,22,23,24}}
};
int i,j,k;
for(i=0;i<2;i++){
for(j=0;j<3;j++){
for(k=0;k<4;k++){
printf("%d\t",a[i][j][k]);
}
printf("\n");
}
printf("\n");
}
return 0;

Strings

Strings are nothing but array of characters terminated by a null character ‘\0’

Char s[6]=”hello”;

S[0] s[1] s[2] s[3] s[4] s[5]

H e l l o ‘/0’

Char s[]=”Hello”;

Char s[]={‘h’,’e’,’l’,’l’,’o’,’\o’};

Char *s;

Pointers while discussing

Write a program to read a string and print it

#include<string.h>

Char name[20];
Name=”hello”;

%s

Scanf stops reading when it sees a white space character

#include <stdio.h>

int main()

char name[30];

printf("Input the name\n");

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

printf("%s",name);

return 0;

Using gets and puts with strings

#include <stdio.h>

int main()

char name[30];

printf("Input the name\n");

gets(name);

printf("Name :");

puts(name);

return 0;

}
Write a program to read a line of text and print it using getchar() function

#include <stdio.h>

int main()

char str[50],ch;

int i=0;

printf("Input a string\n");

while(ch!='\n'){

ch=getchar();

str[i]=ch;

i++;

str[i]='\0';

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

return 0;

Write a program to find the length of the string without using the library functions

#include <stdio.h>

int main()

char str[100];

int i;

printf("Input a string\n");
scanf("%[^\n]",str);//this scanf will accept white spaces also

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

printf("Length of the string is %d\n",i);

return 0;

Write a program to reverse a string without using the library function

#include <stdio.h>

int main()

char s[100],r[100];

int begin,end,count=0;

printf("Input a string\n");//arun kumar

gets(s);

while(s[count]!='\0')count++;//count=11

end=count-1;end=10

for(begin=0;begin<count;begin++){//begin=0;begin<count;

r[begin]=s[end]; //r[0]=r;end=9;begin++ ; 1<10(t) r[1]=s[9]->r[1]=a;r[2]=s[8]->m

end--;

r[begin]='\0';

printf("%s",r);

return 0;

}
Write a program to concatenate two strings without using the library function

#include <stdio.h>

int main()

char s1[60],s2[30];

int i=0,j;

printf("Input a string\n");

gets(s1);//arun

printf("Input another string\n");

gets(s2);//kumar

while(s1[i]!='\0')i++;//i=5

for(j=0;s2[j]!='\0';i++,j++){

s1[i]=s2[j];//s1[5]=s2[0],s1[6]=s2[1],s1[7]=s2[2],s1=arunkumar

s1[i]='\0';

printf("Concatenated string is %s\n",s1);

return 0;

Write a program to find the frequency of occurrence of a character in a string

Sachin is a sports person he is awarded

#include <stdio.h>

int main()

{
char str[100],ch;

int i,frequency=0;

printf("Input a string\n");

gets(str);//str=sachin is a sports person he is awarded

printf("Input the character to find the frequency of occurence\n");

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

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

if(ch==str[i])frequency++;//s==str[0]->s==s(t) freq=2;

printf("The frequency of occurence of %c is %d\n",ch,frequency);

return 0;

Write a program to find whether a string is palindrome or not

#include <stdio.h>

int main()

char str[100];

int begin,end,length=0;

printf("Input a string\n");

gets(str);

while(str[length]!='\0')length++;//length of the string

end=length-1;//end is pointing to last character

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

if(str[begin]!=str[end]){//str[0]!=str[3](t)
printf("Not a palindrome");

break;

end--;

if(begin==length)printf("Palindrome");

return 0;

String.h header file

Strlen(str) we are going to use the built in function of string.h header file

#include <stdio.h>

#include <string.h>

int main()

char a[20]="Program";

char b[20]={'P','r','o','g','r','a','m'};

char c[20];

printf("\nEnter a string");

scanf("%s",c);

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

printf("Length of b is %d\n",strlen(b));

printf("Length of c is %d\n",strlen(c));

return 0;

}
Strlwr(str) strupr(str)

Char name[20];

Name=”arun”

Strcpy()

#include <stdio.h>
#include <string.h>
int main()
{
char str1[10]="welcome";
char str2[20];
char str3[20];
strcpy(str2,str1);
strcpy(str3,"C Tutorials");
puts(str2);
puts(str3);
return 0;
}
strcat(str2,str1);
#include <stdio.h>
#include <string.h>
int main()
{
char str1[10]="welcome";
char str2[30];
printf("Enter a string\n");
scanf("%s",str2);
strcat(str2,str1);
printf("The reverse of the string is %s",str2);
return 0;
}
Strcmp(a,b)->+ve,-veor 0

Built of functions of

Functions in c program

Void(return value) main()(arguments or parameters) 1) function without return values and without
arguments

Int main() 2)function with return values without arguments

Void main(int agrv,char *argc[]) 3)function without return value and with arguments
Int main(int argv,char *argc[]) 4)function with return values and with arguments

1)function WRV and WA

#include <stdio.h>
int add(int,int);//function prototype only declaration section of the function
int main()
{
int x,y;
printf("Enter the values of x and y\n");
scanf("%d%d",&x,&y);

printf("The addition of two numbers is %d\n",add(x,y));


return 0;
}
int add(int a,int b){
return (a+b);
}

2)function WORV and WA

#include <stdio.h>
void add(int,int);//function prototype only declaration section of the function
int main()
{
int x,y;
printf("Enter the values of x and y\n");
scanf("%d%d",&x,&y);
add(x,y);
return 0;
}
void add(int a,int b){
int z;
z=a+b;
printf("The addition of two number is %d\n",z);
}

3)function WRV and WOA

#include <stdio.h>
int add();//function prototype only declaration section of the function
int main()
{
int z;
//printf("Enter the values of x and y\n");
//scanf("%d%d",&x,&y);
z=add();
printf("The addition of two numbers is %d\n",z);
return 0;
}
int add(){
int x,y;
printf("Enter the values of x&y\n");
scanf("%d%d",&x,&y);
return (x+y);
}
4)function WORV and WOA

#include <stdio.h>
void add();//function prototype only declaration section of the function
int main()
{
add();
return 0;
}
void add(){
int x,y,z;
printf("Enter the values of x&y\n");
scanf("%d%d",&x,&y);
z=x+y;
printf("The addition of two numbers is %d\n",z);
}
Prime number write it using function

#include <stdio.h>

int checkPrimeNumber(int);

int main()

int n1,n2,i,flag;

printf("Enter the two positive numbers\n");

scanf("%d%d",&n1,&n2);

printf("Prime numbers between %d and %d is\n",n1,n2);

for(i=n1;i<=n2;i++){
flag=checkPrimeNumber(i);

if(flag==1){

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

return 0;

int checkPrimeNumber(int n){

int j,flag=1;

for(j=2;j<=n/2;j++){

if(n%j==0){

flag=0;

break;

return flag;

Write a program with functions to check whether a number is Armstrong or not

#include <stdio.h>

void armstrongNumber(int);

int main()

int num;

printf("Enter a number\n");
scanf("%d",&num);

armstrongNumber(num);

return 0;

void armstrongNumber(int num){

int originalNumber=num,result=0,rem;

while(originalNumber!=0){

rem=originalNumber%10;

result+=rem*rem*rem;

originalNumber/=10;

if(result==num){

printf("%d is an armstrong Number\n",num);

}else{

printf("%d is not an armstrong number\n",num);

Finding the largest of two numbers using functions

#include <stdio.h>

void armstrongNumber(int);

int main()

int num;

printf("Enter a number\n");

scanf("%d",&num);
armstrongNumber(num);

return 0;

void armstrongNumber(int num){

int originalNumber=num,result=0,rem;

while(originalNumber!=0){

rem=originalNumber%10;

result+=rem*rem*rem;

originalNumber/=10;

if(result==num){

printf("%d is an armstrong Number\n",num);

}else{

printf("%d is not an armstrong number\n",num);

Largest of two numbers

#include <stdio.h>

int large(int,int);//function prototype

int main()

int max,x,y;

printf("Enter the values of x & y\n");

scanf("%d%d",&x,&y);

max=large(x,y);
printf("The largest of two number is %d",max);

return 0;

int large(int x,int y){

if(x>y)return x;

else return y;

Now function returning multiple values

& - addressof operator or referencing operator

*-value of operator or dereferencing operator

#include <stdio.h>

void mathOperation(int x,int y,int *sum,int *diff);//function prototype *

int main()

int x,y,s,d;

printf("Enter the two numbers\n");

scanf("%d%d",&x,&y);

mathOperation(x,y,&s,&d);//call by reference

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

return 0;

void mathOperation(int a,int b,int *sum,int *diff){//function definition *

*sum=a+b;

*diff=a-b;

}
Function call in c

1)call by value

2)call by reference

#include <stdio.h>

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

int main()

int x,y;

printf("Enter the values of x & y\n");

scanf("%d%d",&x,&y);

printf("Before swapping values of x=%d and y=%d\n",x,y);

swap(&x,&y);

printf("After swapping values of x=%d and y=%d\n",x,y);

return 0;

void swap(int *x,int *y){

int *temp;

*temp=*x;

*x=*y;

*y=*temp;

Recursive function

It is a function which calls itself again and again

Sum of natural numbers using recursion

#include <stdio.h>
int addNumbers(int n);

int main()

int num;

printf("Enter a positive number\n");

scanf("%d",&num);

printf("sum=%d",addNumbers(num));

return 0;

int addNumbers(int n)

if(n!=0)return n+addNumbers(n-1);

else return n;

Factorial of a number

#include <stdio.h>

long int factorial(int n);

int main()

int n;

printf("Enter a positive number\n");

scanf("%d",&n);

printf("Factorial of %d=%ld\n",n,factorial(n));

return 0;

}
long int factorial(int n)

if(n>=1)return n*factorial(n-1);

else return 1;

Write a program to show a function calling another function

Ratio 0f a/a-b here if a-b=0 then a/0=infinite it will throw error difference

Another function which is going to calculate the ratio from this function we call difference function

#include <stdio.h>

float ratio(int x,int y);

int diff(int x,int y);

int main()

int a,b;

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

printf("%f\n",ratio(a,b));

return 0;

float ratio(int x,int y)

if(diff(x,y))return (x/(x-y));

else return 0.0;

int diff(int x,int y)

{
if(x!=y)return 1;

else return 0;

Passing single element from an array as argument

#include <stdio.h>

void display(int);

int main()

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

display(arr[2]);

return 0;

void display(int a){

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

Passing whole array as an argument to a function

#include <stdio.h>

void display(int [],int);//function protype u have to specify the array

int main()

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

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

display(arr,size);//function call just the name of the array is enough

return 0;

}
void display(int a[],int size){

int i;

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

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

Write a program to calculate the sum and average of elements of an array using function and print the
average

#include <stdio.h>

float display(int [],int);//function protype u have to specify the array

int main()

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

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

printf("The average of elements of the array is %.2f\n",display(arr,size));//function call just the name
of the array is enough

return 0;

float display(int a[],int size){

int i,sum=0;

float average;

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

sum+=a[i];

average=(float)sum/size;

return average;

}
Two dimensional array display using function

#include <stdio.h>

void display(int [][2]);//function protype u have to specify the array

int main()

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

display(arr);

return 0;

void display(int a[][2]){

int i,j;

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

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

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

printf("\n");

Write a program to find the standard deviation

SD= sqrt(Ei=1ton(xi-x)^2

SD=N∑∣x−μ∣2
#include <math.h>

float calculateSD(float data[]);

int main()

{
int i;

float data[10];

printf("Enter the 10 elements\n");

for(i=0;i<10;i++)scanf("%f",&data[i]);

printf("The Standard Deviation is %.2f\n",calculateSD(data));

return 0;

float calculateSD(float data[]){

float sum=0.0,mean,SD=0.0;

int i;

for(i=0;i<10;i++)sum+=data[i];

mean=sum/10;

for(i=0;i<10;i++)SD+=pow(data[i]-mean,2);

return sqrt(SD/10);

Write a program to pass character array and convert lower case to upper case

#include <stdio.h>

void upper_String(char []);

int main()

char str[100];

printf("Enter a string in lower case\n");

gets(str);

upper_String(str);

printf("The string in upper case is %s\n",str);


return 0;

void upper_String(char s[]){

int c=0;

while(s[c]!='\0'){

if(s[c]>='a'&&s[c]<='z'){

s[c]=s[c]-32;

c++;

Storage classes

1)auto 2)static3)extern4)register

1)what ever variables we declare within a block or a function will be auto by default even if your are not
using auto keyword and it will have garbage value if uninitialized

#include <stdio.h>

void display();

int b;

int main(){

int a=20;

int c;

display();

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

return 0;

void display(){
auto int a=10;

printf("inside function local variable=%d\n",a);

2)static variable

Static variable can be both local and global which maintains its state between different function calls
and initialized only once

#include <stdio.h>

void increment();

int main(){

int i;

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

return 0;

void increment(){

static int j=0;

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

j++;

3)extern

Any global variable can be declared using the keyword extern and it will be initialized and modified from
outside your program

#include <stdio.h>

extern int i;

void main(){

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

}
int i=20;

4)register

Int *p;

Int x=20;

P=&x;

Register is used to store the variable in CPU register and also it is rarely used and faster in execution
since it access the hardware & pointer variables cannot be used as registers

#include <stdio.h>

void main(){

register int i=20;

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

Structures

A structure is a user defined data type that can be used to group items of different types into a single
type

Struct keyword is used for structures

Structure is going the record or some database

Struct address{

Char name[50];

Char street[100];

Char city[30];

Char state[50];

Long int pincode;

};
Declare a structure variable

1) Struct point{
Int x,y;//members of the structure
}p1;
2) Struct point{
Int x,y;
};
Struct point p1;
Members of structure can be accessed with the help of dot(.) operator
P1.x , p1.y
3) You cant initialize a structure member within a structure because no memory is allotted for it
only during declaration we will have memory allotted then we can initialize
Struct point{
Int x=10;
Int y=20;
}p1; not allowed
4) Struct point{
Int x,y;
}p1={10,20};
5) Designated initialization
Struct point{
Int x,y;
};
Struct point p1={.y=10,.x=20};

Designated initialization
#include <stdio.h>
struct point{
int x;
int y;
};
int main()
{
struct point p1={.y=10,.x=20};//designated intialization
printf("p1.x=%d\np1.y=%d\n",p1.x,p1.y);

return 0;
}
Structure initialization through user input
#include <stdio.h>
struct point{
int x;
int y;
};
int main()
{
struct point p1={.y=10,.x=20};//designated intialization
struct point p2;
printf("p1.x=%d\np1.y=%d\n",p1.x,p1.y);
printf("Enter the values of p2.x and p2.y\n");
scanf("%d%d",&p2.x,&p2.y);
printf("p2.x=%d\np2.y=%d\n",p2.x,p2.y);
return 0;
}
Array of structures
#include <stdio.h>
struct point{
int x;
int y;
};
int main()
{
struct point p[3];
int i;
printf("Enter the structure values\n");
for(i=0;i<3;i++){
printf("Enter the values of p[%d].x and p[%d].y\n",i,i);
scanf("%d%d",&p[i].x,&p[i].y);
}
printf("Displaying the array of structures\n");
for(i=0;i<3;i++)
printf("p[%d].x=%d\tp[%d].y=%d\n",i,p[i].x,i,p[i].y);
return 0;
}
Passing strucuture as an argument to a function
#include <stdio.h>
struct point{
int x;
int y;
};
void display(struct point p2);
int main()
{
struct point p1={10,20};
display(p1);
return 0;
}
void display(struct point p2){
printf("p2.x=%d\tp2.y=%d\n",p2.x,p2.y);
}Pointers
Int x=10;
Int *p;
P=&x; pointer holds the address of another variable
How to declare a structure pointer and access
Member operator dot(.) operator
->(pointer to the structure)
#include <stdio.h>
struct point{
int x;
int y;
}p1={10,20};
int main()
{
struct point *p2;
p2=&p1;
printf("p2.x=%d\tp2.y=%d\n",p2->x,p2->y);
return 0;
}
Passing structure pointer as argument to a function
#include <stdio.h>
struct point{
int x;
int y;
}p1={10,20};
int main()
{
struct point *p2;
p2=&p1;
printf("p2.x=%d\tp2.y=%d\n",p2->x,p2->y);
return 0;
}
Structure of a record of a student
#include <stdio.h>
struct student{
char name[50];
int rollno;
float marks;
};
void display(struct student s);
int main()
{
struct student s1;
printf("Enter the name of the student\n");
scanf("%s",&s1.name);
printf("Enter the roll number of the student\n");
scanf("%d",&s1.rollno);
printf("Enter the marks of the student\n");
scanf("%f",&s1.marks);
display(s1);
return 0;
}
void display(struct student s){
printf("Name = %s\n",s.name);
printf("Roll Number = %d\n",s.rollno);
printf("Marks = %f\n",s.marks);
}
Write a program to add two distances and display in inch and feet
struct student{
char name[50];
int rollno;
float marks;
};
void display(struct student s);//int i
int main()
{
struct student s1;
printf("Enter the name of the student\n");
scanf("%s",&s1.name);
printf("Enter the roll number of the student\n");
scanf("%d",&s1.rollno);
printf("Enter the marks of the student\n");
scanf("%f",&s1.marks);
display(s1);//display(10) and receiving place void display(int i);
return 0;
}
void display(struct student s){
printf("Name = %s\n",s.name);
printf("Roll Number = %d\n",s.rollno);
printf("Marks = %f\n",s.marks);
}
What is typedef in case of structures it will be useful
Typedef is used to create an alias name for already existing type
#include <stdio.h>

int main()
{
typedef int age;
age x;
printf("Enter the age of the person\n");
scanf("%d",&x);
printf("The age of the person is %d\n",x);
return 0;
}
How to use typedef in structures
#include <stdio.h>
typedef struct distance
{
int feet;
float inches;
}dist;
void add(dist d1,dist d2,dist *sum);
int main()
{
dist d1,d2,sum;
printf("Enter the 1st distance in feet\n");
scanf("%d",&d1.feet);
printf("Enter the 1st distane in inches\n");
scanf("%f",&d1.inches);
printf("Enter the 2nd distance in feet\n");
scanf("%d",&d2.feet);
printf("Enter the 2nd distance in inches\n");
scanf("%f",&d2.inches);
add(d1,d2,&sum);
printf("Sum of distances is %d\' %.2f\"\n",sum.feet,sum.inches);
return 0;
}
void add(dist d1,dist d2,dist *sum){
sum->feet=d1.feet+d2.feet;
sum->inches=d1.inches+d2.inches;
while(sum->inches>12){
++sum->feet;
sum->inches=sum->inches-12;
}
}
Nested structures
#include <stdio.h>
struct stud_coll_detail{
int college_id;
char college_name[50];
};
struct student_detail{
int id;
char name[40];
float percentage;
struct stud_coll_detail coll_data;
};
void main()
{
struct student_detail stu_data={123,"Arun",76.56,1156,"Naresh"};
printf("Student details are \n");
printf("ID : %d\n",stu_data.id);
printf("Name is : %s\n",stu_data.name);
printf("Percentage is : %f\n",stu_data.percentage);
printf("College id is : %d\n",stu_data.coll_data.college_id);
printf("College name is : %s\n",stu_data.coll_data.college_name);
}
Find the size of the structure
#include <stdio.h>
struct stud{
int id;
char name[30];
float marks;
};
int main(){
struct stud s1;
printf("The size of the structure is %d\n",sizeof(s1));
return 0;
}
Unions which is the largest data type memory will be allotted only for that variable and rest of
the variables will use that memory only
#include <stdio.h>
#include <string.h>
union point{
int x,y;
char name[30];
};
int main()
{
union point p1;
p1.x=10;
p1.y=30;
strcpy(p1.name,"Arun");
printf("p1.x=%d\np1.y=%d\np1.name=%s\n",p1.x,p1.y,p1.name);
return 0;
}
Enum -> enum is user defined data type used to assign names to integral constants
Names make the programs read easily
#include <stdio.h>
enum week{mon,tue=3,wed,thur=7,fri,sat,sun};
int main(){
enum week day;
day=sat;
printf("%d",day);
return 0;
}
Using enum in for loop
#include <stdio.h>
enum year{jan,feb,mar,apr,may,jun,jul,aug,sep,oct,nov,dec};
int main(){
enum year i;
for(i=jan;i<dec;i++)printf("%d\t",i);
return 0;
}
In enums two names can have same value
#include <stdio.h>
enum state{working=1,failed=0,freezed=0};
int main(){
printf("%d%d%d",working,failed,freezed);
return 0;
}
Two enums cannot have same name
#include <stdio.h>
enum state{working=1,failed,freezed};
enum states{working=3,warm,liquid};
int main(){
printf("%d%d%d",working,failed,freezed);
return 0;
}
How to return an enum from a function

#include <stdio.h>
enum state{working=0,failed,freezed};
enum state currstate=1;
enum state findstate(){
return currstate;
};
int main(){
(findstate()==freezed)?printf("Finished"):printf("Working");
return 0;
}
Sizeof enum
#include <stdio.h>
enum suit{club=0,diamonds=10,hearts=20,spades=3}card;
int main(){
card=diamonds;
printf("Size of enum is %d\n",sizeof(card));
return 0;
}
Enum using switch case
#include <stdio.h>

int main()
{
enum color{red,green,blue};
enum color favorite_color;
printf("Enter your favorite color : 0.red,1.green,2.blue\n");
scanf("%d",&favorite_color);
switch(favorite_color){
case red:
printf("Your favorite color is red\n");
break;
case green:
printf("Your favorite color is green\n");
break;
case blue:
printf("Your favorite color is blue\n");
break;
default:
printf("Choose any color from given value\n");
}
return 0;
}

Pointers
Int *p;
Int x=10
P=&x;
&-referencing or address of operator
*-dereferencing or value of operator
Wild /bad pointer
Int *p;
Printf(“p=%d”,*p);
Printf(“p=%p”,p);
Format specifier used are %u,%p,%x
Dangling pointer
A pointer is declared & some address also assigned to the pointer after sometime the address is
deleted but still the pointer is pointing to the same deleted memory address & value inthis case
we call the pointer as dangling pointer
#include <stdio.h>

int main()
{
int *p;
{
int a=100;
p=&a;
printf("a=%d\n",*p);
}
printf("value of a is %d\n",*p);
return 0;
}
Pointer initialization and accessing the memory address
#include <stdio.h>

int main()
{
int *p;
int var=10;
p=&var;
printf("value of variable var is %d\n",var);
printf("value of variable using pointer is %d\n",*p);
printf("Address of variable var is %p\n",&var);
printf("Address of variable var using poiinter is %p\n",p);
printf("Value of var is %d\n",*(&var));
return 0;
}
Pointe to a pointer
#include <stdio.h>

int main()
{
int num=123;
int *ptr1,**ptr2;
ptr1=&num;
ptr2=&ptr1;
printf("\nValue of num is %d\n",num);
printf("\nvalue of num using pointer is %d",*ptr1);
printf("\nvalue of num using pointer to pointer is %d",**ptr2);
printf("\n address of num is %p",&num);
printf("\n address of num using pointer is %p",ptr1);
printf("\n address of num using pointer is %p",*ptr2);
return 0;
}
Null pointer
Int *p=null;
Sizeof pointer
#include <stdio.h>

int main()
{
int *p;
int x=10;
float f=10.35f;
float *fp=&f;
p=&x;
printf("Size of int pointer is %d\n",sizeof(p));
printf("Sizde of float pointer is %d\n",sizeof(fp));
return 0;
}
Pointer we can increment or decrement
You can subtract two pointers possible
You cannot add two pointers
You cannot multiply two pointers
You cannot divide two pointers
Void pointer or generic pointer
A pointer is a variable which holds the address of another variable of same data type
If we need to store address of different data types
We have to declare that many number of pointers which increases the program size to solve this
we have what is called generic or void pointer a void poiner can store any type of address
And it is used in dynamic meory allocation
Before we use void pointer we have to go for explicit type casting
#include <stdio.h>

int main()
{
void *p;//generic or void pointer
int a=100;
float b=2.5f;
char c='x';
p=&a;
printf("The value of integer is %d\n",*(int *)p);
p=&b;
printf("The value of float is %f\n",*(float *)p);
p=&c;
printf("The value of character is %c\n",*(char *)p);
return 0;
}
Pointers can be incremented or decremented
#include <stdio.h>

int main()
{
int arr[]={10,20,30,40,50};
int *p;
int i;
p=&arr;
for(i=0;i<5;i++){
printf("%d\t",*p);
p++;
}
return 0;
}
Decrementing a pointer
#include <stdio.h>

int main()
{
int arr[]={10,20,30,40,50};
int *p;
int i;
p=&arr[4];
for(i=0;i<5;i++){
printf("%d\t",*p);
p--;
}
return 0;
}
How to subtract two pointers
Name1=1024 and name=1035
1035-1024=11/1->11
#include <stdio.h>

int main()
{
char *name="HOW ARE YOU";
char *name1;
int len;
name1=name;
while(*name!='\0'){
printf("%c",*name);
name++;
}
len=name-name1;
printf("Length of the string is %d\n",len);

return 0;

}
Array with pointer subtraction
#include <stdio.h>

int main()
{
int arr[]={10,20,30,40,50};
int *first,*last;
int len;
first=&arr[0];
last=&arr[5];
len=last-first;
printf("The number of elements in the array is %d\n",len);
return 0;

}
Call by reference using pointers
#include <stdio.h>
void salaryHike(int *var,int b);
int main()
{
int sal=0,bonus=0;
printf("Enter the salary\n");
scanf("%d",&sal);
printf("Enter the bonus\n");
scanf("%d",&bonus);
salaryHike(&sal,bonus);
printf("Final salary is :%d",sal);
return 0;

}
void salaryHike(int *var,int b){
*var=*var+b;
}
Function pointer
#include <stdio.h>
int sum(int,int);
int main()
{
int (*fp)(int,int);
int op1,op2;
fp=sum;//function pointer
op1=fp(10,20);
op2=sum(10,20);
printf("The value of addition through function pointer is %d\n",op1);
printf("the value of addition through sum function is %d\n",op2);
return 0;
}
int sum(int num1,int num2){
return num1+num2;
}
Function returning a pointer variable
Int* fun()
#include <stdio.h>
int* findLargest(int *,int *);
int main()
{
int num1,num2;
int *res;
printf("Enter the values of two numbers\n");
scanf("%d%d",&num1,&num2);
res=findLargest(&num1,&num2);
printf("the largest of two numbers is %d\n",*res);
return 0;

}
int* findLargest(int *x,int *y){
if(*x>*y)return x;
else return y;
}
Arrays & pointers relationship
#include <stdio.h>

int main()
{
int data[5],i;
printf("Enter the 5 elements of the array\n");
for(i=0;i<5;i++)scanf("%d",data+i);//data+i=>data[0]
printf("Displaying the elements of the array\n");
for(i=0;i<5;i++)printf("%d\t",*(data+i));//data[0]
return 0;

}
Dynamic memory allocation
The process of allocating memory at runtime is known as DMA
Library routines known as memory management fucntions used for allocating and freeing the
memory during execution of the program.These functions are defined in stdlib.h header file
Local variable(stack)
Free memory(heap memory) this is the area which is used for DMA
Global variable(permanent storage area)
Program instruction(PSA)
Stack variable(PSA)

Stdlib.h
Malloc() Allocates required size of bytes & returns a
void pointer to the first byte of allocated space
Calloc() Allocates space for array of elements initializes
them to zero and returns a void pointer of the
memory
Realloc() Modifies the size of the previously allocated
space
Free() Releases previously allocated memory
Malloc
If it fails in allocating memory it will return a null pointer
(Void *)malloc(byte-size)
Int *x;
X=(int *)malloc(50*sizeof(int));
Free(x);
Calloc()
Calloc normally used for derived data types such as arrays and structures
(void *)calloc(number of items,element-size);
Struct employee{
Char *name;
Int salary;
};
Typedef struct employee emp;
Emp *e1;
E1=(emp *)calloc(30,sizeof(emp));
Realloc()
(void *)realloc(pointer,new-size);
Int *x;
X=(int *)realloc(p1,50*sizeof(int));
Write a program using DMA to find the sum and average of elements of an array
#include <stdio.h>
#include <stdlib.h>
int main()
{

int *ptr,num,sum=0,i;
float average;
printf("Enter the number of elements\n");
scanf("%d",&num);
ptr=(int *)malloc(num*sizeof(int));//here only we create an array of elements
if(ptr==NULL){
printf("Unable to allocate memory\n");
exit(0);
}
printf("Enter the elements\n");
for(i=0;i<num;i++){
scanf("%d",ptr+i);
sum+=*(ptr+i);
}
average=(float)sum/num;
printf("Sum=%d\naverage=%f\n",sum,average);
return 0;
}
Write a program on how to use realloc
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *ptr1,*ptr2,i;
ptr1=(int *)malloc(2*sizeof(int));//=>arr[2] arr[0] arr[1]
*ptr1=10;//arr[0]=10
*(ptr1+1)=20;//arr[1]=20
ptr2=(int *)realloc(ptr1,3*sizeof(int));//=>arr[2] to arr[3]
*(ptr2+2)=30;//arr[2]=30
for(i=0;i<3;i++){
printf("%d\t",*(ptr2+i));//arr[0]arr[1]arr[2]
}
free(ptr1);
free(ptr2);
return 0;
}
Finding the smallest element in an array using pointers
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n,i;
int *element;
printf("enter the number of elements\n");
scanf("%d",&n);
element=(int *)calloc(n,sizeof(int));
if(element==NULL){
printf("Unable to allocate memory\n");
exit(0);
}
for(i=0;i<n;i++){
scanf("%d",element+i);//arr[0] arr[1] arr[2] arr[3] arr[4]
}
for(i=0;i<n;i++){
if(*element>*(element+i)){//arr[0]>arr[0]
*element=*(element+i);
}
}
printf("Smallest element is %d\n",*element);
return 0;
}
Write a program to allocate memory for a structure of students record dynamically and display
the records of the student
#include <stdio.h>
#include <stdlib.h>
struct student{
int id;
char name[30];
}
int main()
{
typedef struct student std;
std *s1;
int i,nor;
printf("Enter the number of records\n");
scanf("%d",&nor);
s1=(std *)malloc(nor*sizeof(std));
if(s1==NULL){
printf("Unable to allocate memory\n");
exit(0);
}
for(i=0;i<nor;i++){
printf("Enter the id and name of the student\n");
scanf("%d%s",&(s1+i)->id,&(s1+i)->name);
}
printf("Displaying the re
cords\n");
for(i=0;i<nor;i++){
printf("%d\t%s\n",(s1+i)->id,(s1+i)->name);
}
return 0;
}
Graphics programming in c
#include<graphics.h>
C is dos based application
Text mode it contains 80 columns and 25 rows
We have to convert this text mode into graphics mode by using the function intigraph()
640 * 480 pixels (h * w)
Dealy function 1000 ms = 1 s
Initgraph(int *graph driver,int *graph mode, char *path to driver);
Int gd=0/DETECT, gm
circle(col,row,radius)
/*#include<graphics.h>
#include<conio.h>
void main()
{
int gd=DETECT,gm;
initgraph(&gd,&gm,"c:\\turboc3\\bgi");
circle(500,300,80);
getch();
} */
/*
#include<graphics.h>
#include<conio.h>
#include<dos.h>
void main()
{
int gd=0,gm,i,r=5;
initgraph(&gd,&gm,"c:\\turboc3\\bgi");
for(i=0;i<=30;i++)
{
circle(320,240,r);
r=r+5;
delay(1000);
}
getch();
} */
/*
#include<graphics.h>
#include<conio.h>
void main()
{
int gd=0,gm;
int left=150,top=150,right=450,bottom=450;
initgraph(&gd,&gm,"c:\\turboc3\\bgi");
rectangle(left,top,right,bottom);
getch();
} */
/*
#include<graphics.h>
#include<conio.h>
void main()
{
int gd=0,gm;
initgraph(&gd,&gm,"c:\\turboc3\\bgi");
line(150,100,100,200);
line(100,200,200,200);
line(200,200,150,100);
getch();
} */
//Printing Random circle
/*
#include<graphics.h>
#include<dos.h>
#include<stdlib.h>
#include<conio.h>
void main()
{
int gd=0,gm;
initgraph(&gd,&gm,"c:\\turboc3\\bgi");
while(!kbhit())
{
setbkcolor(random(16));
setcolor(random(16));
circle(random(640),random(480),random(500));
delay(500);
sound(random(1500));
}
nosound();
getch();
} */
/*
#include<conio.h>
#include<graphics.h>
#include<dos.h>
#include<stdlib.h>
void main()
{
int gd=0,gm;
initgraph(&gd,&gm,"c:\\turboc3\\bgi");
line(1,1,640,480);
delay(1000);
line(1,480,640,1);
delay(1000);
rectangle(20,20,620,460);
delay(1000);
arc(320,240,0,180,100);
delay(1000);
ellipse(320,240,0,360,100,50);
getch();
} */
/*
#include<conio.h>
#include<stdio.h>
#include<graphics.h>
#include<stdlib.h>
void main()
{
int gd=0,gm,xe=320,ye=20,s=1000,touch=0;
initgraph(&gd,&gm,"c:\\turboc3\\bgi");
while(!kbhit())
{
sound(s);
ellipse(320,240,0,90,xe,ye);
ellipse(320,240,180,270,xe,ye);
if(touch==0)
{
xe-=5;
ye+=5;
if(ye>=240)
{
touch=1;
setcolor(random(16));
}
}
else{
xe+=5;
ye-=5;
if(ye<=20)
{
touch=0;
setcolor(random(16));
}
}
}
nosound();
} */
/*
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
printf("%s\n",__DATE__);
printf("%s\n",__TIME__);
printf("%s",__FILE__);
getch();
} */
/*
#include<stdio.h>
#include<conio.h>
#define PI 3.14
#define circle(r) (PI*r*r)
void main()
{
int radius;
float area;
clrscr();
printf("Enter the radius :\n");
scanf("%d",&radius);
area = circle(radius);
printf("Area = %.2f",area);
getch();
} */
//Program to print the own source code
/*#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
int c;
clrscr();
fp=fopen(__FILE__,"r");
do
{
c=getc(fp);
putchar(c);
}while(c!=EOF);
fclose(fp);
getch();
} */
/*
#include <graphics.h>
#include <dos.h>
#include <conio.h>
int main()
{
int i, j = 0, gd = 0, gm;
initgraph(&gd,&gm,"C:\\turboc3\\BGI");
settextstyle(DEFAULT_FONT,HORIZ_DIR,2);
outtextxy(25,240,"Press any key to view the moving car");
getch();
setviewport(0,0,639,440,1);
for (i = 0; i <= 420; i = i + 10, j++)
{
rectangle(50+i,275,150+i,400);
rectangle(150+i,350,200+i,400);
circle(75+i,410,10);
circle(175+i,410,10);
setcolor(j);
delay(100);
if (i == 420)
break;
clearviewport();
}
getch();
closegraph();
return 0;
} */
File handling
A file represents a sequence of bytes on the disk where a group of related data is stored.
File is created for permanent storage of data. It is a ready made structure available in stdio.h
In C programming language we use a structure poiter of file type to declare a file
FILE *fp;
C programming language provides a number of functions that helps to perform basic file
operation.
What are the functions
Fopen() Creates a new file or opens an existing file
Fclose() Closes a file
Getc() Reads a character from the file
Putc() Writes a character to a file
Fscanf() Reads a set of data from the file in formatted manner
Fprintf() Writes a set of data to the file in formatted manner
Getw() Reads an integer from the file
Putw() Writes an integer to the file
Fseek() Set the position to desired position
Ftell() Gives the current position in the file
Rewind() Sets the position to the beginning point

Fopen()
*fp=fopen(const char *filename,const char mode)
*fp is the file pointer(FILE *fp)
Fp will hold the reference to the opened or created file
Mode Description
R Open a test file in reading mode
W Opens or creates a text file in writing mode
A Opens a text file in append mode
R+ Open a file in both reading and writing mode
W+
A+
Rb Opens a binary file in read mode
Wb Opens or create a binay file in write mode
Ab Opens a binary file in append mode
Rb+
Wb+
Ab+

Fclose(fp)
Return zero on success or EOF if there is any error in closing in the file
Here the EOF(End of File is “ctrl+Z”)
Fseek(FILE *pointer,long int offset,int position)
/*#include<stdio.h>
int main()
{
FILE *fp;
char ch;
fp=fopen("two.txt","w");
clrscr();
printf("enter data.....\n");
while((ch=getchar())!=EOF)
{
putc(ch,fp);
}
fclose(fp);
fp=fopen("two.txt","r");
while((ch=getc(fp))!=EOF)
printf("%c",ch);
fclose(fp);
return 0;
} */
//Reading & Writing to file using fprintf() and fscanf()
/*
#include<stdio.h>
struct emp{
char name[30];
int age;
};
void main()
{
struct emp e1;
FILE *p,*q;
clrscr();
p=fopen("one31.txt","w");
q=fopen("one31.txt","r");
printf("Enter Name and Age :");
scanf("%s%d",&e1.name,&e1.age);
fprintf(p,"%s\n%d\n",e1.name,e1.age);
fclose(p);
fscanf(q,"%s%d",&e1.name,&e1.age);
printf("\n%s%d",e1.name,e1.age);
} */
//Program on how to use fscanf()
/*
#include<stdio.h>
int main()
{
char c[1000];
FILE *fptr;
clrscr();
if((fptr=fopen("two.txt","r"))==NULL)
{
printf("Error! opening a file");
exit(0);
}
fscanf(fptr,"%[^\n]",c);
printf("\nData from the file is :\n%s",c);
fclose(fptr);
return 0;
} */
/*#include<stdio.h>
void main()
{
char name[20]="Ravi";
int age=24,length;
FILE *fp;
clrscr();
fp=fopen("test.txt","w");
fprintf(fp,"%s%d",name,age);
length=ftell(fp);//fseek(fp,0,SEEK_END);//or u can use ftell(fp)
rewind(fp);
fscanf(fp,"%s",&name);
fscanf(fp,"%d",&age);
fclose(fp);
printf("Name :%s\n Age :%d\n",name,age);
printf("Total number of character in the file is %d",length);
} */
//Program to list the directories under the working directory
/*
#include<stdio.h>
#include<dirent.h>
int main()
{
DIR *d;
struct dirent *dir;
clrscr();
d=opendir(".");
if(d)
{
while((dir=readdir(d))!=NULL)
{
printf("%s\n",dir->d_name);
}
closedir(d);
}
return 0;
} */
//Program to find the size of any file
/*
#include<stdio.h>
void main()
{
FILE *fp;
char ch;
int size=0;
clrscr();
fp=fopen("one.txt","r");
if(fp==NULL)
{
printf("\nFile unable to open...");
}else{
printf("\nFile opened...");
}
fseek(fp,0,SEEK_END);
size=ftell(fp);
printf("The size of the given file is:%d\n",size);
fclose(fp);
} */
//Program to write into a binary file
/*
#include<stdio.h>
#include<stdlib.h>
struct num{
int n1,n2,n3;
};
int main()
{
int i;
struct num nu1;
FILE *fptr;
clrscr();
if((fptr=fopen("program.bin","wb"))==NULL)
{
printf("Error opening the file\n");
exit(1);
}
for(i=1;i<5;i++)
{
printf("Enter the values of n1,n2 and n3\n");
scanf("%d",&nu1.n1);//nu1.n1=i;
scanf("%d",&nu1.n2);//nu1.n2=5*i;
scanf("%d",&nu1.n3);//nu1.n3=5*i+1;
fwrite(&nu1,sizeof(struct num),1,fptr);
}
fclose(fptr);
if((fptr=fopen("program.bin","rb"))==NULL)
{
printf("Error reading the file\n");
exit(0);
}
for(i=1;i<5;i++)
{
fread(&nu1,sizeof(struct num),1,fptr);
printf("n1 : %d\tn2 : %d\tn3 : %d\n",nu1.n1,nu1.n2,nu1.n3);
}
fclose(fptr);
return 0;
} */
/*#include<stdio.h>
#include<stdlib.h>
void main()
{
int arr[]={10,20,30,40};
int arr1[4];
int i;
FILE *fp;
fp=fopen("arun.dat","wb");
fwrite(arr,sizeof(arr),1,fp);
fclose(fp);
fp=fopen("arun.dat","rb");
fread(&arr1,sizeof(arr),1,fp);
for(i=0;i<4;i++)printf("%d\t",arr1[i]);
} */

/*#include<stdio.h>
#include<string.h>
void main()
{
FILE *fp;
char buf[250];
clrscr();
fp=fopen("Test.txt","w");
strcpy(buf,"Hello world! Welcome arun...\n");
fprintf(fp,"%s",buf);
fclose(fp);
fp=fopen("Test.txt","r");
while(fscanf(fp,"%s",buf)!=EOF){
printf("%s",buf);
}
fclose(fp);
} */

Command line arguments


It’s the process of sending arguments to the main function from command prompt
It will be useful whenever we design application for Dos based environment
The main function by default has 2 arguments
1)int argc->count of the number of arguments entered at command prompt including the file
name
2)char *argv[]->is a string array pointerwhich stores the arguemnts entered at the command
prompt
Write a program to count and print the number of argumets
Finding sum of numbers using command line arguments
Conditional compilation
#if
#elsif
#endif

/*#include<stdio.h>
#define circleArea(r) (3.14*r*r) //userdefined macros
void main()
{
int radius;
float area;
clrscr();
printf("Enter the radius of the circle\n");
scanf("%d",&radius);
area=circleArea(radius);
printf("Area = %.2f",area);
} */
/*#include<stdio.h>
#define PI 3.14//here PI is called as symbolic constant
float circleArea(int radius);
void main()
{
int radius;
float area;
clrscr();
printf("Enter the radius of the circle\n");
scanf("%d",&radius);
area=circleArea(radius);
printf("The area of circle is %f\n",area);
}
float circleArea(int radius)
{
float area;
area=PI*radius*radius;
return area;
} */
//Inbuilt macros
/*#include<stdio.h>
void main()
{
clrscr();
printf("Date is %s\n",__DATE__);
printf("Time is %s\n",__TIME__);
} */
/*#include<stdio.h>
void main()
{
clrscr();
printf("%s\n",__FILE__);
} */
//Program to print the files own source code
/*#include<stdio.h>
void main()
{
FILE *fp;
char c;
clrscr();
fp=fopen(__FILE__,"r");
do{
c=getc(fp);
putchar(c);
}while(c!=EOF);
fclose(fp);
} */

You might also like