C language concept with code apna college.pdf

mhande899 6,503 views 90 slides Mar 30, 2024
Slide 1
Slide 1 of 145
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41
Slide 42
42
Slide 43
43
Slide 44
44
Slide 45
45
Slide 46
46
Slide 47
47
Slide 48
48
Slide 49
49
Slide 50
50
Slide 51
51
Slide 52
52
Slide 53
53
Slide 54
54
Slide 55
55
Slide 56
56
Slide 57
57
Slide 58
58
Slide 59
59
Slide 60
60
Slide 61
61
Slide 62
62
Slide 63
63
Slide 64
64
Slide 65
65
Slide 66
66
Slide 67
67
Slide 68
68
Slide 69
69
Slide 70
70
Slide 71
71
Slide 72
72
Slide 73
73
Slide 74
74
Slide 75
75
Slide 76
76
Slide 77
77
Slide 78
78
Slide 79
79
Slide 80
80
Slide 81
81
Slide 82
82
Slide 83
83
Slide 84
84
Slide 85
85
Slide 86
86
Slide 87
87
Slide 88
88
Slide 89
89
Slide 90
90
Slide 91
91
Slide 92
92
Slide 93
93
Slide 94
94
Slide 95
95
Slide 96
96
Slide 97
97
Slide 98
98
Slide 99
99
Slide 100
100
Slide 101
101
Slide 102
102
Slide 103
103
Slide 104
104
Slide 105
105
Slide 106
106
Slide 107
107
Slide 108
108
Slide 109
109
Slide 110
110
Slide 111
111
Slide 112
112
Slide 113
113
Slide 114
114
Slide 115
115
Slide 116
116
Slide 117
117
Slide 118
118
Slide 119
119
Slide 120
120
Slide 121
121
Slide 122
122
Slide 123
123
Slide 124
124
Slide 125
125
Slide 126
126
Slide 127
127
Slide 128
128
Slide 129
129
Slide 130
130
Slide 131
131
Slide 132
132
Slide 133
133
Slide 134
134
Slide 135
135
Slide 136
136
Slide 137
137
Slide 138
138
Slide 139
139
Slide 140
140
Slide 141
141
Slide 142
142
Slide 143
143
Slide 144
144
Slide 145
145

About This Presentation

Study to achieve your aims


Slide Content

Variables
Variable is the name of a memory
location which stores some data.
25 S
a b
Memory

Variables
Rules
a. Variables are case sensitive
b. 1st character is alphabet or '_'
c. no comma/blank space
d. No other symbol other than '_'

Variables
Data Types

Constants
Values that don't change(fixed)
Types
Integer
Constants
Character
Constants
Real
Constants
1, 2, 3, 0
, -1, -2
1.0, 2.0,
3.14, -24
'a', 'b', 'A',
'#', '&'

32 Keywords in C
Keywords
Reserved words that have special
meaning to the compiler

Keywords
auto double int struct
break else long switch
case enum register typedef
char extern return union
continue for signed void
do if static while
default goto sizeof volatile
const float short unsigned

Program Structure
#include <stdio.h>
int main() {
printf ("Hello World" );
return 0;
}

Comments
Single Line Multiple
Line
Lines that are not part of program
//
/*
*/

Output
printf( " Hello World " );
printf( " kuch bhi \n");
new line

Output
printf( " age is %d ", age);
printf( " value of pi is %f ", pi);
printf( " star looks like this %c ", star);
CASES
integers1.
2. real numbers
3. characters

Input
scanf( " %d ", &age);

Compilation
Hello.c C Compiler
A computer program that translates C code
into machine code
a.exe (windows)
a.out (linux & mac)

C Language Tutorial
(Basic to Advanced)
Topicsto be covered :
Installation + Setup
Chapter 1 - Variables, Data types + Input/Output
Chapter 2 - Instructions & Operators
Chapter 3 - Conditional Statements
Chapter 4 - Loop Control Statements
Chapter 5 - Functions & Recursion
Chapter 6 - Pointers
Chapter 7 - Arrays
Chapter 8 - Strings
Chapter 9 - Structures
Chapter 10 - File I/O
Chapter 11 - Dynamic Memory Allocation
Variables, Data Types + Input/Output
(Chapter 1)
V
1.First Program
#include<stdio.h>
intmain() {
printf("Hello World");
return0;
}
2.Variables & Data Types + Constants & Keywords
#include<stdio.h>
intmain() {
intnumber;
intage;
intprice;
return0;
}

