0% found this document useful (0 votes)
3 views

C Programming

The document discusses comments, multi-way decision statements, switch case statements, and arrays in C programming. Comments are lines of code that are not executed but are used to explain or annotate code. Multi-way decision statements and switch case statements are used to select between multiple blocks of code to execute based on conditions. Arrays allow storing and accessing related data elements through indexes and can be used to simplify code when dealing with multiple variables of the same type.

Uploaded by

2106319
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

C Programming

The document discusses comments, multi-way decision statements, switch case statements, and arrays in C programming. Comments are lines of code that are not executed but are used to explain or annotate code. Multi-way decision statements and switch case statements are used to select between multiple blocks of code to execute based on conditions. Arrays allow storing and accessing related data elements through indexes and can be used to simplify code when dealing with multiple variables of the same type.

Uploaded by

2106319
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 71

C Programming

COMMENTS


Comments are specially marked lines of text in the program that are not evaluated
– Single line of comment:
● // comment here
– Multiple line Comments:
● /* comment here

line two */

// Author: xyz
#include <stdio.h>

/* main() function, where program


execution starts */
int main()
{
int i; // used for roll no
Return 0;
}
Multi-way Decision Statement

#include<stdio.h>
if(condition_1) int main()
{
int day;
statement_1; “);
printf(“\n Enter any number from 1 to 7 :

scanf(“%d”,&day);
else if (condition_2) if(day==1){
printf(“\n SUNDAY”);
statement_2; }else if(day==2){
printf(“\n MONDAY”);
}else if(day==3){
else if(condition_3) printf(“\n TUESDAY”);
}else if(day==4){
printf(“\n WEDNESDAY”);
statement_3; }else if(day==5){
printf(“\n THURSDAY”);
}else if(day==6){
else printf(“\n FRIDAY”);
}else if(day==7){
printf(“\n SATURDAY”);

statement_4; }else{
printf(“\n Wrong Number”);
}

next_statement; }
return 0;
Switch Case

A switch case statement is a multi-way decision statement.

It is used when there is only one variable to evaluate in the expression

test condition only use integer (or character) constants.
switch(<expression>) #include<stdio.h>
int main()
{ {
int day;
case <Value_1> : printf(“\n Enter any number from 1 to 7 : “);
scanf(“%d”,&day);
statement(s); switch(day)
{
break; case 1:
case <Value_2> : printf(“\n SUNDAY”);
break;
statement(s); case 2 :
printf(“\n MONDAY”);
break; break;
case 3 :
case <Value_3> : printf(“\n TUESDAY”);
break;
statement(s); case 4 :
break; printf(“\n WEDNESDAY”);
break;
… case 5 :
printf(“\n THURSDAY”);
… break;
case 6 :
case <Value_n> : printf(“\n FRIDAY”);
break;
statement(s); case 7 :
break; printf(“\n SATURDAY”);
break;
default : default:
printf(“\n Wrong Number”);
statement(s); }
return 0;
} }
Switch Case

#include <stdio.h>

int main() {
int number;
Scanf(“%d”,&number);
switch (number) {
case 1:
case 2:
case 3:
printf("One, Two, or Three.\n");
break;
case 4:
case 5:
case 6:
printf("Four, Five, or Six.\n");
break;
default:
printf("Greater than Six.\n");
}
}
Array
Can you imagine how long we have to write
the declaration part by using normal variable
declaration?

int main(void)
{
int mark1, mark2, mark3, mark4, …, …, mark998,
stuMark999, mark1000;
scanf(“%d”, &mark1); We cannot also use any loop
scanf(“%d”, &mark2); For mark1, mark2, …
… Because each variable
has different name
printf(“%d”, mark1);
printf(“%d”, mark1);


return 0;
}
Array

int mark[10];
1st 2nd 3rd 4th 5th 6th 7th 8th 9th 10th
element element element element element element element element element element

mark[0] mark[1] mark[2] mark[3] mark[4] mark[5] mark[6] mark[7] mark[8] mark[9]

int main(void) int main(void)


