SlideShare a Scribd company logo
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
integers
1.
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)
Topics to 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>
int main() {
printf("Hello World");
return 0;
}
2. Variables & Data Types + Constants & Keywords
#include<stdio.h>
int main() {
int number;
int age;
int price;
return 0;
}
#include<stdio.h>
int main() {
int age = 22;
float pi = 3.14;
char percentage = '%';
return 0;
}
3. Comments
#include<stdio.h>
//This program prints Hello World
int main() {
printf("Hello World");
return 0;
}
4. Output
#include<stdio.h>
int main() {
int age = 22;
float pi = 3.14;
char percentage = '%';
printf("age is %d", age);
printf("age is %f", pi);
printf("age is %c", percentage);
return 0;
}
5. Input (Sum of 2 numbers)
#include<stdio.h>
int main() {
int a, 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);
return 0;
}
6. Practice Qs 1 (Area of Square)
#include<stdio.h>
//area of square
int main() {
int side;
scanf("%d", &side);
printf("%d", side * side);
return 0;
}
7. Practice Qs 2 (Area of Circle)
#include<stdio.h>
//area of square
int main() {
float radius;
scanf("%f", &radius);
printf("%f", 3.14 * radius * radius);
return 0;
}
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 int
op int
int float
op
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)
Topics to 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>
int main() {
int age = 22;
int oldAge = age;
int newAge = oldAge + 2;
printf("new age is : %d", newAge);
int rupee = 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
int age1, age2, age3;
age1 = age2 = age3 = 22;
//invalid
//int a1 = a2 = a3 = 22;
return 0;
}
2. Arithmetic Instructions
#include<stdio.h>
int main() {
int a = 1, b = 2, c = 3;
//valid
a = b + c;
//invalid
// b + c = a;
printf("%d n", 3 % 2);
printf("%d n", -3 % 2);
return 0;
}
> Type Conversion
#include<stdio.h>
int main() {
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);
return 0;
}
> Associativity
#include<stdio.h>
int main() {
printf(" Output : %d", 5+2/2*3);
return 0;
}
3. Relational Operator
#include<stdio.h>
int main() {
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);
return 0;
}
4. Logical Operator
#include<stdio.h>
int main() {
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));
return 0;
}
5. Assignment Operator
# include <stdio.h>
int main() {
int a = 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);
return 0;
}
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)
Topics to 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>
int main() {
int age = 19;
if(age >= 18) {
printf("you are an adult");
}
else {
printf("you are not an adult");
}
return 0;
}
> check if a number is odd or even
#include<stdio.h>
int main() {
int number;
scanf("%d", &number);
if(number % 2 == 0) {
printf("even");
}
else {
printf("odd");
}
return 0;
}
> Use of else if
#include<stdio.h>
int main() {
int age;
printf("Enter age : ");
scanf("%d", &age);
if(age < 12) {
printf("child");
}
else if(age < 18) {
printf("teenager");
}
else {
printf("adult");
}
return 0;
}
2. Ternary Operator
#include<stdio.h>
int main() {
int age;
printf("Enter age : ");
scanf("%d", &age);
age > 18 ? printf("adult n") : printf("not adult n");
int number = 7;
int luckyNumber = 7;
number == luckyNumber ? printf("you are lucky n") : printf("you are not
lucky n");
return 0;
}
3. Switch (integer)
#include<stdio.h>
#include<math.h>
int main() {
int day = 5;
switch(day) {
case 1 : printf("monday n");
break;
case 2 : printf("tuesday n");
break;
case 3 : printf("wednesday n");
break;
case 4 : printf("thursday n");
break;
case 5 : printf("friday n");
break;
case 6 : printf("saturday n");
break;
case 7 : printf("sunday n");
break;
}
return 0;
}
4. Switch (character)
#include<stdio.h>
#include<math.h>
int main() {
char day = '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;
}
return 0;
}
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)
Topics to 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>
int main () {
//for loop
for(int i=1; i<=100; i++) {
printf("%dn", i);
}
//while loop
int i=1;
while(i<=100) {
printf("%dn", i);
i++;
}
//do while loop
i = 1;
do {
printf("%dn", i);
i++;
} while(i<=100);
return 0;
}
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)
Topics to 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
void printHello();
int main() {
//function call
printHello();
return 0;
}
//function definition
void printHello() {
printf("Hello!n");
}
2. Function to calculate square of a number
# include <stdio.h>
//function to calculate square of a number
int calcSquare(int n);
int main() {
int n;
printf("enter n : ");
scanf("%d", &n);
printf("square is : %d", calcSquare(n));
return 0;
}
int calcSquare(int n) {
return n * n;
}
3. Function to calculate n factorial (using recursion)
# include <stdio.h>
//function to print factorial of n
int factorial(int n);
int main() {
int n;
printf("enter n : ");
scanf("%d", &n);
printf("factorial is : %d", factorial(n));
return 0;
}
int factorial(int n) {
if(n == 0) {
return 1;
}
int factnm1 = factorial(n-1);
int factn = factnm1 * n;
return factn;
}
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)
Topics to 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>
int main() {
int age = 22;
int *ptr = &age;
int _age = *ptr;
printf("%dn", _age);
//address
printf("%pn", &age);
printf("%pn", ptr);
printf("%pn", &ptr);
//data
printf("%dn", age);
printf("%dn", *ptr);
printf("%dn", *(&age));
return 0;
}
2. Pointers in Function call
# include <stdio.h>
void square(int n);
void _square(int* n);
int main() {
int number = 4;
//call by value
square(number);
printf("n is : %dn", number);
//call by reference
_square(&number);
printf("n is : %dn", number);
return 0;
}
void square(int n) {
n = n * n;
printf("square is : %dn", n);
}
void _square(int* n) {
*n = *n * *n;
printf("square is : %dn", *n);
}
3. Swap 2 numbers
# include <stdio.h>
void swap(int a, int b);
void _swap(int* a, int *b);
int main() {
int x = 3, y = 5;
//call by value
swap(x, y);
printf("x = %d & y = %dn", x, y);
//call by reference
_swap(&x, &y);
printf("x = %d & y = %dn", x, y);
return 0;
}
void swap(int a, int b) {
int t = a;
a = b;
b = a;
}
void _swap(int* a, int* b) {
int t = *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)
Topics to 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>
int main() {
int marks[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
return 0;
}
2. Pointer Arithmetic
# include <stdio.h>
int main() {
int age = 22;
int *ptr = &age;
int _age = 25;
int *_ptr = &_age;
printf("%un", ptr);
ptr++;
printf("%un", ptr);
ptr--;
printf("%un", ptr);
ptr = ptr - _ptr;
printf("%un", ptr);
ptr = &_age;
printf("%dn", ptr == _ptr);
return 0;
}
3. Accessing an Array
# include <stdio.h>
void printNumbers(int *arr, int n);
void _printNumbers(int arr[], int n);
int main() {
int arr[] = {1, 2, 3, 4, 5, 6};
printNumbers(arr, 6);
printNumbers(arr, 6);
return 0;
}
void printNumbers(int *arr, int n) {
for(int i=0; i<n; i++) {
printf("%d : %dn", i, arr[i]);
}
}
void _printNumbers(int arr[], int n) {
for(int i=0; i<n; i++) {
printf("%d : %dn", 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)
Topics to 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>
int main() {
//declaration
char name[] = "Shradha Khapra";
char course[] = {'a','p', 'n', 'a', ' ', 'c', 'o', 'l', 'l', 'e', 'g', 'e',
'0'};
//printing string
for(int i=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("%sn", name);
//input a string
char firstName[40];
printf("enter first name : ");
scanf("%s", firstName);
printf("you first name is %sn", firstName);
char fullName[40];
printf("enter full name : ");
scanf("%s", fullName);
printf("you first name is %sn", fullName);
// gets & puts
char fullName[40];
printf("enter full name : ");
fgets(fullName, 40, stdin);
puts(fullName);
//Library Functions
char name[] = "Shradha";
int length = strlen(name);
printf("the length of name : %dn", length);
char oldVal[] = "oldValue";
char newVal[50];
strcpy(newVal, oldVal);
puts(newVal);
char firstStr[50] = "Hello ";
char secStr[] = "World";
strcat(firstStr, secStr);
puts(firstStr);
char str1[] = "Apple";
char str2[] = "Banana";
printf("%dn", strcmp(str1, str2));
//enter String using %c
printf("enter string : ");
char str[100];
char ch;
int i = 0;
while(ch != 'n') {
scanf("%c", &ch);
str[i] = ch;
i++;
}
str[i] = '0';
puts(str);
return 0;
}
> 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[]);
void checkChar(char str[], char ch);
int main() {
char str[] = "ApnaCollege";
char ch = 'x';
checkChar(str, ch);
}
void checkChar(char str[], char ch) {
for(int i=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
2114
2110
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)
Topics to 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>
struct student {
char name[100];
int roll;
float cgpa;
};
typedef struct ComputerEngineeringStudent{
int roll;
float cgpa;
char name[100];
} coe;
void printInfo(struct student s1);
int main() {
struct student s1;
// s1.name = "Shradha"; // not a modifiable value
strcpy(s1.name,"Shradha");
s1.roll = 64;
s1.cgpa = 9.2;
printf("student info : n");
printf("name = %sn", s1.name);
printf("roll no = %dn", s1.roll);
printf("cgpa = %fn", s1.cgpa);
//array of structures
struct student IT[60];
struct student COE[60];
struct student ECE[60];
//declaration
struct student s2 = {"Rajat", 1552, 8.6};
struct student s3 = {0};
printf("roll no of s2 = %dn", s2.roll);
printf("roll no of s3 = %dn", s3.roll);
//pointer to structure
struct student *ptr = &s1;
printf("student.name = %sn", (*ptr).name);
printf("student.roll = %dn", (*ptr).roll);
printf("student.cgpa = %fn", (*ptr).cgpa);
//arrow operator
printf("student->name = %sn", ptr->name);
printf("student->roll = %dn", ptr->roll);
printf("student->cgpa = %fn", ptr->cgpa);
//Passing structure to function
printInfo(s1);
//typedef keyword
coe student1;
student1.roll = 1664;
student1.cgpa = 6.7;
strcpy(student1.name, "sudhir");
return 0;
}
void printInfo(struct student s1) {
printf("student info : n");
printf("name = %sn", s1.name);
printf("roll no = %dn", s1.roll);
printf("cgpa = %fn", 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
typedef struct student {
int roll;
float cgpa;
char name[100];
} stu ;
typedef struct computerengineeringstudent {
int roll;
float cgpa;
char name[100];
} coe;
struct address {
int houseNo;
int block;
char city[100];
char state[100];
};
struct vector {
int x;
int y;
};
void calcSum(struct vector v1, struct vector v2, struct vector sum);
struct complex {
int real;
int img;
};
typedef struct BankAccount {
int accountNo;
char name[100];
} acc ;
int main() {
acc acc1 = {123, "shradha"};
acc acc2 = {124, "rajat"};
acc acc3 = {125, "sudhir"};
printf("acc no = %d", acc1.accountNo);
printf("name = %s", acc1.name);
return 0;
}
void calcSum(struct vector v1, struct vector v2, struct vector sum) {
sum.x = v1.x + v2.x;
sum.y = v1.y + v2.y;
printf("sum of x is : %dn", sum.x);
printf("sum of y is : %dn", 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)
Topics to 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>
int main() {
FILE *fptr;
//Reading a file
char ch;
fptr = fopen("Test.txt", "r");
if(fptr == NULL) {
printf("doesn't exist!n");
} else {
fscanf(fptr, "%c", &ch);
printf("character in file is : %cn", ch);
fscanf(fptr, "%c", &ch);
printf("character in file is : %cn", 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 : %cn", fgetc(fptr));
printf("character in file is : %cn", fgetc(fptr));
printf("character in file is : %cn", fgetc(fptr));
printf("character in file is : %cn", fgetc(fptr));
printf("character in file is : %cn", 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);
return 0;
}
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)
Topics to 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
int main() {
//sizeof function
printf("%dn", sizeof(int));
printf("%dn", sizeof(float));
printf("%dn", 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 = %dn", i+1, ptr[i]);
// }
//calloc
int *ptr = (int *) calloc(5, sizeof(int));
for(int i=0; i<5; i++) {
printf("number %d = %dn", i+1, ptr[i]);
}
//free
free(ptr);
return 0;
}

More Related Content

PPT
BJT.ppt
PPTX
Advance excel
PPTX
Interview of an entrepreneur
PPTX
Water PPT
PDF
Uniform-Cost Search Algorithm in the AI Environment
PPTX
Presentation on bipolar junction transistor
PPTX
Depth first search [dfs]
PDF
java notes.pdf
BJT.ppt
Advance excel
Interview of an entrepreneur
Water PPT
Uniform-Cost Search Algorithm in the AI Environment
Presentation on bipolar junction transistor
Depth first search [dfs]
java notes.pdf

What's hot (20)

PPTX
Managing input and output operations in c
PPTX
Functions in c
PPT
CPU INPUT OUTPUT
PPTX
Input Output Management In C Programming
PPTX
User defined functions in C
DOCX
Let us C (by yashvant Kanetkar) chapter 3 Solution
PDF
Modular Programming in C
PDF
Chapter 6 Balagurusamy Programming ANSI in c
 
PPT
Mesics lecture 5 input – output in ‘c’
PDF
STRUCTURE AND UNION IN C MRS.SOWMYA JYOTHI.pdf
PDF
Chapter 3 : Balagurusamy Programming ANSI in C
 
PDF
Keywords, identifiers ,datatypes in C++
PPTX
What are variables and keywords in c++
PDF
Let us c(by Yashwant Kanetkar) 5th edition solution chapter 1
PPTX
Programming in C Presentation upto FILE
PPT
Types of operators in C
PDF
Let us c chapter 4 solution
DOCX
Practical File of C Language
PPTX
Pointer in c
PPTX
Constants, Variables, and Data Types
Managing input and output operations in c
Functions in c
CPU INPUT OUTPUT
Input Output Management In C Programming
User defined functions in C
Let us C (by yashvant Kanetkar) chapter 3 Solution
Modular Programming in C
Chapter 6 Balagurusamy Programming ANSI in c
 
Mesics lecture 5 input – output in ‘c’
STRUCTURE AND UNION IN C MRS.SOWMYA JYOTHI.pdf
Chapter 3 : Balagurusamy Programming ANSI in C
 
Keywords, identifiers ,datatypes in C++
What are variables and keywords in c++
Let us c(by Yashwant Kanetkar) 5th edition solution chapter 1
Programming in C Presentation upto FILE
Types of operators in C
Let us c chapter 4 solution
Practical File of C Language
Pointer in c
Constants, Variables, and Data Types
Ad

Similar to C language concept with code apna college.pdf (20)

PPTX
M2 (1).pptxisedepofengiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii
PDF
sodapdf-converted into ppt presentation(1).pdf
PPTX
Fundamentals of computer programming by Dr. A. Charan Kumari
PDF
9.C Programming
PPT
Unit 5 Foc
 
PPTX
the refernce of programming C notes ppt.pptx
DOCX
Program flowchart
PPT
Fucntions & Pointers in C
PDF
7 functions
PDF
The best every notes on c language is here check it out
DOCX
Practical write a c program to reverse a given number
DOCX
Practical write a c program to reverse a given number
PDF
DSC program.pdf
PPTX
Input output functions
PDF
C lab programs
PDF
C lab programs
DOCX
C programming Lab 2
PDF
The solution manual of c by robin
M2 (1).pptxisedepofengiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii
sodapdf-converted into ppt presentation(1).pdf
Fundamentals of computer programming by Dr. A. Charan Kumari
9.C Programming
Unit 5 Foc
 
the refernce of programming C notes ppt.pptx
Program flowchart
Fucntions & Pointers in C
7 functions
The best every notes on c language is here check it out
Practical write a c program to reverse a given number
Practical write a c program to reverse a given number
DSC program.pdf
Input output functions
C lab programs
C lab programs
C programming Lab 2
The solution manual of c by robin
Ad

Recently uploaded (20)

PPTX
Introduction-to-Cloud-ComputingFinal.pptx
PPTX
climate analysis of Dhaka ,Banglades.pptx
PPTX
Introduction to Basics of Ethical Hacking and Penetration Testing -Unit No. 1...
PPTX
Introduction to Firewall Analytics - Interfirewall and Transfirewall.pptx
PDF
.pdf is not working space design for the following data for the following dat...
PDF
TRAFFIC-MANAGEMENT-AND-ACCIDENT-INVESTIGATION-WITH-DRIVING-PDF-FILE.pdf
PPTX
STUDY DESIGN details- Lt Col Maksud (21).pptx
PPTX
iec ppt-1 pptx icmr ppt on rehabilitation.pptx
PDF
168300704-gasification-ppt.pdfhghhhsjsjhsuxush
PPTX
DISORDERS OF THE LIVER, GALLBLADDER AND PANCREASE (1).pptx
PPTX
Acceptance and paychological effects of mandatory extra coach I classes.pptx
PPTX
Computer network topology notes for revision
PPTX
01_intro xxxxxxxxxxfffffffffffaaaaaaaaaaafg
PPTX
advance b rammar.pptxfdgdfgdfsgdfgsdgfdfgdfgsdfgdfgdfg
PPTX
Business Acumen Training GuidePresentation.pptx
PPTX
Qualitative Qantitative and Mixed Methods.pptx
PPTX
1_Introduction to advance data techniques.pptx
PPT
ISS -ESG Data flows What is ESG and HowHow
PPT
Reliability_Chapter_ presentation 1221.5784
Introduction-to-Cloud-ComputingFinal.pptx
climate analysis of Dhaka ,Banglades.pptx
Introduction to Basics of Ethical Hacking and Penetration Testing -Unit No. 1...
Introduction to Firewall Analytics - Interfirewall and Transfirewall.pptx
.pdf is not working space design for the following data for the following dat...
TRAFFIC-MANAGEMENT-AND-ACCIDENT-INVESTIGATION-WITH-DRIVING-PDF-FILE.pdf
STUDY DESIGN details- Lt Col Maksud (21).pptx
iec ppt-1 pptx icmr ppt on rehabilitation.pptx
168300704-gasification-ppt.pdfhghhhsjsjhsuxush
DISORDERS OF THE LIVER, GALLBLADDER AND PANCREASE (1).pptx
Acceptance and paychological effects of mandatory extra coach I classes.pptx
Computer network topology notes for revision
01_intro xxxxxxxxxxfffffffffffaaaaaaaaaaafg
advance b rammar.pptxfdgdfgdfsgdfgsdgfdfgdfgsdfgdfgdfg
Business Acumen Training GuidePresentation.pptx
Qualitative Qantitative and Mixed Methods.pptx
1_Introduction to advance data techniques.pptx
ISS -ESG Data flows What is ESG and HowHow
Reliability_Chapter_ presentation 1221.5784

C language concept with code apna college.pdf

  • 1. Variables Variable is the name of a memory location which stores some data. 25 S a b Memory
  • 2. Variables Rules a. Variables are case sensitive b. 1st character is alphabet or '_' c. no comma/blank space d. No other symbol other than '_'
  • 4. 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', '#', '&'
  • 5. 32 Keywords in C Keywords Reserved words that have special meaning to the compiler
  • 6. 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
  • 7. Program Structure #include<stdio.h> int main() { printf("Hello World"); return 0; }
  • 8. Comments Single Line Multiple Line Lines that are not part of program // /* */
  • 9. Output printf(" Hello World "); printf(" kuch bhi n"); new line
  • 10. Output printf(" age is %d ", age); printf(" value of pi is %f ", pi); printf(" star looks like this %c ", star); CASES integers 1. 2. real numbers 3. characters
  • 12. Compilation Hello.c C Compiler A computer program that translates C code into machine code a.exe (windows) a.out (linux & mac)
  • 13. C Language Tutorial (Basic to Advanced) Topics to 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> int main() { printf("Hello World"); return 0; } 2. Variables & Data Types + Constants & Keywords #include<stdio.h> int main() { int number; int age; int price; return 0; }
  • 14. #include<stdio.h> int main() { int age = 22; float pi = 3.14; char percentage = '%'; return 0; } 3. Comments #include<stdio.h> //This program prints Hello World int main() { printf("Hello World"); return 0; } 4. Output #include<stdio.h> int main() { int age = 22; float pi = 3.14; char percentage = '%'; printf("age is %d", age); printf("age is %f", pi); printf("age is %c", percentage); return 0; } 5. Input (Sum of 2 numbers) #include<stdio.h> int main() { int a, b; printf("enter a n"); scanf("%d", &a); printf("enter b n");
  • 15. scanf("%d", &b); printf("sum of a & b is : %d n", a+b); return 0; } 6. Practice Qs 1 (Area of Square) #include<stdio.h> //area of square int main() { int side; scanf("%d", &side); printf("%d", side * side); return 0; } 7. Practice Qs 2 (Area of Circle) #include<stdio.h> //area of square int main() { float radius; scanf("%f", &radius); printf("%f", 3.14 * radius * radius); return 0; }
  • 16. Instructions These are statements in a Program Types Type Declaration Instructions Control Instructions Arithmetic Instructions
  • 17. 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;
  • 18. Arithmetic Instructions a + b Operand 1 Operand 2 Operator NOTE - single variable on the LHS
  • 19. 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
  • 20. Modular Operator % Returns remainder for int 3 % 2 = 1 -3 % 2 = -1 Arithmetic Instructions
  • 21. Arithmetic Instructions Type Conversion int int op int int float op op float float float float
  • 22. Arithmetic Instructions Operator Precedence *, /, % +, - = x = 4 + 9 * 10 x = 4 * 3 / 6 * 2
  • 23. Arithmetic Instructions Associativity (for same precedence) Left to Right x = 4 * 3 / 6 * 2
  • 24. Instructions Control Instructions Used to determine flow of program a. Sequence Control b. Decision Control d. Case Control c. Loop Control
  • 25. Operators a. Arithmetic Operators b. Relational Operators d. Bitwise Operators c. Logical Operators e. Assignment Operators f. Ternary Operator
  • 27. Operators && AND || OR ! NOT Logical Operators
  • 30. C Language Tutorial (Basic to Advanced) Topics to 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> int main() { int age = 22; int oldAge = age; int newAge = oldAge + 2; printf("new age is : %d", newAge); int rupee = 1, dollar; dollar = 74; /* order of declaration is important - Wrong Declaration Order float pi = 3.14; float area = pi * rad * rad; float rad = 3; */
  • 31. // valid declaration int age1, age2, age3; age1 = age2 = age3 = 22; //invalid //int a1 = a2 = a3 = 22; return 0; } 2. Arithmetic Instructions #include<stdio.h> int main() { int a = 1, b = 2, c = 3; //valid a = b + c; //invalid // b + c = a; printf("%d n", 3 % 2); printf("%d n", -3 % 2); return 0; } > Type Conversion #include<stdio.h> int main() { 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); return 0; } > Associativity #include<stdio.h> int main() { printf(" Output : %d", 5+2/2*3);
  • 32. return 0; } 3. Relational Operator #include<stdio.h> int main() { 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); return 0; } 4. Logical Operator #include<stdio.h> int main() { 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)); return 0; }
  • 33. 5. Assignment Operator # include <stdio.h> int main() { int a = 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); return 0; } V
  • 35. if-else if(Condition) { //do something if TRUE } else { //do something if FALSE } Ele is optional block can also work without {}
  • 36. else if if(Condition 1) { //do something if TRUE } else if (Condition 2) { //do something if 1st is FALSE & 2nd is TRUE }
  • 37. Conditional Operators Condition ? doSomething if TRUE : doSomething if FALSE; give 1 & 0 cases Ternary
  • 38. Conditional Operators switch(number) { case C1: //do something break; case C2 : //do something break; default : //do something } switch
  • 39. Conditional Operators a. Cases can be in any order switch Properties b. Nested switch (switch inside switch) are allowed
  • 40. C Language Tutorial (Basic to Advanced) Topics to 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> int main() { int age = 19; if(age >= 18) { printf("you are an adult"); } else { printf("you are not an adult"); } return 0; } > check if a number is odd or even #include<stdio.h> int main() { int number;
  • 41. scanf("%d", &number); if(number % 2 == 0) { printf("even"); } else { printf("odd"); } return 0; } > Use of else if #include<stdio.h> int main() { int age; printf("Enter age : "); scanf("%d", &age); if(age < 12) { printf("child"); } else if(age < 18) { printf("teenager"); } else { printf("adult"); } return 0; } 2. Ternary Operator #include<stdio.h> int main() { int age; printf("Enter age : "); scanf("%d", &age); age > 18 ? printf("adult n") : printf("not adult n"); int number = 7;
  • 42. int luckyNumber = 7; number == luckyNumber ? printf("you are lucky n") : printf("you are not lucky n"); return 0; } 3. Switch (integer) #include<stdio.h> #include<math.h> int main() { int day = 5; switch(day) { case 1 : printf("monday n"); break; case 2 : printf("tuesday n"); break; case 3 : printf("wednesday n"); break; case 4 : printf("thursday n"); break; case 5 : printf("friday n"); break; case 6 : printf("saturday n"); break; case 7 : printf("sunday n"); break; } return 0; } 4. Switch (character) #include<stdio.h> #include<math.h> int main() { char day = 'f'; switch(day) { case 'm' : printf("monday n"); break;
  • 43. 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; } return 0; }
  • 44. Loop Control Instructions Types for do while while To repeat some parts of the program
  • 45. for Loop for(initialisation; condition; updation) { //do something }
  • 46. - Increment Operator Special Things - Decrement Operator - Loop counter can be float or even character - Infinite Loop
  • 48. do { //do something } while(condition); do while Loop
  • 49. exit the loop break Statement
  • 50. skip to next iteration continue Statement
  • 51. Nested Loops for( .. ) { for( .. ) { } }
  • 52. C Language Tutorial (Basic to Advanced) Topics to 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> int main () { //for loop for(int i=1; i<=100; i++) { printf("%dn", i); } //while loop int i=1; while(i<=100) { printf("%dn", i); i++; } //do while loop i = 1; do {
  • 54. Take Argument Do Work Return Result block of code that performs particular task Functions increase code reusability it can be used multiple times
  • 55. Function Prototype Syntax void printHello( ); > Tell the compiler 1
  • 57. Syntax Function Call int main() { return 0; } printHello( ); 3 > Use the Work
  • 58. - Execution always starts from main Properties - A function gets called directly or indirectly from main - There can be multiple functions in a program
  • 59. Function Types Library function User- defined Special functions inbuilt in C declared & defined by programmer scanf( ), printf( )
  • 60. Passing Arguments functions can take value & give some value parameter return value
  • 61. Passing Arguments void printHello( ); void printTable(int n); int sum(int a, int b);
  • 62. Passing Arguments functions can take value & give some value parameter return value
  • 63. 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
  • 64. 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
  • 65. Recursion When a function calls itself, it's called recursion
  • 66. 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.
  • 67. C Language Tutorial (Basic to Advanced) Topics to 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 void printHello(); int main() { //function call printHello(); return 0; } //function definition void printHello() { printf("Hello!n"); } 2. Function to calculate square of a number
  • 68. # include <stdio.h> //function to calculate square of a number int calcSquare(int n); int main() { int n; printf("enter n : "); scanf("%d", &n); printf("square is : %d", calcSquare(n)); return 0; } int calcSquare(int n) { return n * n; } 3. Function to calculate n factorial (using recursion) # include <stdio.h> //function to print factorial of n int factorial(int n); int main() { int n; printf("enter n : "); scanf("%d", &n); printf("factorial is : %d", factorial(n)); return 0; } int factorial(int n) { if(n == 0) { return 1; } int factnm1 = factorial(n-1); int factn = factnm1 * n; return factn; }
  • 69. Pointers A variable that stores the memory address of another variable 22 age Memory 2010 ptr 2010 2013
  • 70. Syntax int age = 22; int *ptr = &age; int _age = *ptr; 22 age Memory 2010 ptr 2010 2013
  • 73. Pointer to Pointer A variable that stores the memory address of another pointer 22 age Memory 2010 ptr 2010 2013 pptr 2013 2012
  • 74. Pointer to Pointer Syntax int **pptr; char **pptr; float **pptr;
  • 75. Pointers in Function Call Call by Value call by Reference We pass value of variable as argument We pass address of variable as argument
  • 76. C Language Tutorial (Basic to Advanced) Topics to 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> int main() { int age = 22; int *ptr = &age; int _age = *ptr; printf("%dn", _age); //address printf("%pn", &age); printf("%pn", ptr); printf("%pn", &ptr); //data printf("%dn", age); printf("%dn", *ptr); printf("%dn", *(&age)); return 0;
  • 77. } 2. Pointers in Function call # include <stdio.h> void square(int n); void _square(int* n); int main() { int number = 4; //call by value square(number); printf("n is : %dn", number); //call by reference _square(&number); printf("n is : %dn", number); return 0; } void square(int n) { n = n * n; printf("square is : %dn", n); } void _square(int* n) { *n = *n * *n; printf("square is : %dn", *n); } 3. Swap 2 numbers # include <stdio.h> void swap(int a, int b); void _swap(int* a, int *b); int main() { int x = 3, y = 5; //call by value swap(x, y);
  • 78. printf("x = %d & y = %dn", x, y); //call by reference _swap(&x, &y); printf("x = %d & y = %dn", x, y); return 0; } void swap(int a, int b) { int t = a; a = b; b = a; } void _swap(int* a, int* b) { int t = *a; *a = *b; *b = *a; }
  • 79. Arrays Collection of similar data types stored at contiguous memory locations
  • 81. Input & Output scanf("%d", &marks[0]); printf("%d", marks[0]);
  • 82. Inititalization of Array int marks[ ] = {97, 98, 89}; int marks[ 3 ] = {97, 98, 89}; Memory Reserved :
  • 83. Pointer Arithmetic Pointer can be incremented & decremented CASE 1
  • 85. Pointer Arithmetic - We can also subtract one pointer from another - We can also compare 2 pointers
  • 86. Array is a Pointer int *ptr = &arr[0]; int *ptr = arr;
  • 87. Traverse an Array int aadhar[10]; int *ptr = &aadhar[0];
  • 88. Arrays as Function Argument printNumbers(arr, n); void printNumbers (int arr[ ], int n) void printNumbers (int *arr, int n) OR //Function Declaration //Function Call
  • 89. 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]
  • 90. C Language Tutorial (Basic to Advanced) Topics to 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> int main() { int marks[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
  • 91. return 0; } 2. Pointer Arithmetic # include <stdio.h> int main() { int age = 22; int *ptr = &age; int _age = 25; int *_ptr = &_age; printf("%un", ptr); ptr++; printf("%un", ptr); ptr--; printf("%un", ptr); ptr = ptr - _ptr; printf("%un", ptr); ptr = &_age; printf("%dn", ptr == _ptr); return 0; } 3. Accessing an Array # include <stdio.h> void printNumbers(int *arr, int n); void _printNumbers(int arr[], int n); int main() { int arr[] = {1, 2, 3, 4, 5, 6}; printNumbers(arr, 6); printNumbers(arr, 6); return 0; }
  • 92. void printNumbers(int *arr, int n) { for(int i=0; i<n; i++) { printf("%d : %dn", i, arr[i]); } } void _printNumbers(int arr[], int n) { for(int i=0; i<n; i++) { printf("%d : %dn", i, arr[i]); } }
  • 93. 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'};
  • 94. 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";
  • 95. 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
  • 96. String Format Specifier "%s" printf("%s", name); char name[ ] = "Shradha";
  • 97. IMPORTANT scanf( ) cannot input multi-word strings with spaces Here, gets( ) & puts( ) come into picture
  • 98. 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
  • 99. 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
  • 100. Standard Library Functions 1 strlen(str) count number of characters excluding '0' <string.h>
  • 101. Standard Library Functions 2 strcpy(newStr, oldStr) copies value of old string to new string <string.h>
  • 102. Standard Library Functions 3 strcat(firstStr, secStr) concatenates first string with second string <string.h> firstStr should be large enough
  • 103. 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)
  • 104. C Language Tutorial (Basic to Advanced) Topics to 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> int main() { //declaration char name[] = "Shradha Khapra"; char course[] = {'a','p', 'n', 'a', ' ', 'c', 'o', 'l', 'l', 'e', 'g', 'e', '0'}; //printing string for(int i=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);
  • 105. } printf("n"); //printing using format specifier printf("%sn", name); //input a string char firstName[40]; printf("enter first name : "); scanf("%s", firstName); printf("you first name is %sn", firstName); char fullName[40]; printf("enter full name : "); scanf("%s", fullName); printf("you first name is %sn", fullName); // gets & puts char fullName[40]; printf("enter full name : "); fgets(fullName, 40, stdin); puts(fullName); //Library Functions char name[] = "Shradha"; int length = strlen(name); printf("the length of name : %dn", length); char oldVal[] = "oldValue"; char newVal[50]; strcpy(newVal, oldVal); puts(newVal); char firstStr[50] = "Hello "; char secStr[] = "World"; strcat(firstStr, secStr); puts(firstStr); char str1[] = "Apple"; char str2[] = "Banana"; printf("%dn", strcmp(str1, str2)); //enter String using %c
  • 106. printf("enter string : "); char str[100]; char ch; int i = 0; while(ch != 'n') { scanf("%c", &ch); str[i] = ch; i++; } str[i] = '0'; puts(str); return 0; } > 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[]); void checkChar(char str[], char ch); int main() { char str[] = "ApnaCollege"; char ch = 'x'; checkChar(str, ch); } void checkChar(char str[], char ch) { for(int i=0; str[i] != '0'; i++) { if(str[i] == ch) { printf("character is present!"); return;
  • 107. } } 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);
  • 108. // } // 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"); // }
  • 109. Structures a collection of values of different data types EXAMPLE name (String) For a student store the following : roll no (Integer) cgpa (Float)
  • 110. Syntax struct student { char name[100]; int roll; float cgpa; }; struct student s1; s1.cgpa = 7.5;
  • 111. Syntax struct student { char name[100]; int roll; float cgpa; }
  • 112. Structures in Memory struct student { char name[100]; int roll; float cgpa; } name 2010 cgpa 2114 2110 roll structures are stored in contiguous memory locations
  • 113. Benefits of using Structures - Good data management/organization - Saves us from creating too many variables
  • 114. 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;
  • 115. Initializing Structures struct student s1 = { "shradha", 1664, 7.9}; struct student s2 = { "rajat", 1552, 8.3}; struct student s3 = { 0 };
  • 116. Pointers to Structures struct student *ptr; ptr =&s1; struct student s1;
  • 118. Passing structure to function void printInfo(struct student s1); //Function Prototype
  • 119. typedef Keyword used to create alias for data types coe student1;
  • 120. C Language Tutorial (Basic to Advanced) Topics to 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> struct student { char name[100]; int roll; float cgpa; }; typedef struct ComputerEngineeringStudent{ int roll; float cgpa; char name[100]; } coe; void printInfo(struct student s1); int main() {
  • 121. struct student s1; // s1.name = "Shradha"; // not a modifiable value strcpy(s1.name,"Shradha"); s1.roll = 64; s1.cgpa = 9.2; printf("student info : n"); printf("name = %sn", s1.name); printf("roll no = %dn", s1.roll); printf("cgpa = %fn", s1.cgpa); //array of structures struct student IT[60]; struct student COE[60]; struct student ECE[60]; //declaration struct student s2 = {"Rajat", 1552, 8.6}; struct student s3 = {0}; printf("roll no of s2 = %dn", s2.roll); printf("roll no of s3 = %dn", s3.roll); //pointer to structure struct student *ptr = &s1; printf("student.name = %sn", (*ptr).name); printf("student.roll = %dn", (*ptr).roll); printf("student.cgpa = %fn", (*ptr).cgpa); //arrow operator printf("student->name = %sn", ptr->name); printf("student->roll = %dn", ptr->roll); printf("student->cgpa = %fn", ptr->cgpa); //Passing structure to function printInfo(s1); //typedef keyword coe student1; student1.roll = 1664; student1.cgpa = 6.7;
  • 122. strcpy(student1.name, "sudhir"); return 0; } void printInfo(struct student s1) { printf("student info : n"); printf("name = %sn", s1.name); printf("roll no = %dn", s1.roll); printf("cgpa = %fn", 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 typedef struct student { int roll; float cgpa; char name[100]; } stu ; typedef struct computerengineeringstudent { int roll; float cgpa; char name[100]; } coe; struct address { int houseNo; int block; char city[100]; char state[100]; }; struct vector { int x;
  • 123. int y; }; void calcSum(struct vector v1, struct vector v2, struct vector sum); struct complex { int real; int img; }; typedef struct BankAccount { int accountNo; char name[100]; } acc ; int main() { acc acc1 = {123, "shradha"}; acc acc2 = {124, "rajat"}; acc acc3 = {125, "sudhir"}; printf("acc no = %d", acc1.accountNo); printf("name = %s", acc1.name); return 0; } void calcSum(struct vector v1, struct vector v2, struct vector sum) { sum.x = v1.x + v2.x; sum.y = v1.y + v2.y; printf("sum of x is : %dn", sum.x); printf("sum of y is : %dn", sum.y); }
  • 125. 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
  • 126. Operation on Files Create a File Open a File Close a File Read from a File Write in a File
  • 127. Types of Files Text Files .exe, .mp3, .jpg Binary Files textual data .txt, .c binary data
  • 128. 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;
  • 129. Opening a File fptr = fopen("filename", mode); FILE *fptr; Closing a File fclose(fptr);
  • 130. 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"
  • 131. BEST Practice Check if a file exists before reading from it.
  • 132. Reading from a file fscanf(fptr, "%c", &ch); char ch;
  • 133. Writing to a file fprintf(fptr, "%c", ch); char ch = 'A';
  • 134. Read & Write a char fgetc(fptr) fputc( 'A', fptr)
  • 135. EOF (End Of File) fgetc returns EOF to show that the file has ended
  • 136. C Language Tutorial (Basic to Advanced) Topics to 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> int main() { FILE *fptr; //Reading a file char ch; fptr = fopen("Test.txt", "r"); if(fptr == NULL) { printf("doesn't exist!n"); } else { fscanf(fptr, "%c", &ch); printf("character in file is : %cn", ch); fscanf(fptr, "%c", &ch); printf("character in file is : %cn", ch); fclose(fptr); } //Writing in a file ch = 'M'; fptr = fopen("NewFile.txt", "w");
  • 137. fprintf(fptr, "%cANGO", ch); fclose(fptr); //fgets fptr = fopen("NewFile.txt", "r"); printf("character in file is : %cn", fgetc(fptr)); printf("character in file is : %cn", fgetc(fptr)); printf("character in file is : %cn", fgetc(fptr)); printf("character in file is : %cn", fgetc(fptr)); printf("character in file is : %cn", 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); return 0; }
  • 138. 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.
  • 139. Functions for DMA a. malloc( ) b. calloc( ) c. free( ) d. realloc( )
  • 140. malloc( ) takes number of bytes to be allocated & returns a pointer of type void ptr = (*int) malloc(5 * sizeof(int)); memory allocation
  • 141. calloc( ) initializes with 0 ptr = (*int) calloc(5, sizeof(int)); continuous allocation
  • 142. free( ) We use it to free memory that is allocated using malloc & calloc free(ptr);
  • 143. realloc( ) reallocate (increase or decrease) memory using the same pointer & size. ptr = realloc(ptr, newSize);
  • 144. C Language Tutorial (Basic to Advanced) Topics to 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 int main() { //sizeof function printf("%dn", sizeof(int)); printf("%dn", sizeof(float)); printf("%dn", 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 = %dn", i+1, ptr[i]);
  • 145. // } //calloc int *ptr = (int *) calloc(5, sizeof(int)); for(int i=0; i<5; i++) { printf("number %d = %dn", i+1, ptr[i]); } //free free(ptr); return 0; }