#include<stdio.h>
intmain() {
intage=22;
floatpi=3.14;
charpercentage='%';
return0;
}
3.Comments
#include<stdio.h>
//This program prints Hello World
intmain() {
printf("Hello World");
return0;
}
4.Output
#include<stdio.h>
intmain() {
intage=22;
floatpi=3.14;
charpercentage='%';
printf("age is%d",age);
printf("age is%f",pi);
printf("age is%c",percentage);
return0;
}
5.Input (Sum of 2 numbers)
#include<stdio.h>
intmain() {
inta,b;
printf("enter a\n");
scanf("%d", &a);
printf("enter b\n");

scanf("%d", &b);
printf("sum of a & b is : %d\n",a+b);
return0;
}
6.Practice Qs 1 (Area of Square)
#include<stdio.h>
//area of square
intmain() {
intside;
scanf("%d", &side);
printf("%d",side*side);
return0;
}
7.Practice Qs 2 (Area of Circle)
#include<stdio.h>
//area of square
intmain() {
floatradius;
scanf("%f", &radius);
printf("%f",3.14*radius*radius);
return0;
}

Instructions
These are statements in a Program
Types
Type Declaration
Instructions
Control
Instructions
Arithmetic
Instructions

Instructions
Type Declaration Instructions
Declare var before using it
int a = 22;
int b = a;
int c = b + 1;
int d = 1, e;
VALID INVALID
int a = 22;
int b = a;
int c = b + 2;
int d = 2, e;
int a,b,c;
a = b = c = 1;
int a,b,c = 1;

Arithmetic Instructions
a + b
Operand 1 Operand 2
Operator
NOTE - single variable on the LHS

a = b + c
VALID INVALID
b + c = a
a = bc
a = b^c
a = b * c
a = b / c
NOTE - pow(x,y) for x to the power y
Arithmetic Instructions

Modular Operator %
Returns remainder for int
3 % 2 = 1
-3 % 2 = -1
Arithmetic Instructions

Arithmetic Instructions
Type Conversion
int intop
int
int floatop
op
float
float float float

Arithmetic Instructions
Operator Precedence
*, /, %
+, -
=
x = 4 + 9 * 10
x = 4 * 3 / 6 * 2

Arithmetic Instructions
Associativity (for same precedence)
Left to Right
x = 4 * 3 / 6 * 2

Instructions
Control Instructions
Used to determine flow of program
a. Sequence Control
b. Decision Control
d. Case Control
c. Loop Control

Operators
a. Arithmetic Operators
b. Relational Operators
d. Bitwise Operators
c. Logical Operators
e. Assignment Operators
f. Ternary Operator

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

Operators
&& AND
|| OR
! NOT
Logical Operators

Operator Precendence
Priority
1
2
3
4
5
6
7
8
Operator
!
*, /, %
+, -
<, <=, >, >=
==, !=
&&
||
=

Operators
=
+=
-=
Assignment Operators
*=
/=
%=

C Language Tutorial
(Basic to Advanced)
Topicsto be covered :
Installation + Setup
Chapter 1 - Variables, Data types + Input/Output
Chapter 2 - Instructions & Operators
Chapter 3 - Conditional Statements
Chapter 4 - Loop Control Statements
Chapter 5 - Functions & Recursion
Chapter 6 - Pointers
Chapter 7 - Arrays
Chapter 8 - Strings
Chapter 9 - Structures
Chapter 10 - File I/O
Chapter 11 - Dynamic Memory Allocation
Instructions & Operators
(Chapter 2)
1.Type Declaration Instructions
#include<stdio.h>
intmain() {
intage=22;
intoldAge=age;
intnewAge=oldAge+2;
printf("new age is :%d",newAge);
intrupee=1,dollar;
dollar=74;
/*
order of declaration is important - Wrong Declaration Order
float pi = 3.14;
float area = pi * rad * rad;
float rad = 3;
*/

// valid declaration
intage1,age2,age3;
age1=age2=age3=22;
//invalid
//inta1= a2 = a3 = 22;
return0;
}
2.Arithmetic Instructions
#include<stdio.h>
intmain() {
inta=1,b=2,c=3;
//valid
a=b+c;
//invalid
// b + c = a;
printf("%d\n",3%2);
printf("%d\n", -3%2);
return0;
}
> Type Conversion
#include<stdio.h>
intmain() {
printf("sum of 2 & 3 : %d",2+3);
printf("sum of 2.0 & 3 : %f",2.0+3);
printf("sum of 2.0 & 3.0 : %f",2.0+3.0);
return0;
}
> Associativity
#include<stdio.h>
intmain() {
printf(" Output :%d",5+2/2*3);

return0;
}
3.Relational Operator
#include<stdio.h>
intmain() {
printf("%d\n",4==4);
printf("%d\n",4<3);
printf("%d\n",3<4);
printf("%d\n",4<4);
printf("%d\n",4<=4);
printf("%d\n",4>3);
printf("%d\n",3>4);
printf("%d\n",4>4);
printf("%d\n",4>=4);
printf("%d\n",4!=4);
printf("%d\n",3!=4);
return0;
}
4.Logical Operator
#include<stdio.h>
intmain() {
printf("%d\n",3<4&&3<5);
printf("%d\n",3<4&&5<4);
printf("%d\n",3<4&&5<4);
printf("%d\n",3>4&&5>4);
printf("%d\n",3<4&&3<5);
printf("%d\n", !(3<4&&3<5));
printf("%d\n", !(4<3||5<3));
return0;
}