{ {
int mark[10]; int mark[10];
int I;
scanf(“%d”, &mark[0]); for(i=0;i<10;i++){
scanf(“%d”, &mark[1]); scanf(“%d”, &mark[i]);
… }
printf(“%d”, mark[0]);
printf(“%d”, mark[1]); for(i=0;i<10;i++){
printf(“%d”, mark[i]);
}
… …
} }
Array


An array is a collection of similar data elements.

The elements of the array are stored in consecutive memory
locations and are referenced by an index starts with 0
99 67 78 56 88 90 34 85
mark[0] mark[1] mark[2] mark[3] mark[4] mark[5] mark[6] mark[7]
1000 1002 1004 1006 1008 1010 1012 1014

int mark[8];

Declaration of an array mainly contains three things:
– data type : int
– Name of the : mark
– Number of elements : 8 (index : 0 to 7)
Array
int main(void) int main(void)
{ {
int mark[5]; int mark[5]={2,4,5,12,3};
int i; int i;
for(i=0 ; i<5 ; i++){
scanf(“%d”, &mark[i]); for(i=0 ; i<5 ; i++){
} printf(“%d”, mark[i]);
}
for(i=0 ; i<5 ; i++){ return 0;
printf(“%d”, mark[i]); }
}
return 0;
}

int main(void) int main(void)


{ {
int mark[5]; int mark[5]={2,4,5,12,3};
int I, sum=0; int I, sum=0;
for(i=0 ; i<5 ; i++){
scanf(“%d”, &mark[i]); for(i=0 ; i<5 ; i++){
} sum=sum+mark[i];
for(i=0 ; i<5 ; i++){ }
sum=sum+mark[i]; printf(“%d”, sum);
} return 0;
printf(“%d”, sum); }
return 0;
}
Problems


Display the array in reverse order.

Find the smallest element in an array.

Write a program to interchange the biggest and the smallest
number in the array.

Write a program to find the mean of n numbers using arrays.

Write a program to search an element in an array.

Write a program to merge two integer arrays. Also display the
merged array in reverse order.

Write a program to insert a number in an array.(either in
sorted array or in an unsorted array by index)

Write a program to delete a number from an array.
Inserting an Element
(26,5)

15 12 7 8 45 7 8 9
0 1 2 3 4 5 6 7 8 9
i

15 12 7 8 45 26 7 8 9
0 1 2 3 4 5 6 7 8 9
Deleting an Element
5

15 12 7 8 45 7 8 9
0 1 2 3 4 5 6 7 8 9
i

15 12 7 8 45 8 9
0 1 2 3 4 5 6 7 8 9
Array & Function
int main(void) void display(int data[], int size){
{ int i;
int mark[5]={12, 34, 35, 14, 57}; for(i=0 ; i<size ; i++){
int i; printf(“%d”, data[i]);
for(i=0 ; i<5 ; i++){ }
printf(“%d”, mark[i]); }
} int main(void) {
return 0; int mark[5]={12, 34, 35, 14, 57};
} display(mark,5);
return 0;
}

int main(void) int total(int data[], int size){


{ int i,sum=0;
int mark[5]={12, 34, 35, 14, 57}; for(i=0 ; i<5 ; i++){
int I,sum=0; sum=sum + data[i];
for(i=0 ; i<5 ; i++){ }
sum=sum+mark[i]; return sum;
} }
printf(“Total=%d”, sum); int main(void) {
return 0; int mark[5]={12, 34, 35, 14, 57};
} int sum;
sum = total(mark,5);
printf(“Total=%d”, sum);
return 0;
}
Array & Pointer
int a=5; a 5
100 0 1 2 3 4 5 6 7

int *b; b 99 b 67 78 56 88 90 34 85
1000 1002 1004 1006 1008 1010 1012 1014
200

b=&a; 100 int a[8]; a[3] => 56


200
a[0] => 99 *(1006) => 56
b => 100
*(1000) => 99 *(1000 + 3) => *(1000 + 3 X 2) => 56
*b => *(b) => *(100) => 5
*(1000 + 0) => 99
b+1 = b + 1 X sizeof(int)
=b+1X2 a => 1000
= 100 + 2 = 102
a is the address of the first element of the array => 1000

a[i] => *(a + i)


