C Programming
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>
#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]
●
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;
}
●
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 *b; b 99 b 67 78 56 88 90 34 85
1000 1002 1004 1006 1008 1010 1012 1014
200
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)
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]
String length
String
a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9]
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;
};
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;
}; };
20B 4B 20B
a union is a collection of variables of
different data types share a single
block of memory
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
enum tag_name {
enumeration_list
} variable_list;
enum Data Type
int d2;
d2=TUE;
enum Data Type
●
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.
●
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
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]
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()
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;
}