5.Assignment Operator
# include<stdio.h>
intmain() {
inta=10;
a+=10;
printf("a+10 =%d\n",a);
a-=10;
printf("a-10 =%d\n",a);
a*=10;
printf("a*10 =%d\n",a);
a/=10;
printf("a/10 =%d\n",a);
a%=10;
printf("a%c10 =%d\n",'%',a);
return0;
}
V

Conditional Statements
Types
if-else Switch

if-else
if(Condition ) {
//do something if TRUE
}
else {
//do something if FALSE
}
Ele is optional block
can also work without {}

else if
if(Condition 1 ) {
//do something if TRUE
}
else if (Condition 2 ) {
//do something if 1st is FALSE & 2nd is TRUE
}

Conditional Operators
Condition ? doSomething if TRUE : doSomething if FALSE ;
give 1 & 0 cases
Ternary

Conditional Operators
switch(number) {
case C1: //do something
break;
case C2 : //do something
break;
default : //do something
}
switch

Conditional Operators
a. Cases can be in any order
switch Properties
b. Nested switch (switch inside switch) are allowed

C Language Tutorial
(Basic to Advanced)
Topicsto be covered :
Installation + Setup
Chapter 1 - Variables, Data types + Input/Output
Chapter 2 - Instructions & Operators
Chapter 3 - Conditional Statements
Chapter 4 - Loop Control Statements
Chapter 5 - Functions & Recursion
Chapter 6 - Pointers
Chapter 7 - Arrays
Chapter 8 - Strings
Chapter 9 - Structures
Chapter 10 - File I/O
Chapter 11 - Dynamic Memory Allocation
Conditional Statements
(Chapter 3)
1.If-else
#include<stdio.h>
intmain() {
intage=19;
if(age>=18) {
printf("you are an adult");
}
else{
printf("you are not an adult" );
}
return0;
}
> check if a number is odd or even
#include<stdio.h>
intmain() {
intnumber;

scanf("%d", &number);
if(number%2==0) {
printf("even");
}
else{
printf("odd");
}
return0;
}
> Use of else if
#include<stdio.h>
intmain() {
intage;
printf("Enter age : ");
scanf("%d", &age);
if(age<12) {
printf("child");
}
elseif(age<18) {
printf("teenager");
}
else{
printf("adult");
}
return0;
}
2.Ternary Operator
#include<stdio.h>
intmain() {
intage;
printf("Enter age : ");
scanf("%d", &age);
age>18?printf("adult\n") :printf("not adult\n");
intnumber=7;

intluckyNumber=7;
number==luckyNumber?printf("you are lucky \n"):printf("you are not
lucky\n");
return0;
}
3.Switch (integer)
#include<stdio.h>
#include<math.h>
intmain() {
intday=5;
switch(day) {
case1:printf("monday\n");
break;
case2:printf("tuesday\n");
break;
case3:printf("wednesday\n");
break;
case4:printf("thursday\n");
break;
case5:printf("friday\n");
break;
case6:printf("saturday\n");
break;
case7:printf("sunday\n");
break;
}
return0;
}
4.Switch (character)
#include<stdio.h>
#include<math.h>
intmain() {
charday='f';
switch(day) {
case'm':printf("monday\n");
break;

case't':printf("tuesday\n");
break;
case'w':printf("wednesday\n");
break;
case'T':printf("thursday\n");
break;
case'f':printf("friday\n");
break;
case's':printf("saturday\n");
break;
case'S':printf("sunday\n");
break;
}
return0;
}

Loop Control Instructions
Types
for do while
while
To repeat some parts of the program

for Loop
for(initialisation; condition; updation) {
//do something
}

- Increment Operator
Special Things
- Decrement Operator
- Loop counter can be float
or even character
- Infinite Loop

while(condition) {
//do something
}
while Loop

do {
//do something
} while(condition);
do while Loop

exit the loop
break Statement

skip to next iteration
continue Statement

Nested Loops
for( .. ) {
for( .. ) {

}
}

C Language Tutorial
(Basic to Advanced)
Topicsto be covered :
Installation + Setup
Chapter 1 - Variables, Data types + Input/Output
Chapter 2 - Instructions & Operators
Chapter 3 - Conditional Statements
Chapter 4 - Loop Control Statements
Chapter 5 - Functions & Recursion
Chapter 6 - Pointers
Chapter 7 - Arrays
Chapter 8 - Strings
Chapter 9 - Structures
Chapter 10 - File I/O
Chapter 11 - Dynamic Memory Allocation
Loop Control Statements
(Chapter 4)
1.Syntax of 3 Loops
# include<stdio.h>
intmain() {
//for loop
for(inti=1;i<=100;i++) {
printf("%d\n",i);
}
//while loop
inti=1;
while(i<=100) {
printf("%d\n",i);
i++;
}
//do while loop
i=1;
do{

printf("%d\n",i);
i++;
}while(i<=100);
return0;
}

Take
Argument
Do
Work
Return
Result
block of code that performs particular task
Functions
increase code reusability
it can be used multiple times

Function Prototype
Syntax
void printHello ( );
> Tell the compiler
1

Function Definition
Syntax
printf("Hello");
void printHello () {
}
2
> Do the Work

Syntax
Function Call
int main() {
return 0;
}
printHello ( );
3
> Use the Work

- Execution always starts from main
Properties
- A function gets called directly or indirectly from main
- There can be multiple functions in a program

Function Types
Library
function
User-
defined
Special functions
inbuilt in C
declared & defined by
programmer
scanf( ), printf( )

Passing Arguments
functions can take value & give some value
parameter return value

Passing Arguments
void printHello ( );
void printTable (int n);
int sum(int a, int b);

Passing Arguments
functions can take value & give some value
parameter return value

Argument v/s Parameter
values that are
passed in
function call
values in function
declaration &
definition
used to send
value
used to receive
value
actual
parameter
formal
parameters

NOTE
a. Function can only return one value at a time
b. Changes to parameters in function don't change the values in
calling function.
Because a copy of argument is passed to the function

Recursion
When a function calls itself , it's called recursion

a. Anything that can be done with Iteration, can be done with
recursion and vice-versa.
Properties of Recursion
b. Recursion can sometimes give the most simple solution.
d. Iteration has infinite loop & Recursion has stack overflow
c. Base Case is the condition which stops recursion.

C Language Tutorial
(Basic to Advanced)
Topicsto be covered :
Installation + Setup
Chapter 1 - Variables, Data types + Input/Output
Chapter 2 - Instructions & Operators
Chapter 3 - Conditional Statements
Chapter 4 - Loop Control Statements
Chapter 5 - Functions & Recursion
Chapter 6 - Pointers
Chapter 7 - Arrays
Chapter 8 - Strings
Chapter 9 - Structures
Chapter 10 - File I/O
Chapter 11 - Dynamic Memory Allocation
Functions & Recursion
(Chapter 5)
1.Function to print Hello
#include<stdio.h>
//function declaration/prototype
voidprintHello();
intmain() {
//function call
printHello();
return0;
}
//function definition
voidprintHello() {
printf("Hello!\n");
}
2.Function to calculate square of a number

# include<stdio.h>
//function to calculate square of a number
intcalcSquare(intn);
intmain() {
intn;
printf("enter n : ");
scanf("%d", &n);
printf("square is :%d",calcSquare(n));
return0;
}
intcalcSquare(intn) {
returnn*n;
}
3.Function to calculate n factorial (using recursion)
# include<stdio.h>
//function to print factorial of n
intfactorial(intn);
intmain() {
intn;
printf("enter n : ");
scanf("%d", &n);
printf("factorial is : %d",factorial(n));
return0;
}
intfactorial(intn) {
if(n==0) {
return1;
}
intfactnm1=factorial(n-1);
intfactn=factnm1*n;
returnfactn;
}

Pointers
A variable that stores the memory
address of another variable
22
age
Memory
2010
ptr
2010
2013

Syntax
int age = 22;
int *ptr = &age;
int _age = *ptr;
22
age
Memory
2010
ptr
2010
2013

Declaring Pointers
int *ptr;
char *ptr;
float *ptr;

Format Specifier
printf("%p", &age);
printf("%p", ptr);
printf("%p", &ptr);

Pointer to Pointer
A variable that stores the memory
address of another pointer
22
age
Memory
2010
ptr
2010
2013
pptr
2013
2012

Pointer to Pointer
Syntax
int **pptr;
char **pptr;
float **pptr;

Pointers in Function Call
Call by
Value
call by
Reference
We pass value of
variable as
argument
We pass address of
variable as
argument

C Language Tutorial
(Basic to Advanced)
Topicsto be covered :
Installation + Setup
Chapter 1 - Variables, Data types + Input/Output
Chapter 2 - Instructions & Operators
Chapter 3 - Conditional Statements
Chapter 4 - Loop Control Statements
Chapter 5 - Functions & Recursion
Chapter 6 - Pointers
Chapter 7 - Arrays
Chapter 8 - Strings
Chapter 9 - Structures
Chapter 10 - File I/O
Chapter 11 - Dynamic Memory Allocation
Pointers
(Chapter 6)
1.Syntax
#include<stdio.h>
intmain() {
intage=22;
int*ptr= &age;
int_age= *ptr;
printf("%d\n",_age);
//address
printf("%p\n", &age);
printf("%p\n",ptr);
printf("%p\n", &ptr);
//data
printf("%d\n",age);
printf("%d\n", *ptr);
printf("%d\n", *(&age));
return0;

}
2.Pointers in Function call
# include<stdio.h>
voidsquare(intn);
void_square(int*n);
intmain() {
intnumber=4;
//call by value
square(number);
printf("n is :%d\n",number);
//call by reference
_square(&number);
printf("n is :%d\n",number);
return0;
}
voidsquare(intn) {
n=n*n;
printf("square is :%d\n",n);
}
void_square(int*n) {
*n= *n* *n;
printf("square is :%d\n", *n);
}
3.Swap 2 numbers
# include<stdio.h>
voidswap(inta,intb);
void_swap(int*a,int*b);
intmain() {
intx=3,y=5;
//call by value
swap(x,y);

printf("x =%d& y =%d\n",x,y);
//call by reference
_swap(&x, &y);
printf("x =%d& y =%d\n",x,y);
return0;
}
voidswap(inta,intb) {
intt=a;
a=b;
b=a;
}
void_swap(int*a,int*b) {
intt= *a;
*a= *b;
*b= *a;
}

Arrays
Collection of similar data types stored at
contiguous memory locations

Syntax
int marks[3];
char name[10];
float price[2];

Input & Output
scanf("%d", &marks[0] );
printf ("%d", marks[0] );

Inititalization of Array
int marks[ ] = {97, 98, 89 };
int marks[ 3 ] = {97, 98, 89 };
Memory Reserved :

Pointer Arithmetic
Pointer can be incremented
& decremented
CASE 1

Pointer Arithmetic
CASE 2
CASE 3

Pointer Arithmetic
- We can also subtract one pointer from another
- We can also compare 2 pointers

Array is a Pointer
int *ptr = &arr[0];
int *ptr = arr;

Traverse an Array
int aadhar[10];
int *ptr = &aadhar[0];

Arrays as Function Argument
printNumbers (arr, n);
void printNumbers (int arr[ ], int n)
void printNumbers (int *arr, int n)
OR
//Function Declaration
//Function Call

Multidimensional Arrays
arr[0][0]
2 D Arrays
int arr[ ][ ] = { {1, 2}, {3, 4} }; //Declare
//Access
arr[0][1]
arr[1][0]
arr[1][1]

C Language Tutorial
(Basic to Advanced)
Topicsto be covered :
Installation + Setup
Chapter 1 - Variables, Data types + Input/Output
Chapter 2 - Instructions & Operators
Chapter 3 - Conditional Statements
Chapter 4 - Loop Control Statements
Chapter 5 - Functions & Recursion
Chapter 6 - Pointers
Chapter 7 - Arrays
Chapter 8 - Strings
Chapter 9 - Structures
Chapter 10 - File I/O
Chapter 11 - Dynamic Memory Allocation
Arrays
(Chapter 7)
1.Syntax
# include<stdio.h>
intmain() {
intmarks[3];
printf("physics : ");
scanf("%d", &marks[0]);
printf("chem : ");
scanf("%d", &marks[1]);
printf("math : ");
scanf("%d", &marks[2]);
printf("physics =%d, ",marks[0]);//physics
printf("chem =%d, ",marks[1]);//chem
printf("math =%d\n",marks[2]);//math

return0;
}
2.Pointer Arithmetic
# include<stdio.h>
intmain() {
intage=22;
int*ptr= &age;
int_age=25;
int*_ptr= &_age;
printf("%u\n",ptr);
ptr++;
printf("%u\n",ptr);
ptr--;
printf("%u\n",ptr);
ptr=ptr-_ptr;
printf("%u\n",ptr);
ptr= &_age;
printf("%d\n",ptr==_ptr);
return0;
}
3.Accessing an Array
# include<stdio.h>
voidprintNumbers(int*arr,intn);
void_printNumbers(intarr[],intn);
intmain() {
intarr[]= {1,2,3,4,5,6};
printNumbers(arr,6);
printNumbers(arr,6);
return0;
}

voidprintNumbers(int*arr,intn) {
for(inti=0;i<n;i++) {
printf("%d:%d\n",i,arr[i]);
}
}
void_printNumbers(intarr[],intn) {
for(inti=0;i<n;i++) {
printf("%d:%d\n",i,arr[i]);
}
}

Strings
A character array terminated by a '\0' (null character)
null character denotes string termination
EXAMPLE
char name[ ] = { 'S', 'H', 'R', 'A', 'D', 'H', 'A','\0' };
char class[ ] = { 'A', 'P', 'N', 'A', ' ', 'C', 'O', 'L', 'L', 'E', 'G', 'E', '\0' };

Initialising Strings
char name[ ] = { 'S', 'H', 'R', 'A', 'D', 'H', 'A','\0' };
char class[ ] = { 'A', 'P', 'N', 'A', ' ', 'C', 'O', 'L', 'L', 'E', 'G', 'E', '\0' };
char name[ ] = "SHRADHA" ;
char class[ ] = "APNA COLLEGE" ;

What Happens in Memory?
char name[ ] = { 'S', 'H', 'R', 'A', 'D', 'H', 'A','\0' };
char name[ ] = "SHRADHA" ;
2000
name
S H R A D H A
\0
2001 2002 2003 2004 2005 2006 2007

String Format Specifier
"%s"
printf("%s", name);
char name[ ] = "Shradha" ;

IMPORTANT
scanf( ) cannot input multi-word strings with spaces
Here,
gets( ) & puts( ) come into picture

String Functions
gets(str)
input a string
(even multiword)
puts(str)
output a string
fgets( str, n, file)
Dangerous &
Outdated
stops when n-1
chars input or new
line is entered

String using Pointers
char *str = "Hello World" ;
Store string in memory & the assigned
address is stored in the char pointer 'str'
char *str = "Hello World" ;
char str[ ] = "Hello World" ;
//cannot be reinitialized
//can be reinitialized

Standard Library Functions
1 strlen( str)
count number of characters excluding '\0'
<string.h>

Standard Library Functions
2 strcpy( newStr, oldStr )
copies value of old string to new string
<string.h>

Standard Library Functions
3 strcat( firstStr, secStr )
concatenates first string with second string
<string.h>
firstStr should be large
enough

Standard Library Functions
4 strcpm( firstStr, secStr )
Compares 2 strings & returns a value
<string.h>
0 -> string equal
positive -> first > second (ASCII)
negative -> first < second (ASCII)

C Language Tutorial
(Basic to Advanced)
Topicsto be covered :
Installation + Setup
Chapter 1 - Variables, Data types + Input/Output
Chapter 2 - Instructions & Operators
Chapter 3 - Conditional Statements
Chapter 4 - Loop Control Statements
Chapter 5 - Functions & Recursion
Chapter 6 - Pointers
Chapter 7 - Arrays
Chapter 8 - Strings
Chapter 9 - Structures
Chapter 10 - File I/O
Chapter 11 - Dynamic Memory Allocation
Strings
(Chapter 8)
1.Strings
# include<stdio.h>
# include<string.h>
intmain() {
//declaration
charname[]="Shradha Khapra";
charcourse[]= {'a','p','n','a',' ','c','o','l','l','e','g','e',
'\0'};
//printing string
for(inti=0;name[i] !='\0';i++) {
printf("%c",name[i]);
}
printf("\n");
//printing string with pointer
for(char*ptr=name; *ptr!='\0';ptr++) {
printf("%c", *ptr);

}
printf("\n");
//printing using format specifier
printf("%s\n",name);
//input a string
charfirstName[40];
printf("enter first name : " );
scanf("%s",firstName);
printf("you first name is %s\n",firstName);
charfullName[40];
printf("enter full name : " );
scanf("%s",fullName);
printf("you first name is %s\n",fullName);
// gets & puts
charfullName[40];
printf("enter full name : " );
fgets(fullName,40,stdin);
puts(fullName);
//Library Functions
charname[]="Shradha";
intlength=strlen(name);
printf("the length of name : %d\n",length);
charoldVal[]="oldValue";
charnewVal[50];
strcpy(newVal,oldVal);
puts(newVal);
charfirstStr[50] ="Hello ";
charsecStr[]="World";
strcat(firstStr,secStr);
puts(firstStr);
charstr1[]="Apple";
charstr2[]="Banana";
printf("%d\n",strcmp(str1,str2));
//enter String using %c

printf("enter string : ");
charstr[100];
charch;
inti=0;
while(ch!='\n') {
scanf("%c", &ch);
str[i] =ch;
i++;
}
str[i] ='\0';
puts(str);
return0;
}
>Some more Qs
# include<stdio.h>
# include<string.h>
// void printString(char arr[]);
// int countLength(char arr[]);
// void salting(char password[]);
// void slice(char str[], int n, int m);
//int countVowels(char str[]);
voidcheckChar(charstr[],charch);
intmain() {
charstr[]="ApnaCollege";
charch='x';
checkChar(str,ch);
}
voidcheckChar(charstr[],charch) {
for(inti=0;str[i] !='\0';i++) {
if(str[i] ==ch) {
printf("character is present!" );
return;

}
}
printf("character is NOT present:(" );
}
// int countVowels(char str[]) {
// int count = 0;
// for(int i=0; str[i] != '\0'; i++) {
// if(str[i] == 'a' || str[i] == 'e' || str[i] == 'i' ||
// str[i] == 'o' || str[i] == 'u') {
// count++;
// }
// }
// return count;
// }
// void slice(char str[], int n, int m) { // n & m are valid value
// char newStr[100];
// int j = 0;
// for(int i=n; i<=m; i++, j++) {
// newStr[j] = str[i];
// }
// newStr[j] = '\0';
// puts(newStr);
// }
// void salting(char password[]) {
// char salt[] = "123";
// char newPass[200];
// strcpy(newPass, password); // newPass = "test"
// strcat(newPass, salt); // newPass = "test" + "123";
// puts(newPass);

// }
// int countLength(char arr[]) {
// int count = 0;
// for(int i=0; arr[i]!='\0'; i++) {
// count++;
// }
// return count-1;
// }
// void printString(char arr[]) {
// for(int i=0; arr[i] != '\0' ;i++) {
// printf("%c", arr[i]);
// }
// printf("\n");
// }

Structures
a collection of values of different data types
EXAMPLE
name (String)
For a student store the following :
roll no (Integer)
cgpa (Float)

Syntax
struct student {
char name[100];
int roll;
float cgpa;
};
struct student s1;
s1.cgpa = 7.5;

Syntax
struct student {
char name[100];
int roll;
float cgpa;
}

Structures in Memory
struct student {
char name[100];
int roll;
float cgpa;
}
name
2010
cgpa
21142110
roll
structures are stored in contiguous memory locations

Benefits of using Structures
- Good data management/organization
- Saves us from creating too many variables

Array of Structures
struct student COE[100];
struct student ECE[100];
struct student IT[100];
IT[0].roll = 200;
ACCESS
IT[0].cgpa = 7.6;

Initializing Structures
struct student s1 = { "shradha", 1664, 7.9};
struct student s2 = { "rajat", 1552, 8.3};
struct student s3 = { 0 };

Pointers to Structures
struct student * ptr;
ptr =&s1;
struct student s1;

Arrow Operator
(*ptr).code ptr->code

Passing structure to function
void printInfo( struct student s1);
//Function Prototype

typedef Keyword
used to create alias for data types
coe student1;

C Language Tutorial
(Basic to Advanced)
Topicsto be covered :
Installation + Setup
Chapter 1 - Variables, Data types + Input/Output
Chapter 2 - Instructions & Operators
Chapter 3 - Conditional Statements
Chapter 4 - Loop Control Statements
Chapter 5 - Functions & Recursion
Chapter 6 - Pointers
Chapter 7 - Arrays
Chapter 8 - Strings
Chapter 9 - Structures
Chapter 10 - File I/O
Chapter 11 - Dynamic Memory Allocation
Structures
(Chapter 9)
1.Structures
# include<stdio.h>
# include<string.h>
structstudent{
charname[100];
introll;
floatcgpa;
};
typedefstructComputerEngineeringStudent {
introll;
floatcgpa;
charname[100];
}coe;
voidprintInfo(structstudents1);
intmain() {

structstudents1;
// s1.name = "Shradha"; // not a modifiable value
strcpy(s1.name,"Shradha");
s1.roll=64;
s1.cgpa=9.2;
printf("student info : \n");
printf("name =%s\n",s1.name);
printf("roll no =%d\n",s1.roll);
printf("cgpa =%f\n",s1.cgpa);
//array of structures
structstudentIT[60];
structstudentCOE[60];
structstudentECE[60];
//declaration
structstudents2= {"Rajat",1552,8.6};
structstudents3= {0};
printf("roll no of s2 = %d\n",s2.roll);
printf("roll no of s3 = %d\n",s3.roll);
//pointer to structure
structstudent*ptr= &s1;
printf("student.name = %s\n", (*ptr).name);
printf("student.roll = %d\n", (*ptr).roll);
printf("student.cgpa = %f\n", (*ptr).cgpa);
//arrow operator
printf("student->name = %s\n",ptr->name);
printf("student->roll = %d\n",ptr->roll);
printf("student->cgpa = %f\n",ptr->cgpa);
//Passing structure to function
printInfo(s1);
//typedef keyword
coestudent1;
student1.roll=1664;
student1.cgpa=6.7;

strcpy(student1.name,"sudhir");
return0;
}
voidprintInfo(structstudents1) {
printf("student info : \n");
printf("name =%s\n",s1.name);
printf("roll no =%d\n",s1.roll);
printf("cgpa =%f\n",s1.cgpa);
//change
s1.roll=1660;//but it won't be reflected to the main function
//as structures are passed by value
}
> Some more Qs
# include<stdio.h>
# include<string.h>
//user defined
typedefstructstudent{
introll;
floatcgpa;
charname[100];
}stu;
typedefstructcomputerengineeringstudent {
introll;
floatcgpa;
charname[100];
}coe;
structaddress{
inthouseNo;
intblock;
charcity[100];
charstate[100];
};
structvector{
intx;

inty;
};
voidcalcSum(structvectorv1,structvectorv2,structvectorsum);
structcomplex{
intreal;
intimg;
};
typedefstructBankAccount{
intaccountNo;
charname[100];
}acc;
intmain() {
accacc1= {123,"shradha"};
accacc2= {124,"rajat"};
accacc3= {125,"sudhir"};
printf("acc no =%d",acc1.accountNo);
printf("name =%s",acc1.name);
return0;
}
voidcalcSum(structvectorv1,structvectorv2,structvectorsum) {
sum.x=v1.x+v2.x;
sum.y=v1.y+v2.y;
printf("sum of x is : %d\n",sum.x);
printf("sum of y is : %d\n",sum.y);
}

File IO
RAM Hard Disk

File IO
- RAM is volatile
FILE - container in a storage device to store data
- Contents are lost when program terminates
- Files are used to persist the data

Operation on Files
Create a File
Open a File
Close a File
Read from a File
Write in a File

Types of Files
Text Files
.exe, .mp3, .jpg
Binary Files
textual data
.txt, .c
binary data

File Pointer
FILE is a (hidden)structure that needs to be created for opening a file
A FILE ptr that points to this structure & is used to
access the file.
FILE *fptr;

Opening a File
fptr = fopen("filename" , mode);
FILE *fptr;
Closing a File
fclose (fptr);

File Opening Modes
open to read"r"
open to read in binary"rb"
open to write"w"
open to write in binary"wb"
open to append"a"

BEST Practice
Check if a file exists before reading from it.

Reading from a file
fscanf(fptr, "%c", &ch);
char ch;

Writing to a file
fprintf (fptr, "%c", ch);
char ch = 'A';

Read & Write a char
fgetc(fptr)
fputc( 'A', fptr)

EOF (End Of File)
fgetc returns EOF to show that the file has ended

C Language Tutorial
(Basic to Advanced)
Topicsto be covered :
Installation + Setup
Chapter 1 - Variables, Data types + Input/Output
Chapter 2 - Instructions & Operators
Chapter 3 - Conditional Statements
Chapter 4 - Loop Control Statements
Chapter 5 - Functions & Recursion
Chapter 6 - Pointers
Chapter 7 - Arrays
Chapter 8 - Strings
Chapter 9 - Structures
Chapter 10 - File I/O
Chapter 11 - Dynamic Memory Allocation
File I/O
(Chapter 10)
# include<stdio.h>
intmain() {
FILE*fptr;
//Reading a file
charch;
fptr=fopen("Test.txt","r");
if(fptr==NULL) {
printf("doesn't exist!\n");
}else{
fscanf(fptr,"%c", &ch);
printf("character in file is : %c\n",ch);
fscanf(fptr,"%c", &ch);
printf("character in file is : %c\n",ch);
fclose(fptr);
}
//Writing in a file
ch='M';
fptr=fopen("NewFile.txt","w");

fprintf(fptr,"%cANGO",ch);
fclose(fptr);
//fgets
fptr=fopen("NewFile.txt","r");
printf("character in file is : %c\n",fgetc(fptr));
printf("character in file is : %c\n",fgetc(fptr));
printf("character in file is : %c\n",fgetc(fptr));
printf("character in file is : %c\n",fgetc(fptr));
printf("character in file is : %c\n",fgetc(fptr));
fclose(fptr);
//fputc
fptr=fopen("NewFile.txt","w");
fputc('a',fptr);
fputc('p',fptr);
fputc('p',fptr);
fputc('l',fptr);
fputc('e',fptr);
fclose(fptr);
//read the full file (EOF)
fptr=fopen("NewFile.txt","r");
ch=fgetc(fptr);
while(ch!=EOF) {
printf("%c",ch);
ch=fgetc(fptr);
}
printf("\n");
fclose(fptr);
return0;
}

Dynamic Memory Allocation
It is a way to allocate memory to a data structure during
the runtime .
We need some functions to allocate
& free memory dynamically.

Functions for DMA
a. malloc( )
b. calloc( )
c. free( )
d. realloc( )

malloc( )
takes number of bytes to be allocated
& returns a pointer of type void
ptr = (*int) malloc(5 * sizeof(int));
memory allocation

calloc( )
initializes with 0
ptr = (*int) calloc(5, sizeof(int));
continuous allocation

free( )
We use it to free memory that is allocated
using malloc & calloc
free(ptr);

realloc( )
reallocate (increase or decrease) memory
using the same pointer & size.
ptr = realloc(ptr, newSize);

C Language Tutorial
(Basic to Advanced)
Topicsto be covered :
Installation + Setup
Chapter 1 - Variables, Data types + Input/Output
Chapter 2 - Instructions & Operators
Chapter 3 - Conditional Statements
Chapter 4 - Loop Control Statements
Chapter 5 - Functions & Recursion
Chapter 6 - Pointers
Chapter 7 - Arrays
Chapter 8 - Strings
Chapter 9 - Structures
Chapter 10 - File I/O
Chapter 11 - Dynamic Memory Allocation
Dynamic Memory Allocation
(Chapter 11)
# include<stdio.h>
# include<stdlib.h>
//Dynamic Memory Allocation
intmain() {
//sizeof function
printf("%d\n",sizeof(int));
printf("%d\n",sizeof(float));
printf("%d\n",sizeof(char));
//malloc
// int *ptr;
// ptr = (int *) malloc(5 * sizeof(int));
// for(int i=0; i<5; i++) {
// scanf("%d", &ptr[i]);
// }
// for(int i=0; i<5; i++) {
// printf("number %d = %d\n", i+1, ptr[i]);

// }
//calloc
int*ptr= (int*)calloc(5,sizeof(int));
for(inti=0;i<5;i++) {
printf("number%d=%d\n",i+1,ptr[i]);
}
//free
free(ptr);
return0;
}