Array & Pointer
void modify(int data[], int size){ data 1000 size 5
int i;
Data[3] => *(data+3) => *(1000 + 3 X 2) => *(1006)
data[3] = 54;
data[1] = data[1] + 10; 0 1 2 3 4
mark 12 b 44 35 54 57
}
1000 1002 1004 1006 1008
int main(void) {
0 1 2 3 4
int mark[5]={12, 34, 35, 14, 57}; mark 12 b 34 35 14 57
modify(mark,5); 1000 1002 1004 1006 1008

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


printf(“%d ”, mark[i]); 12 44 35 54 57
}
return 0;
}
TWO DIMENSIONAL ARRAYS
Column
0 1 2

It has two subscripts 0
a(0,0) (0,1) (0,2)
1000 1002 1004
– one subscript denotes row 1 (1,0) (1,1) (1,2)

Row
1006 1008 1010
– the other denotes column.
2 (2,0) (2,1) (2,2)

Declaration 1012 1014 1016
3 (3,0) (3,1) (3,2)
– int a[4][3]; 1018 1020 1022

– Int a[4][3]={ 5 3 7
{5,3,7},
{6,8,2}, 6 8 2
{1,7,9},
{3,5,6} 1 7 9
};
3 5 6
TWO DIMENSIONAL ARRAYS
Column
0 1 2
a[0][0] a[0][1] a[0][2]
0 3 7
5
A[0][0] for(j=0 ; j<3 ; j++){

Row
A[0][1] printf(“%d”, a[0][j]); 1 a[1][0] a[1][1] a[1][2]
6 8 2
A[0][2]
}
2 a[2][0] a[2][1] a[2][2]
1 7 9
A[1][0] for(j=0 ; j<3 ; j++){
3 a[3][0] a[3][1] a[3][2]
A[1][1] printf(“%d”, a[1][j]); 3 5 6
A[1][2]
}
for(i=0 ; i<4 ; i++){
A[2][0] for(j=0 ; j<3 ; j++){ for(j=0 ; j<3 ; j++){
A[2][1] printf(“%d”, a[2][j]); printf(“%d”, a[i][j]);
A[2][2]
} }
}
A[3][0] for(j=0 ; j<3 ; j++){
A[3][1] printf(“%d”, a[3][j]);
A[3][2]
}
TWO DIMENSIONAL ARRAYS
int I,j; Column
0 1 2
for(i=0 ; i<4 ; i++){
for(j=0 ; j<3 ; j++){
a[0][0] a[0][1] a[0][2]
0 3 7
printf(“%d”, a[i][j]);
5

Row
} 1 a[1][0] a[1][1] a[1][2]
6 8 2
}
2 a[2][0] a[2][1] a[2][2]
1 7 9
int I,j; 3 a[3][0] a[3][1] a[3][2]
3 5 6
for(i=0 ; i<4 ; i++){
for(j=0 ; j<3 ; j++){ int I,j, sum=0;
scanf(“%d”, &a[i][j]); for(i=0 ; i<4 ; i++){
} for(j=0 ; j<3 ; j++){
} sum=sum+a[i][j];
}
}
TWO DIMENSIONAL ARRAYS
Column
0 1 2 3
a[0][0] a[0][1] a[0][2] a[0][3]
0 3 7 4
5

Row
1 a[1][0] a[1][1] a[1][2] a[1][3]
6 8 2 8
2 a[2][0] a[2][1] a[2][2] a[2][3]
1 7 9 1
3 a[3][0] a[3][1] a[3][2] a[3][3]
3 5 6 2
Problems


Write a program to find the sum of elements present in
each individual row and column.

Write a program to find the sum of elements present in
each diagonal.

Write a program to fill a square matrix with value zero
on the diagonals, 1 on the upper right triangle, and -1
on the lower left triangle.

Write a menu-driven program to read and display an m
X n matrix. Also find the sum, transpose, and product of
two m X n matrices.

Write a program to read and display a 2 X 2 X 2 array.
Matrix Multiplication
A (3 X 4) B (4 X 2)

(0,0) (0,1) (0,2) (0,3) (0,0) (0,1) sum=0;


(1,0) (1,1) for(k=0 ; k<4 ; k++){
(1,0) (1,1) (1,2) (1,3)
(2,0) (2,1) Sum = sum+A[i][k] * B[k][j];
(2,0) (2,1) (2,2) (2,3) (3,0) (3,1) }
C[i][j]=sum;

C (3 X 2) k
i j
(0,0) (0,1) A B
(1,0) * (0,0) for(i=0 ; i<3 ; i++){
(1,1) * (1,0)
(1,0) (1,1) (1,2) * (2,0) for(j=0 ; j<2 ; j++){
(1,3) * (3,0)
(2,0) (2,1) ---------------
(1,0) }
i C j
}
int main(void){ int main(void){
int i; int i;
for(i=0;i<5;i++){ for(i=0;i<5;i++){
printf(“A ”); AAAAA printf(“A ”); ABABABABAB
} printf(“B ”);
return 0; }
} return 0;
}
int main(void){
int i; int main(void){
for(i=0;i<5;i++) int i;
printf(“A ”); AAAAA for(i=0;i<5;i++)
return 0; printf(“A ”); AAAAAB
} printf(“B ”);

return 0;
}
String


A string is a null-terminated “abcd”
character array ‘a’ ‘b’ ‘c’ ‘d’ ‘\0’

Declaration
– char <name>[size];
– Example

char str[10]; str[0] str[1] str[2] str[3] str[4] str[5] str[6] str[7] str[8] str[9]

char str[10]=”good”; str ‘g’ ‘o’ ‘o’ ‘d’ ‘\0’
100 101 102 103 104 105 106 107 108 109

Read String
– scanf(“%s”,str);

Write String
– printf(“%s”,str);
String
int main(void)
int main(void) {
{ char str[10] = ”good”;
char str[10]; printf(“%s”,str);
scanf(“%s”,str); return 0;
printf(“%s”,str); }
return 0;
}

int main(void)
{
char str[10]; str[0] str[1] str[2] str[3] str[4] str[5] str[6] str[7] str[8] str[9]

scanf(“%s”,str); str ‘g’ ‘o’ ‘o’ ‘d’ ‘\0’


for(i=0 ; str[i]!=’\0’ ; i++) 100 101 102 103 104 105 106 107 108 109
;
printf(“SIZE=%d”,i);
return 0;
}

String length
String
a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9]

a ‘g’ ‘o’ ‘o’ ‘d’ ‘\0’


int main(void)
b[0] b[1] b[2] b[3] b[4] b[5] b[6] b[7] b[8] b[9] {
b ‘d’ ‘a’ ‘y’ ‘\0’ char a[10], b[10], c[10];
int i, k=0;
c[0] c[1] c[2] c[3] c[4] c[5] c[6] c[7] c[8] c[9] scanf(“%s”,a);
c ‘g’ ‘o’ ‘o’ ‘d’ ‘d’ ‘a’ ‘y’ ‘\0’ scanf(“%s”,b);
for(i=0 ; a[i]!=’\0’ ; i++){
c[k]=a[i];
k++;
}
for(i=0 ; b[i]!=’\0’ ; i++){
c[k]=b[i];
k++;
}
c[k]=’\0’;

printf(“%s”,c);
return 0;
}
Concatenate two Strings
Problems on String


NOTE:
– to receive a string without space

scanf(“%s”,a);
– to receive a string without space

gets(a);
– You can also directly initialize string during declaration

char a[100]=”asdf gh jkl vbcz”;

Write a program to find the length of a string.

Write a program to convert characters of a string to upper case. (Do the reverse also)

Write a program to concatenate two Strings.

Write a program to reverse the given string.

Write a program to compare two strings.

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

Write a program to extract certain range of characters of a string. (Range is from one position to another position)

Write a program to insert a string at the particular position of the the main text.

Write a program to display position of the substring in the main string.

Wriote a program to remove all the extra space in a text.

Write a program to delete a substring from a text.

Write program to display all the words present in the string.

Write a program to remove all the continuous duplicate letters present in the string.

Write a program to replace a pattern with another pattern in the text. (similar to find and replace)

Write a program to enter a string. Then enter a new string. Then find whether the new string is the sub-string of the original string.
Structure

Read the student information such as name, roll
no, mark in subject-1, mark in subject-2,
semester.
int main(void)
{
char name[10];
int rollno;
float mark1, mark2;
int sem;
scanf(“%s”,name);
scanf(“%d”,&rollno);
scanf(“%f%f”,&mark1,&mark2);
scanf(“%d”,&sem);

printf(“%s : %d : %d : %f : %f” ,
name,rollno,sem,mark1,mark2);
return 0;
}
Data type
Structure
struct stu
{ scanf(“%s”,s1.name);
char name[10]; scanf(“%d”,&s1.rollno);
int rollno; Member scanf(“%d”,&s1.mark1);
float mark1, mark2; variable
int sem; printf(“%d”,s1.rollno);
}; printff(“%s”,s1.name);
User Defined data type
whose name is “struct stu”

Variable of
struct stu s1, s2; struct stu
Structure is basically a user
defined data type that can
s1.name
s1.rollno store related information
. (even of different data types)
. together.
S2.name
Structure
struct stu
{
char name[10];
int rollno;
float mark1, mark2;
int sem;
};

struct stu s1={“ABC”,190,23.4,64.5,2};



Write a program to enter two points and then
calculate the distance between them.

Write a program to read, display, add, and subtract
two time defined using hour, minutes, and values of
seconds.

Write a program to read and display the information
of all the students in the class. Then edit the details
of the ith student and redisplay the entire
information.

Write a program to read and display information of a
student, using a structure within a structure.

STRUCTURE

struct stu struct stu


{ {
char name[10]; char name[10];
int rollno; int rollno;
float mark1; float mark1;
int dob_dd; int dob_dd;
int dob_mm; int dob_mm;
int dob_yy; int dob_yy;
}; } s1, s2;

struct stu s1,s2;


NESTED STRUCTURES
struct stu
struct stu {
{ char name[10];
char name[10]; int rollno;
int rollno; float mark1;
float mark1; struct dt{
int dob_dd; int dob_dd;
int dob_mm; int dob_mm;
int dob_yy; int dob_yy;
}; }db;
};
struct stu s1; struct stu s1;

s1.name s1.name
s1.rollno s1.rollno
s1.mark1 s1.mark1
s1.dob_dd s1.db.dob_dd
s1.dob_mm s1.db.dob_mm
s1.dob_yy s1.db.dob_yy
NESTED STRUCTURES
struct stu struct dt{
{ int dob_dd;
char name[10]; int dob_mm;
int rollno; int dob_yy;
float mark1; };
struct dt{ struct stu
int dob_dd; {
int dob_mm; char name[10];
int dob_yy; int rollno;
}db; float mark1;
}; struct dt db;
};
struct teacher
{ struct teacher
char name[10]; {
int emp_id; char name[10];
struct dt{ int emp_id;
int dob_dd; struct dt db;
int dob_mm; };
int dob_yy;
}db;
};
NESTED STRUCTURES
struct stu struct dt{
{ int dob_dd;
char name[10]; int dob_mm;
int rollno; int dob_yy;
float mark1; };
struct dt{ struct stu
int dob_dd; {
int dob_mm; char name[10];
int dob_yy; int rollno;
}db; float mark1;
}; struct dt db;
};
struct stu s1;
struct stu s1;
s1.name
s1.rollno s1.name
s1.mark1 s1.rollno
s1.db.dob_dd s1.mark1
s1.db.dob_mm s1.db.dob_dd
s1.db.dob_yy s1.db.dob_mm
s1.db.dob_yy
Structure & pointer
struct dt{
int dob_dd;
int dob_mm;
int a=5; a 5 int dob_yy;
100 };
int *b; b struct dt d1={23,4,2020}; d1 23 | 4 | 2020
200
250
b=&a; 100 p
Struct dt *p;
200 300
b => 100 p=&d1; p 250
300
*b => *(b) => *(100) => 5
p->dob_dd : 23
p->dob_mm : 4
p->dob_dd : 2020

d1.dob_dd : 23
d1.dob_mm : 4
d1.dob_dd : 2020
Structure & Function
struct point{ struct point{
int x; int x;
int y; int y;
}; };

void display(struct point p){ void display(struct point *p){


printf(“%d %d”, p.x, p.y); printf(“%d %d”, p->x, p->y);
} }
Int main(){ Int main(){
struct point p1={23,5}; struct point p1={23,5};
display(p1); display(&p1);
return 0; return 0;
} }
void display(int p){ void display(int *p){
printf(“%d”, p); printf(“%d”, *p);
} }
Int main(){ Int main(){
int p1=5; int p1=5;
display(p1); display(&p1);
return 0; return 0;
} }
Array of Structure
struct stu s[5];
struct stu s[0].name
{ s[0].rollno
char name[10]; s[0].mark1
int rollno; s[0].mark2
float mark1, mark2; s[0].sem
int sem;
}; s[1].name
s[1].rollno
struct stu s; s[1].mark1
s.name s[1].mark2
s.rollno s[1].sem
smark1
s.mark2
s[0] s[1] s[2] s[3] s[4]
s.sem
s
Union
struct stu union stu
{ {
char name[20]; char name[20];
int rollno; int rollno;
}; };

20B 4B 20B
a union is a collection of variables of
different data types share a single
block of memory

struct stu s1; union stu s1;

s1.name s1.name
s1.rollno s1.rollno
Union
struct student
{
union identification 20B 4B 4B
{ id mark sem
char name[20];
int rollno; s1
}id;
int mark;
int sem; struct student s1;
};
s1.id.name Only one will be
s1.id.rollno used at a time
s1.mark
s1.sem
Union
union data
{ 00101000 100
a/b
char a; 4B
int b; 00000001 101
a/b
}; 00000000 102
d1
00000000 103
union data d1;
d1.b = 295;
printf(“%d”,d1.a); 40

296 <=> 00000000000000000000000100101000


enum Data Type
enum is used to declare named integer constants.

if(1){ enum ownconst {


printf(“YES”); FALSE,
} TRUE
};
Not correct
if(TRUE){ if(TRUE){
printf(“YES”); printf(“YES”);
} }

enum tag_name {
enumeration_list
} variable_list;
enum Data Type

enum days{ Size of enum data type


SUN, 0 is same as size of int
MON, 1 data type
TUE, 2
WED, 3
THU, 4
FRI, 5
SAT 6
};

enum days d1;


d1=MON;
d1=12;

int d2;
d2=TUE;
enum Data Type

enum days{ enum days{


SUN, 0 SUN=5, 5
MON=4, 4 MON=2, 2
TUE, 5 TUE, 3
WED, 6 WED=1, 1
THU, 7 THU, 2
FRI, 8 FRI, 3
SAT 9 SAT 4
}; };
Scope of the Variable


Visibility of the variables

Type void display(int p){
int i=5;
– Block Scope printf(“%d”, i);
}
– Function Scope
Int main(){
– Program Scope int k = 7;
printf(“%d”, i);
– File Scope printf(“%d”, k);
} i is out
side its
scope
Block Scope

A block refers to any sets of statements inside braces
{ and }.

A variable declared inside a block has block scope.

int main(){ int main(){


int i=5; int i=5;
printf("%d\n",i); 5 printf("%d\n",i); 5
{ {
int j=6; int j=6,i=3;
printf("%d\n",i); 5 printf("%d\n",i); 3
printf("%d\n",j); 6 printf("%d\n",j); 6
} }
printf("%d\n",i); 5 printf("%d\n",i); 5
printf("%d",j); return 0;
return 0; }
}
Function Scope

It is active and visible from the beginning to the end of a function.

Only the goto label has function scope.

Goto satement and its corresponding label must be in the same
function.
int main()
{
int i; /* block scope */
.
.
mylb: /* function scope */
.
.
goto mylb;
.
.
return 0;
}
Program Scope

It is declared outside a function
and accessible through out the int x = 2; /* program scope */
float y = 4.5; /* program scope */
whole program.

These variable are referred as void count(){
global variable. printf(“%d, %f\n”,x,y); 2, 4.5
}
int x = 0; /* program scope */
int main()
void count(){ {
x++; int x=6; /* block scope */
} count();
printf(“%d, %f\n”,x,y); 6, 4.5
int main() {
{ int y=8.5; /* block scope */
x++; printf(“%d, %f\n”,x,y); 6, 8.5
count(); }
printf(“%d”,x); 2 return 0;
return 0; }
}
File Scope

a global variable declared with the static specifier is said to
have file scope.

But a global variable without static can be accessed outside
of a file.
b.c a.c
int x=4; int main(){
static int y=7; /* file scope */ extern int x;
void dis(){ extern int y;
printf("%d, %d\n",x,y); printf("%d, %d\n",x); 4
} printf("%d, %d\n",y);
return 0;
}
Storage Class


It gives the scope (visibility) of variables

It gives life time of variables and/or functions.

It determines which part of the storage space will be allocated for that
variable or function.

It gives whether the variable will be automatically initialized or not.

Types
– auto specifier
– static specifier
– register specifier
– extern specifier
auto specifier

Accessible within the function or block in which it is declared

Exists when the function or block in which it is declared is
entered. Ceases to exist when the control returns from the
function or the block in which it was declared

By default the a variable with block scope is auto type.
void count(){
auto int x = 1;
x++;
printf(“%d”,x); 2 2
}

int main()
{
count();
count();
return 0;
}
static specifier

Local
– Accessible within the function or block in which it is declared
– Retains value between function calls or block entries
– automatically initialized
void count(){
static int x = 1;
x++;
printf(“%d”,x); 2 3
}

int main()
{
count();
count();
return 0;
}
static specifier

Global
– Accessible within the file in which it is declared
– Retains value
– automatically initialized
static int x = 1;
void count(){
x++;
printf(“%d”,x); 3 4
}

int main()
{
x++;
count();
count();
return 0;
}
register Specifier

Stores variables in registers (not guaranteed) may help to speed up your
program.

Accessible within the function or block in which it is declared

Exists when the function or block in which it is declared is entered. Ceases
to exist when the control returns from the function or the block in which it
was declared

It's illegal to take the address of a register variable.
int main()
{
register int i;
...
for (i=0; i<MAX; i++){
/* some statements */
}
...
return 0;
}
extern Specifier

The extern specifier provides a reference to a
global variable defined elsewhere.

The extern specifier declares outside or inside
the function
b.c a.c
int x=4; extern int x;
void dis(){
printf("%d \n",x); int main(){
} printf("%d, %d\n",x); 4
return 0;
}
STORAGE CLASS
FEATURE
Auto Extern Register Static

Local: Accessible
within the function
Accessible within or block in which it is
Accessible within the Accessible within the
all program files declared
Accessibility function or block in function or block in
that are a part of Global: Accessible
which it is declared which it is declared
the program within the program
in which it is
declared

Storage Main Memory Main Memory CPU Register Main Memory

Exists when the


Exists when the function function or block in
Local: Retains value
or block in which it is which it is declared is
between function
declared is entered. Exists throughout entered. Ceases to
calls or block entries
Existence Ceases to exist when the the execution of exist when the control
Global: Preserves
control returns from the the program returns from the
value in program
function or the block in function or the block
files
which it was declared in which it was
declared

Default
Garbage Zero Garbage Zero
value
Constant Codifier


A variable with the const modifier, the content of
the variable cannot be changed after it is
initialized.

int main()
{
const int i=5;
i=9;

return 0;
}
Dynamic Memory Allocation

int main()
{
int data[5];
int no;
printf(“Enter no of elements:”); If no is more Can you
scanf(“%d”,&no); than 5, then change the NO!!!
for(i=0;i<no;i++) what will array size?
scanf(“%d”,&data[i]); happen?
return 0; Allocate the
} memory at
run time.

Dynamic
memory
allocation
Dynamic Memory Allocation


How to allocate memory during run time? p[i] = *(p+i)
– malloc(),calloc(),realloc(),andfree()
You can feel that p
is a character array
#include <stdlib.h> char *p; having 10 elements.
void *malloc(size_t size); p=malloc(10);

p[0] p[1] p[2] p[3] p[4] p[5] p[6] p[7] p[8] p[9]

Returns starting How many


address of the Bytes of 100 101 102 103 104 105 106 107 108 109
allocated memory to be
memory allocated
char *p;
int no;
printf(“Enter no of elements:”);
scanf(“%d”,&no);
p=malloc(no);
Dynamic Memory Allocation
int *p; int *p;
int no; int no,i;
printf(“Enter no of elements:”); printf(“Enter no of elements:”);
scanf(“%d”,&no); scanf(“%d”,&no);
p=malloc(no * sizeof(int)); p=malloc(no * sizeof(int));
for(i=0;i<no;i++){
p[i]=i+2;
5 }
int *p; sizeof(int)
p=malloc(10); =2 bytes int *p;
p=malloc(10);
p[0] p[1] p[2] p[3] p[4] free(p);

100 102 104 106 108 This will free the


allocated memory
p+1 = p+ 1 * sizeof(int)
Dynamic Memory Allocation

Use of calloc()
int *p;
int no,i; #include <stdlib.h>;
printf(“Enter no of elements:”);
void *calloc(size_t nmemb, size_t size);
scanf(“%d”,&no);
p=malloc(no * sizeof(int));
for(i=0;i<no;i++){ Number Size of
p[i]=0; of each
} element element

int *p;
int no,i;
printf(“Enter no of elements:”);
Unlike malloc, in
scanf(“%d”,&no);
calloc the memory is
automatically set to p=calloc(no, sizeof(int));
zero.
Dynamic Memory Allocation
Use of realloc()

#include <stdlib.h>; realloc() changes the size


of the memory block
void *realloc(void *ptr, size_t size) pointed to by ptr to size
bytes.

Pointer pointing to existing New


allocated memory memory size

char *p;
int no,i;
printf(“Enter no of elements:”);
scanf(“%d”,&no);
p=malloc(no); p 4 6 12 3
. . .
printf(“Enter new no of elements:”);
scanf(“%d”,&no);
p=realloc(p, no); p 4 6 12 3
File Handling


File is a collection of data mostly stored in secondary storage.

Basic operations on File
– Open
– Close
– Read
– Write

File types
– Text

contains ASCII characters only
– Binary

can contain non-ASCII characters

Ex: image file, executable file, etc.
Open and Close a File


Before performing any operations on a file, we need to
open it.
– fopen()

After performing operations on a file, we need to close it.
– fclose()

Modes of opening a file
r Open a text file for reading rb Open a binary file for reading

w Create a text file for writing, if it wb Create a binary file for writing, if it exists,
exists, it is overwritten. it is overwritten.

a Open a text file and append text to ab Open a binary file and append data to
the end of the file. the end of the file.
Open and Close a File
#include <stdio.h> Name of the file
int main (){
FILE *fp; Opening mode
fp = fopen("a1.txt", "r");
if (fp == NULL) {
printf("Error in file opening!\n");
exit(0);
}
fclose(fp);
return 0;
}
Read a File
#include <stdio.h>
#include <stdio.h>
int main (){
int main (){
FILE *fp;
FILE *fp;
char c;
char c;
fp = fopen("a1.txt", "r");
fp = fopen("a1.txt", "r");
if (fp == NULL) exit(0);
if (fp == NULL) {
while(1){
printf("Error in file opening!\n");
c=fgetc(fp);
exit(0);
Read one if(c==EOF) break;
}
character through printf(“%c”,c);
c=fgetc(fp); fp pointer
}
fclose(fp);
fclose(fp);
return 0;
return 0;
}
}
Write to a File
#include <stdio.h>
int main (){
FILE *fp;
char c;
fp = fopen("a1.txt", "w");
if (fp == NULL) {
printf("Error in file opening!\n");
exit(0);
} Write one
character through
fputc(‘J’,fp); fp pointer
fclose(fp);
return 0;
}
Copy a File
#include <stdio.h>
int main (){
FILE *fp, *fp1;
char c;
fp = fopen("a1.txt", "r");
fp1 = fopen("a2.txt", "w");
if (fp == NULL || fp1 == NULL) exit(0);
while(1){
c=fgetc(fp);
if(c==EOF) break;
fputc(c,fp1);
}
fclose(fp);
fclose(fp1);
return 0;
}
Copy a Image File
#include <stdio.h>
#include <stdlib.h>
int main (){
FILE *fp, *fp1;
char c[1];
fp = fopen("kiit.jpeg", "rb");
fp1 = fopen("test.jpeg", "wb");
if (fp == NULL || fp1 == NULL) exit(0);
while(!feof(fp)){
fread(c,1,1,fp);
fwrite(c,1,1,fp1);
}
fclose(fp);
fclose(fp1);
return 0;
}

You might also like