0% found this document useful (0 votes)
3 views160 pages

Notes Programming

good material

Uploaded by

23ce01050
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
3 views160 pages

Notes Programming

good material

Uploaded by

23ce01050
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 160

CS1L001 - Introduction to Programming and Data Structures

Instructor
Manas Jyoti Kashyop (manaskashyop@iitbbs.ac.in)
Functions
Functions in C

Functions help us to define our own subtasks that we want to


use in bigger tasks and program them to reuse whenever
needed. This approach is called modular approach (Divide and
Conquer technique) to program design.

Functions help us to re-use previously written codes.


Example: pow(), sqrt(), printf(), scanf()

We can define our own functions and use them


Function example
#include<stdio.h>
int square(int); /* function prototype */

/* function main begins program execution */


int main(){
int i;
for(i=1; i < 10; i++){
printf("%d %d\n",i,square(i)); /* call to function square()*/
}
return 0; /* indicates succesful termincation */
}

/* function definition */
int square(int x){/* x is a copy of argument to the function */
int result = x * x;
return result; /* returns square of x */
}
Function example
#include<stdio.h> Function prototype
int square(int); /* function prototype */

/* function main begins program execution */


int main(){ Function call
int i;
for(i=1; i < 10; i++){
printf("%d %d\n",i,square(i)); /* call to function square()*/
}
return 0; /* indicates succesful termincation */
} Function definition
/* function definition */
int square(int x){/* x is a copy of argument to the function */
int result = x * x;
return result; /* returns square of x */
}
Function Definition
/* function definition */
int square(int x){/* x is a copy of argument to the function */
int result = x * x;
return result; /* returns square of x */
}

return-value-type function-name( parameter-list ){

Statements; /* function block */

}
Function Definition
/* function definition */
int square(int x){/* x is a copy of argument to the function */
int result = x * x;
return result; /* returns square of x */
}

return-value-type function-name( parameter-list ){

Statements; /* function block */

A function cannot be defined inside another function

Syntax Error!
Function Prototype

int square(int); /* function prototype */

return-value-type function-name( datatypes-parameter-list );


Function Prototype

int square(int); /* function prototype */

return-value-type function-name( datatypes-parameter-list );

Forgetting the semicolon

Syntax Error!
Function example
#include<stdio.h>
int findMaximum(int, int, int); /* function prototype */

int main(){
int number1, number2, number3;
printf("Enter three numbers: ");
scanf("%d%d%d",&number1, &number2, &number3);
printf("Maximum number is: %d\n",findMaximum(number1,number2,number3)); /* function call */

return 0;
}

int findMaximum(int a, int b, int c){ /* function definition */


int max = a;
if(b > max){
max = b;
}
if(c > max){
max = c;
}
return max;
}
Function example
#include<stdio.h>
#include<math.h>
long int DO(int);

int main(){
int number;
printf("Enter a number: ");
scanf("%d",&number);
printf("You entered: %ld\n”, DO(number));
}

long int DO(int x){


long int y = 0;
int counter = 0;
while(x){
y = y + (x%2)*pow(10,counter);
counter++;
x = x/2;
}

return y;
}
Function example
#include<stdio.h>

float findArea(float);

int main(){
float radius, area;
printf("Enter radius of a circle: ");
scanf("%f",&radius);
area = findArea(radius);
printf("Area of the circle: %f\n",findArea(radius));

return 0;
}
Function example
#include<stdio.h>

float findArea(float);

int main(){
float radius, area;
printf("Enter radius of a circle: ");
scanf("%f",&radius);
area = findArea(radius);
printf("Area of the circle: %f\n",findArea(radius));

return 0;
}

float findArea(float radius){


return 3.14 * radius * radius;
}
Function example
#include<stdio.h>
#include<math.h>

int isPrime(int);

int main(){
int number;
printf("Enter a number: ");
scanf("%d",&number);
if(isPrime(number)){
printf("%d is a prime number\n",number);
}
else{
printf("%d is not a prime number\n",number);
}
return 0;
}
Function example
#include<stdio.h>
#include<math.h>
int isPrime(int);
int main(){
int number;
printf("Enter a number: ");
scanf("%d",&number);
if(isPrime(number)){
printf("%d is a prime number\n",number);
}
else{
printf("%d is not a prime number\n",number);
}
return 0;
}

int isPrime(int x){


int primeFlag = 1;
int i;
for(i = 2; i <= sqrt(x); i++){
if(x%i == 0){
primeFlag = 0;
return primeFlag;
}
}
return primeFlag;
}
Function example
#include<stdio.h>
long int computeFactorial(int);

int main(){
int number;
printf("Enter a number: ");
scanf("%d",&number);
printf("Factorial of %d is: %ld\n", number, computeFactorial(number));

return 0;
}
Function example
#include<stdio.h>
long int computeFactorial(int);

int main(){
int number;
printf("Enter a number: ");
scanf("%d",&number);
printf("Factorial of %d is: %ld\n", number, computeFactorial(number));

return 0;
}

long int computeFactorial(int num){


long int numFact = 1;
while(num){
numFact = numFact * num;
num--;
}
return numFact;
}
Function example
#include<stdio.h>
long int computeFactorial(int);
float compute_nCr(int,int);

int main(){
int n,r;
printf("Enter n and r: ");
scanf("%d%d",&n,&r);
printf("%dC%d is : %f\n",n,r,compute_nCr(n,r));

return 0;
}
Nested Functions example
#include<stdio.h>
long int computeFactorial(int);
float compute_nCr(int,int);

int main(){
int n,r;
printf("Enter n and r: ");
scanf("%d%d",&n,&r);
printf("%dC%d is : %f\n",n,r,compute_nCr(n,r));

return 0;
}

float compute_nCr(int n, int r){


float nCr = computeFactorial(n)/(computeFactorial(r) * computeFactorial(n-r));
return nCr;
}

long int computeFactorial(int num){


long int numFact = 1;
while(num){
numFact = numFact * num;
num--;
}
return numFact;
}
Local variables

Variables defined in a function are local variables of the function

Local variables can be accessed only within the function in which


they are declared

- Local variables cease to exist when the function returns


- Every execution of the function uses a new set of local variables
- Parameters are also local to the function
Variables

Variables defined in a function are local variables of the function

Local variables can be accessed only within the function in which


they are declared

- Local variables cease to exist when the function returns


- Every execution of the function uses a new set of local variables
- Parameters are also local to the function

Scope of a variable:
- Within the block in which the variable is defined
- Block: group of statements enclosed within { }
Variables

Variables defined in a function are local variables of the function

Local variables can be accessed only within the function in which


they are declared

- Local variables cease to exist when the function returns


- Every execution of the function uses a new set of local variables
- Parameters are also local to the function

Scope of a variable:
- Within the block in which the variable is defined
- Block: group of statements enclosed within { }

Local variable scope: the function in which it is define


Global variable scope: Entire program
Scope of variables example
#include<stdio.h>
int num_global = 13; /* global variable */
void userFunction();

int main(){
int number = 10; /* local variable for main() */
printf("Number in main: %d\n",number);
printf("Global variable in main: %d\n",num_global);
userFunction();

return 0;
}

void userFunction(){
int number = 130; /* local variable for userFunction() */
printf("Number in userFunction: %d\n",number);
printf("Global variable in userFunction: %d\n",num_global);
}
Scope of variables example
#include<stdio.h>
void userFunction();

int main(){
int number = 10;
printf("Number in main: %d\n",number);
userFunction();
printf("Number in main: %d\n",number);
return 0;
}

void userFunction(){
int number = 130;
printf("Number in userFunction: %d\n",number);
number = number/2;
printf("Number in userFunction: %d\n",number);
}
Scope of variables example
#include<stdio.h>
int num_global = 13; /* global variable */
void userFunction();

int main(){
int number = 10;
printf("Number in main: %d\n",number);
printf("Global variable in main: %d\n",num_global);
userFunction();

return 0;
}

void userFunction(){
int number = 130;
int num_global = 111;
printf("Number in userFunction: %d\n",number);
printf("Global variable in userFunction: %d\n",num_global);
}
Nested Functions example
#include<stdio.h>
void firstFunction();
void secondFunction();
void thirdFunction();

int main(){
firstFunction();
printf("Program control is in main function\n");
return 0;
}
void firstFunction(){
printf("Program control is in first function\n");
secondFunction();
return;
}

void secondFunction(){
printf("Program control is in second function\n");
thirdFunction();
return;
}

void thirdFunction(){
printf("Program control is in third function\n");
return;
}
Nested Functions example
#include<stdio.h>
void firstFunction();
void secondFunction();
void thirdFunction();

int main(){
firstFunction();
printf("Program control is in main function\n");
return 0;
}
void firstFunction(){
printf("Program control is in first function\n");
secondFunction();
return;
}

void secondFunction(){
Program control is in first function
printf("Program control is in second function\n");
thirdFunction(); Program control is in second function
return; Program control is in third function
} Program control is in main function

void thirdFunction(){
printf("Program control is in third function\n");
return;
}
Nested Functions example
#include<stdio.h>
void firstFunction();
void secondFunction();
void thirdFunction();

int main(){
printf("Program control is in main function\n");
firstFunction();
return 0;
}
void firstFunction(){
secondFunction();
printf("Program control is in first function\n");
}

void secondFunction(){
thirdFunction();
printf("Program control is in second function\n");
}

void thirdFunction(){
printf("Program control is in third function\n");
}
Nested Functions example
#include<stdio.h>
void firstFunction();
void secondFunction();
void thirdFunction();

int main(){
printf("Program control is in main function\n");
firstFunction();
return 0;
}
void firstFunction(){
secondFunction(); Program control is in main function
printf("Program control is in first function\n"); Program control is in third function
} Program control is in second function
Program control is in first function
void secondFunction(){
thirdFunction();
printf("Program control is in second function\n");
}

void thirdFunction(){
printf("Program control is in third function\n");
}
Nested Functions example
#include<stdio.h>
void firstFunction();
void secondFunction();
void thirdFunction();

int main(){
printf("Program control is in main function\n");
firstFunction();
return 0;
}
void firstFunction(){
secondFunction();
return;
printf("Program control is in first function\n");
}

void secondFunction(){
thirdFunction();
return;
printf("Program control is in second function\n");
}

void thirdFunction(){
printf("Program control is in third function\n");
return;
}
Nested Functions example
#include<stdio.h>
void firstFunction();
void secondFunction();
void thirdFunction();

int main(){
printf("Program control is in main function\n");
firstFunction();
return 0;
}
void firstFunction(){
secondFunction();
return;
printf("Program control is in first function\n");
Program control is in main function
}
Program control is in third function
void secondFunction(){
thirdFunction();
return;
printf("Program control is in second function\n");
}

void thirdFunction(){
printf("Program control is in third function\n");
return;
}
Function example
#include<stdio.h>
int searchLinear(int [], int, int);

int main(){
int listNumbers[] = {17,21,13,49,61,91,99};
int size = sizeof(listNumbers)/sizeof(int);
int key = 21;
if(searchLinear(listNumbers,size,key)){
printf("%d is found in the array\n",key);
}
else{
printf("%d is not found in the array\n",key);
}
return 0;
}

int searchLinear(int ARR[], int N, int key){


int i = 0, foundflag = 0;
while(i < N){
if( key == ARR[i] ){
foundflag = 1;
return foundflag;
}
i++;
}
return foundflag;
}
Function: array as parameter
#include<stdio.h>
void printArray(int [], int);

int main(){
int listNumbers[] = {17,21,13,49,61,91,99};
int size = sizeof(listNumbers)/sizeof(int);
printArray(listNumbers,size);

return 0;
}

void printArray(int ARR[], int N){


int i;
for(i = 0; i < N; i++){
printf("%d ",ARR[i]);
}
printf("\n");
}
Function: array as parameter
#include<stdio.h>
int searchLinear(int ARR[], int N, int key);

int main(){
int listNumbers[] = {17,21,13,49,61,91,99};
int size = sizeof(listNumbers)/sizeof(int);
int key = 21;
if(searchLinear(listNumbers,size,key)){
printf("%d is found in the array\n",key);
}
else{
printf("%d is not found in the array\n",key);
}
return 0;
}
Function: array as parameter
#include<stdio.h>
int searchLinear(int [], int, int);

int main(){
int listNumbers[] = {17,21,13,49,61,91,99};
int size = sizeof(listNumbers)/sizeof(int);
int key = 21;
if(searchLinear(listNumbers,size,key)){
printf("%d is found in the array\n",key);
}
else{
printf("%d is not found in the array\n",key);
}
return 0;
}

int searchLinear(int ARR[], int N, int key){


int i = 0, foundflag = 0;
while(i < N){
if( key == ARR[i] ){
foundflag = 1;
return foundflag;
}
i++;
}
return foundflag;
}
Function: array as parameter
#include<stdio.h>
void reverseArray(int [], int [], int);

int main(){
int listNumbers[] = {17,21,13,49,61,91,99};
int reverseList[7];
int size = sizeof(listNumbers)/sizeof(int);
printArray(listNumbers,size);
reverseArray(listNumbers,reverseList,size);
printArray(reverseList,size);

return 0;
}

void reverseArray(int ARR[], int reverseARR[], int N){

/* Write your code here */


}
Function: array as parameter
#include<stdio.h>
void printArray(int [], int);
void reverseArray(int [], int [], int);

int main(){
int listNumbers[] = {17,21,13,49,61,91,99};
int reverseList[7];
int size = sizeof(listNumbers)/sizeof(int);
printArray(listNumbers,size);
reverseArray(listNumbers,reverseList,size);
printArray(reverseList,size);

return 0;
}

void reverseArray(int ARR[], int reverseARR[], int N){


int i;
for(i = 0; i < N; i++){
reverseARR[N-1-i] = ARR[i];
}
}

void printArray(int ARR[], int N){


int i;
for(i = 0; i < N; i++){
printf("%d ",ARR[i]);
}
printf("\n");
}
Function: array as parameter
#include<stdio.h>
void printArray(int [], int);
void reverseArrayInPlace(int [], int);

int main(){
int listNumbers[] = {17,21,13,49,61,91,99};
int size = sizeof(listNumbers)/sizeof(int);
printArray(listNumbers,size);
reverseArrayInPlace(listNumbers,size);
printArray(listNumbers,size);

return 0;
}

void reverseArrayInPlace(int ARR[], int N){


/* Write your code here */
}

void printArray(int ARR[], int N){


int i;
for(i = 0; i < N; i++){
printf("%d ",ARR[i]);
}
printf("\n");
}
Function: array as parameter
#include<stdio.h>
void printArray(int [], int);
void reverseArrayInPlace(int [], int);

int main(){
int listNumbers[] = {17,21,13,49,61,91,99};
int size = sizeof(listNumbers)/sizeof(int);
printArray(listNumbers,size);
reverseArrayInPlace(listNumbers,size);
printArray(listNumbers,size);

return 0;
}

void reverseArrayInPlace(int ARR[], int N){


int low, high;
int buffer;
for(low = 0, high = N-1 ; low < high; low++, high--){
buffer = ARR[low];
ARR[low] = ARR[high];
ARR[high] = buffer;
}
}

void printArray(int ARR[], int N){


int i;
for(i = 0; i < N; i++){
printf("%d ",ARR[i]);
}
printf("\n");
}
Function: 2D-array as parameter
#include<stdio.h>
const int rSIZE = 3;
const int cSIZE = 3;

void printMatrix(int [][cSIZE]);


void scanMatrix(int [][cSIZE]);

int main(){
int A[rSIZE][cSIZE], B[rSIZE][cSIZE];
printf("Enter matrix A\n");
scanMatrix(A);
printMatrix(A);
return 0;
}

void scanMatrix(int A[][cSIZE]){


int i,j;
for( i = 0; i < rSIZE; i++){
for( j = 0; j < cSIZE; j++){
scanf("%d",&A[i][j]);
}
}
}

void printMatrix(int A[][cSIZE]){


int i,j;
for( i = 0; i < rSIZE; i++){
for( j = 0; j < cSIZE; j++){
printf("%d ",A[i][j]);
}
printf("\n");
}
}
Recursion
Recursion

A function calls itself repeatedly

- F calls F (directly)
- F calls G, G calls H, and H calls F (cyclically in a chain)
Factorial Problem: Basis and Recursion

For a problem to be written in recursive form, two conditions are to


be satisfied:

- It should be possible to express the problem in recursive form


- The problem statement must include a stopping condition

Factorial(n) = 1, if n = 0 /* stopping criteria */

= n * Factorial(n-1), if n > 0 /* recursive form */


Factorial Problem: Basis and Recursion

For a problem to be written in recursive form, two conditions are to


be satisfied:

- It should be possible to express the problem in recursive form


- The problem statement must include a stopping condition

Factorial(n) = 1, if n = 0 /* stopping criteria */

= n * Factorial(n-1), if n > 0 /* recursive form */

Fibonacci(1) = 1 /* stopping criteria */


Fibonacci(2) = 1 /* stopping criteria */

Fibonacci(n) = Fibonacci(n-1) + Fibonacci(n-2), if n > 2


/* recursive form */
Factorial Problem
#include<stdio.h>

long int computeFactorial(int n){


long int n_factorial;
if( n == 0)
return 1;

n_factorial = n * computeFactorial(n-1);
return n_factorial;
}

int main(){
int x = 5;
printf("Factorial of %d is %ld\n",x,computeFactorial(x));
return 0;
}
Factorial Problem
#include<stdio.h>

long int Factorial(int n){


long int n_factorial;
if( n == 0)
return 1;

n_factorial = n * Factorial(n-1);
return n_factorial;
}

int main(){
int x = 5;
printf("Factorial of %d is %ld\n",x,Factorial(x));
return 0;
}

x=5
Factorial( 5 )

main( )
Factorial Problem
#include<stdio.h>

long int Factorial(int n){


long int n_factorial;
if( n == 0)
return 1;

n_factorial = n * Factorial(n-1);
return n_factorial;
}

int main(){
int x = 5;
printf("Factorial of %d is %ld\n",x,Factorial(x));
return 0;
}

n=5
x=5
Factorial( 5 )
n_factorial = 5 * ?

main( ) Factorial( 5 )
Factorial Problem
#include<stdio.h>

long int Factorial(int n){


long int n_factorial;
if( n == 0)
return 1;

n_factorial = n * Factorial(n-1);
return n_factorial;
}

int main(){
int x = 5;
printf("Factorial of %d is %ld\n",x,Factorial(x));
return 0;
}

n=5 n=4
x=5
Factorial( 5 )
n_factorial = 5 * ? n_factorial = 4 * ?

main( ) Factorial( 5 ) Factorial( 4 )


Factorial Problem
#include<stdio.h>

long int Factorial(int n){


long int n_factorial;
if( n == 0)
return 1;

n_factorial = n * Factorial(n-1);
return n_factorial;
}

int main(){
int x = 5;
printf("Factorial of %d is %ld\n",x,Factorial(x));
return 0;
}

n=5 n=4 n=3


x=5
Factorial( 5 )
n_factorial = 5 * ? n_factorial = 4 * ? n_factorial = 3 * ?

main( ) Factorial( 5 ) Factorial( 4 ) Factorial( 3 )


Factorial Problem
#include<stdio.h>

long int Factorial(int n){


long int n_factorial;
if( n == 0)
return 1;

n_factorial = n * Factorial(n-1);
return n_factorial;
}

int main(){
int x = 5;
printf("Factorial of %d is %ld\n",x,Factorial(x));
return 0;
}

n=5 n=4 n=3 n=2


x=5
Factorial( 5 )
n_factorial = 5 * ? n_factorial = 4 * ? n_factorial = 3 * ? n_factorial = 2 * ?

main( ) Factorial( 5 ) Factorial( 4 ) Factorial( 3 ) Factorial( 2 )


Factorial Problem
#include<stdio.h>

long int Factorial(int n){


long int n_factorial;
if( n == 0)
return 1;

n_factorial = n * Factorial(n-1);
return n_factorial;
}

int main(){
int x = 5;
printf("Factorial of %d is %ld\n",x,Factorial(x));
return 0;
}

n=5 n=4 n=3 n=2 n=1


x=5
Factorial( 5 )
n_factorial = 5 * ? n_factorial = 4 * ? n_factorial = 3 * ? n_factorial = 2 * ? n_factorial = 1 * ?

main( ) Factorial( 5 ) Factorial( 4 ) Factorial( 3 ) Factorial( 2 ) Factorial( 1 )


Factorial Problem
#include<stdio.h>

long int Factorial(int n){


long int n_factorial;
if( n == 0)
return 1; Factorial( 0 )
n_factorial = n * Factorial(n-1);
return n_factorial;
} n=0
int main(){
int x = 5;
return 1
printf("Factorial of %d is %ld\n",x,Factorial(x));
return 0;
}

n=5 n=4 n=3 n=2 n=1


x=5
Factorial( 5 )
n_factorial = 5 * ? n_factorial = 4 * ? n_factorial = 3 * ? n_factorial = 2 * ? n_factorial = 1 * ?

main( ) Factorial( 5 ) Factorial( 4 ) Factorial( 3 ) Factorial( 2 ) Factorial( 1 )


Factorial Problem
#include<stdio.h>

long int Factorial(int n){


long int n_factorial;
if( n == 0)
return 1; Factorial( 0 )
n_factorial = n * Factorial(n-1);
return n_factorial;
} n=0
int main(){
int x = 5;
return 1
printf("Factorial of %d is %ld\n",x,Factorial(x));
return 0;
}

n=5 n=4 n=3 n=2 n=1


x=5
Factorial( 5 )
n_factorial = 5 * ? n_factorial = 4 * ? n_factorial = 3 * ? n_factorial = 2 * ? n_factorial = 1 * ?

main( ) Factorial( 5 ) Factorial( 4 ) Factorial( 3 ) Factorial( 2 ) Factorial( 1 )


Factorial Problem
#include<stdio.h>

long int Factorial(int n){


long int n_factorial;
if( n == 0)
return 1;

n_factorial = n * Factorial(n-1);
return n_factorial;
}

int main(){
int x = 5;
printf("Factorial of %d is %ld\n",x,Factorial(x));
return 0;
}

n=5 n=4 n=3 n=2 n=1


x=5
Factorial( 5 )
n_factorial = 5 * ? n_factorial = 4 * ? n_factorial = 3 * ? n_factorial = 2 * 1 n_factorial = 1 * 1

main( ) Factorial( 5 ) Factorial( 4 ) Factorial( 3 ) Factorial( 2 ) Factorial( 1 )


Factorial Problem
#include<stdio.h>

long int Factorial(int n){


long int n_factorial;
if( n == 0)
return 1;

n_factorial = n * Factorial(n-1);
return n_factorial;
}

int main(){
int x = 5;
printf("Factorial of %d is %ld\n",x,Factorial(x));
return 0;
}

n=5 n=4 n=3 n=2


x=5
Factorial( 5 )
n_factorial = 5 * ? n_factorial = 4 * ? n_factorial = 3 * 2 n_factorial = 2 * 1

main( ) Factorial( 5 ) Factorial( 4 ) Factorial( 3 ) Factorial( 2 )


Factorial Problem
#include<stdio.h>

long int Factorial(int n){


long int n_factorial;
if( n == 0)
return 1;

n_factorial = n * Factorial(n-1);
return n_factorial;
}

int main(){
int x = 5;
printf("Factorial of %d is %ld\n",x,Factorial(x));
return 0;
}

n=5 n=4 n=3


x=5
Factorial( 5 )
n_factorial = 5 * ? n_factorial = 4 * 6 n_factorial = 3 * 2

main( ) Factorial( 5 ) Factorial( 4 ) Factorial( 3 )


Factorial Problem
#include<stdio.h>

long int Factorial(int n){


long int n_factorial;
if( n == 0)
return 1;

n_factorial = n * Factorial(n-1);
return n_factorial;
}

int main(){
int x = 5;
printf("Factorial of %d is %ld\n",x,Factorial(x));
return 0;
}

n=5 n=4
x=5
Factorial( 5 )
n_factorial = 5 * 24 n_factorial = 4 * 6

main( ) Factorial( 5 ) Factorial( 4 )


Factorial Problem
#include<stdio.h>

long int Factorial(int n){


long int n_factorial;
if( n == 0)
return 1;

n_factorial = n * Factorial(n-1);
return n_factorial;
}

int main(){
int x = 5;
printf("Factorial of %d is %ld\n",x,Factorial(x));
return 0;
}

x=5 n=5
Factorial( 5
120 n_factorial = 5 * 24

main( ) Factorial( 5 )
Factorial Problem
#include<stdio.h>

long int Factorial(int n){


long int n_factorial;
if( n == 0)
return 1;

n_factorial = n * Factorial(n-1);
return n_factorial;
}

int main(){
int x = 5;
printf("Factorial of %d is %ld\n",x,Factorial(x));
return 0;
}

x=5
Factorial( 5
120

main( )
Recursion Example
#include<stdio.h>
void print(int counter){
int data;
if(counter == 0)
return;
scanf("%d",&data);
print(counter-1);
printf("%d\n",data);
}

int main(){
int counter = 5;
print(counter);
return 0;
}
Recursion Example
#include<stdio.h>
void print(int counter){
int data;
if(counter == 0)
return;
print(counter-1);
scanf("%d",&data);
printf("%d\n",data);
}

int main(){
int counter = 5;
print(counter);
return 0;
}
Recursion Example
#include<stdio.h>
void print(int counter){
int data;
if(counter == 0)
return;
scanf("%d",&data);
printf("%d\n",data);
print(counter-1);
}

int main(){
int counter = 5;
print(counter);
return 0;
}
Recursion Example : nSUM
#include<stdio.h>
int nSUM(int n){
/* Write your code here */
}

int main(){
int x;
printf("Enter value of x: ");
scanf("%d",&x);
printf("Sum of numbers from 1 to %d: %d\n",x, nSUM(x));
return 0;
}
Recursion Example : nSUM
#include<stdio.h>
int nSUM(int n){
if( n == 0)
return 0;
return n + nSUM(n-1);
}

int main(){
int x;
printf("Enter value of x: ");
scanf("%d",&x);
printf("Sum of numbers from 1 to %d: %d\n",x, nSUM(x));
return 0;
}
Recursion Example : nSUM
#include<stdio.h>
int nSUMt(int n, int sum){
if( n == 0)
return sum;
return nSUMt(n-1, n+sum);
}

int main(){
int x;
printf("Enter value of x: ");
scanf("%d",&x);
printf("Sum of numbers from 1 to %d: %d\n",x, nSUMt(x,0));
return 0;
}
Recursion Example : nSUM
#include<stdio.h>
int nSUM(int n){
int sum;
if( n == 0)
return 0;
sum = n + nSUM(n-1);
return sum;
}

int main(){
int x;
printf("Enter value of x: ");
scanf("%d",&x);
printf("Sum of numbers from 1 to %d: %d\n",x, nSUM(x));
return 0;
}
Recursion Example : Fibonacci

Fibonacci(1) = 1 /* stopping criteria */


Fibonacci(2) = 1 /* stopping criteria */

Fibonacci(n) = Fibonacci(n-1) + Fibonacci(n-2), if n > 2


/* recursive form */
Recursion Example : Fibonacci
#include<stdio.h>
int computeFibonacci(int n){
if( n == 1 || n == 2){
return 1;
}
return computeFibonacci(n-1)+computeFibonacci(n-2);
}

int main(){
int x = 5;
int i;
for(i = 1; i <=x; i++){
printf("%d ",computeFibonacci(i));
}
printf("\n");
return 0;
}
Pointers
Pointers

int i: i is a variable that stores data of type integer

Similarly float f, double d, and char c


Pointers

int i: i is a variable that stores data of type integer

Similarly float f, double d, and char c

Pointer variable is a variable whose value is an address

< data type > * variable-name


Pointer example
#include<stdio.h>
int main(){
int x = 5;
int *ptr_x; //ptr_x: pointer to hold the address of an integer variable
ptr_x = &x; // assigning the address of x to pointer ptr_x

printf("content: %d\n",x);
printf("content: %d\n",*ptr_x); // dereferencing a pointer

printf("address: %p\n",&x);
printf("address: %p\n",ptr_x);

return 0;
}
Pointer example
#include<stdio.h>
int main(){
int x = 5;
int *ptr_x; //ptr_x: pointer to hold the address of an integer variable
ptr_x = &x; // assigning the address of x to pointer ptr_x

printf("content: %d\n",x);
printf("content: %d\n",*ptr_x); // dereferencing a pointer

printf("address: %p\n",&x);
printf("address: %p\n",ptr_x);

return 0;
}

content: 5
content: 5
address: 0x16cfb73a8
address: 0x16cfb73a8
Pointer example
#include<stdio.h>
int main(){
int x = 5;
int *ptr_x; //ptr_x: pointer to hold the address of an integer variable
ptr_x = &x; // assigning the address of x to pointer ptr_x

printf("content: %d\n",x);
printf("content: %d\n",*ptr_x); // dereferencing a pointer

printf("address: %p\n",&x);
printf("address: %p\n",ptr_x);

printf("address of pointer: %p\n",&ptr_x);

return 0;
}
content: 5
content: 5
address: 0x16cfb73a8
address: 0x16cfb73a8
address of pointer: 0x16cfb73a0
Pointer example
#include<stdio.h>
int main(){
int num;
int* ptr_num;
num = 2024;
printf("content of num: %d\n",num);
ptr_num = &num;
printf("content of location pointed by ptr_num: %d\n",*ptr_num);
*ptr_num = 24;
printf("content of num: %d\n",num);
return 0;
}
Pointer example
#include<stdio.h>
int main(){
int num;
int* ptr_num;
num = 2024;
printf("content of num: %d\n",num);
ptr_num = &num;
printf("content of location pointed by ptr_num: %d\n",*ptr_num);
*ptr_num = 24;
printf("content of num: %d\n",num);
return 0;
}

content of num: 2024


content of location pointed by ptr_num: 2024
content of num: 24
Pointer example
#include<stdio.h>
int main(){
int num;
int* ptr_num;
num = 2024;
printf("content of num: %d\n",num);
printf("address of num: %p\n",&num);
ptr_num = &num;
printf("content of location pointed by ptr_num: %d\n",*ptr_num);
printf("content of ptr_num: %p\n",ptr_num);
*ptr_num = 24;
printf("content of num: %d\n",num);
printf("content of location pointed by ptr_num: %d\n",*ptr_num);

return 0;
}
content of num: 2024
address of num: 0x16b6373a8
content of location pointed by ptr_num: 2024
content of ptr_num: 0x16b6373a8
content of num: 24
content of location pointed by ptr_num: 24
Pointer application
#include<stdio.h>

void swap(int x, int y){


int buffer;
buffer = x;
x = y;
y = buffer;
}

int main(){
int a = 11, b = 13;
printf("Before swap: a = %d, b = %d\n",a,b);
swap(a,b);
printf("After swap: a = %d, b = %d\n",a,b);

return 0;
}
Pointer application
#include<stdio.h>

void swap(int x, int y){


int buffer;
buffer = x;
x = y;
y = buffer;
}

int main(){
int a = 11, b = 13;
printf("Before swap: a = %d, b = %d\n",a,b);
swap(a,b);
printf("After swap: a = %d, b = %d\n",a,b);

return 0;
}
Before swap: a = 11, b = 13
After swap: a = 11, b = 13
Pointer application
#include<stdio.h>

void swap(int x, int y){


int buffer;
buffer = x;
x = y;
y = buffer; Call-by-value
}

int main(){
int a = 11, b = 13;
printf("Before swap: a = %d, b = %d\n",a,b);
swap(a,b);
printf("After swap: a = %d, b = %d\n",a,b);

return 0;
}
Before swap: a = 11, b = 13
After swap: a = 11, b = 13
Pointer application
#include<stdio.h>

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


int buffer;
buffer = *x;
*x = *y;
*y = buffer;
}

int main(){
int a = 11, b = 13;
printf("Before swap: a = %d, b = %d\n",a,b);
swap(&a, &b);
printf("After swap: a = %d, b = %d\n",a,b);

return 0;
}
Pointer application
#include<stdio.h>

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


int buffer;
buffer = *x;
*x = *y;
*y = buffer; Call-by-reference
}

int main(){
int a = 11, b = 13;
printf("Before swap: a = %d, b = %d\n",a,b);
swap(&a, &b);
printf("After swap: a = %d, b = %d\n",a,b);

return 0;
}
Before swap: a = 11, b = 13
After swap: a = 13, b = 11
Pointer application
#include<stdio.h>
void swap(int *x, int *y){
int* buffer;
buffer = x;
x = y;
y = buffer; Is it swapping a and b?
}

int main(){
int a = 11, b = 13;
printf("Before swap: a = %d, b = %d\n",a,b);
swap(&a, &b);
printf("After swap: a = %d, b = %d\n",a,b);
return 0;
}
Pointer application
#include<stdio.h>
void swap(int *x, int *y){
int* buffer;
buffer = x;
x = y;
y = buffer; Is it swapping a and b?
}

int main(){
int a = 11, b = 13;
printf("Before swap: a = %d, b = %d\n",a,b);
swap(&a, &b);
printf("After swap: a = %d, b = %d\n",a,b);
return 0;
} Before swap: a = 11, b = 13
After swap: a = 11, b = 13
Pointer application
#include<stdio.h>
void swap(int *x, int *y){
int* buffer;
printf("address stored in x: %p\n",x);
printf("address stored in y: %p\n",y);
buffer = x;
x = y;
y = buffer;
printf("address stored in x: %p\n",x);
printf("address stored in y: %p\n",y);
}

int main(){
int a = 11, b = 13;
printf("Before swap: a = %d, b = %d\n",a,b);
swap(&a, &b);
printf("After swap: a = %d, b = %d\n",a,b); Before swap: a = 11, b = 13
return 0; address stored in x: 0x16bc8f398
} address stored in y: 0x16bc8f394
address stored in x: 0x16bc8f394
address stored in y: 0x16bc8f398
After swap: a = 11, b = 13
Pointer example
#include<stdio.h>

void intArithmetic(int x, int y, int* sum, int* diff, int* prod, int* div){
*sum = x+y;
*diff = x-y;
*prod = x*y;
*div = x/y;
}

int main(){

int num1, num2, sum, diff, prod, div;


num1 = 10;
num2 = 11;
intArithmetic(num1,num2,&sum,&diff,&prod,&div);
printf("sum: %d\n",sum);
printf("difference: %d\n",diff);
printf("product: %d\n",prod);
printf("divide: %d\n",div);

return 0;
}
Pointer example
#include<stdio.h>
int main(){
int numList[] = {3,17,29,37,41};

printf("Starting address of array: %p\n",numList);


printf("Starting address of array: %p\n”,&numList[0]);

return 0;
}
Pointer example
#include<stdio.h>
int main(){
int numList[] = {3,17,29,37,41};

printf("Starting address of array: %p\n",numList);


printf("Starting address of array: %p\n”,&numList[0]);

return 0;
}

Starting address of array: 0x16f517390


Starting address of array: 0x16f517390
Pointer example
#include<stdio.h>
int main(){
int numList[] = {3,17,29,37,41};
printf("%d\n",numList[1]);
printf("%d\n",*(numList+1));

return 0;
}

17
17
Pointer example
#include<stdio.h>
void printArray(int numList[], int N){
int i;
for(i = 0; i < N; i++){
printf("%d ",*(numList+i));
}
printf("\n");
}

int main(){
int numList[] = {3,17,29,37,41};
int size = sizeof(numList)/sizeof(int);
printArray(numList,size);

return 0;
}
Pointer example
#include<stdio.h>
void printArray(int numList[], int N){
int i;
for(i = 0; i < N; i++){
printf("%d ",*(numList+i));
}
printf("\n");
}

int main(){
int numList[] = {3,17,29,37,41};
int size = sizeof(numList)/sizeof(int);
printArray(numList,size);

return 0;
}
3 17 29 37 41
Pointer example
#include<stdio.h>
void printArrayAddress(int numList[], int N){
int i;
for(i = 0; i < N; i++){
printf("%p\n",(numList+i));
}
}

int main(){
int numList[] = {3,17,29,37,41};
int size = sizeof(numList)/sizeof(int);
printArrayAddress(numList,size);

return 0;
}
Pointer example
#include<stdio.h>
void printArrayAddress(int numList[], int N){
int i;
for(i = 0; i < N; i++){
printf("%p\n",(numList+i));
}
}

int main(){
int numList[] = {3,17,29,37,41};
int size = sizeof(numList)/sizeof(int);
printArrayAddress(numList,size);

return 0;
} 0x16f99f390
0x16f99f394
0x16f99f398
0x16f99f39c
0x16f99f3a0
Pointer example
#include<stdio.h>

void probeArray(int numList[], int index, int bias){


numList[index] = *(numList+index) + bias;
}

void printArray(int numList[], int N){


int i;
for(i = 0; i < N; i++){
printf("%d ",numList[i]);
}
printf("\n");
}

int main(){
int numList[] = {3,17,29,37,41};
int size = sizeof(numList)/sizeof(int);
int i;
for(i = 0; i < size; i++){
probeArray(numList,i,2*i+1);
}
printArray(numList,size);

return 0;
}
Pointer example
#include<stdio.h>

void probeArray(int numList[], int index, int bias){


numList[index] = *(numList+index) + bias;
}

void printArray(int numList[], int N){


int i;
for(i = 0; i < N; i++){
printf("%d ",numList[i]);
}
printf("\n");
}

int main(){
int numList[] = {3,17,29,37,41};
int size = sizeof(numList)/sizeof(int);
int i;
for(i = 0; i < size; i++){
probeArray(numList,i,2*i+1);
}
printArray(numList,size); 4 20 34 44 50
return 0;
}
Pointer example with Constants
#include<stdio.h>
int main(){
int number = 10, pivot = 20;
const int* ptr_n;
ptr_n = &number;
printf("Content in the address: %d\n",*ptr_n);
printf("Address: %p\n",ptr_n);
ptr_n = &pivot;
printf("Content in the address: %d\n",*ptr_n);
printf("Address: %p\n”,ptr_n);

return 0;
}
Pointer example with Constants
#include<stdio.h>
int main(){
int number = 10, pivot = 20;
const int* ptr_n;
ptr_n = &number;
printf("Content in the address: %d\n",*ptr_n);
printf("Address: %p\n",ptr_n);
ptr_n = &pivot;
printf("Content in the address: %d\n",*ptr_n);
printf("Address: %p\n”,ptr_n);

return 0;
} Content in the address: 10
Address: 0x16dcf73a8
Content in the address: 20
Address: 0x16dcf73a4
Pointer example with Constants
#include<stdio.h>
int main(){
int number = 10, pivot = 20;
const int* ptr_n;
ptr_n = &number;
printf("Content in the address: %d\n",*ptr_n);
printf("Address: %p\n",ptr_n);
*ptr_n = pivot;
printf("Content in the address: %d\n",*ptr_n);
printf("Address: %p\n”,ptr_n);

return 0;
}
Pointer example with Constants
#include<stdio.h>
int main(){
int number = 10, pivot = 20;
const int* ptr_n;
ptr_n = &number;
printf("Content in the address: %d\n",*ptr_n);
printf("Address: %p\n",ptr_n);
*ptr_n = pivot;
printf("Content in the address: %d\n",*ptr_n);
printf("Address: %p\n”,ptr_n);

return 0;
}

constPointer-ex1.c:8:12: error: read-only variable is not assignable


*ptr_n = pivot;
~~~~~~ ^
1 error generated.
Pointer example with Constants
#include<stdio.h>
int main(){
int number = 10, pivot = 20;
int* const ptr_n = &number;
printf("Content in the address: %d\n",*ptr_n);
printf("Address: %p\n",ptr_n);
*ptr_n = pivot;
printf("Content in the address: %d\n",*ptr_n);
printf("Address: %p\n",ptr_n);

return 0;
}
Pointer example with Constants
#include<stdio.h>
int main(){
int number = 10, pivot = 20;
int* const ptr_n = &number;
printf("Content in the address: %d\n",*ptr_n);
printf("Address: %p\n",ptr_n);
*ptr_n = pivot;
printf("Content in the address: %d\n",*ptr_n);
printf("Address: %p\n",ptr_n);

return 0;
}
Content in the address: 10
Address: 0x16b8d33a8
Content in the address: 20
Address: 0x16b8d33a8
Pointer example with Constants
#include<stdio.h>
int main(){
int number = 10, pivot = 20;
int* const ptr_n = &number;
printf("Content in the address: %d\n",*ptr_n);
printf("Address: %p\n",ptr_n);
ptr_n = &pivot;
printf("Content in the address: %d\n",*ptr_n);
printf("Address: %p\n",ptr_n);

return 0;
}
Pointer example with Constants
#include<stdio.h>
int main(){
int number = 10, pivot = 20;
int* const ptr_n = &number;
printf("Content in the address: %d\n",*ptr_n);
printf("Address: %p\n",ptr_n);
ptr_n = &pivot;
printf("Content in the address: %d\n",*ptr_n);
printf("Address: %p\n",ptr_n);

return 0;
}

constPointer-ex2.c:7:11: error: cannot assign to variable 'ptr_n' with


const-qualified type 'int *const'
ptr_n = &pivot;
Strings
Strings

String is a character array where the last character is


‘\0’ (Null character)
Strings

String is a character array where the last character is


‘\0’ (Null character)

char str1[] = "PDS theory";

char str2[11] = "PDS theory”;

char str3[] = {'P','D','S',' ','t','h','e','o','r','y','\0'};

char str4[11] = {'P','D','S',' ','t','h','e','o','r','y','\0'};


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

char str1[] = "PDS theory";


char str2[11] = "PDS theory";
char str3[] = {'P','D','S',' ','t','h','e','o','r','y','\0'};
char str4[11] = {'P','D','S',' ','t','h','e','o','r','y','\0'};

int i = 0;
while(str1[i] != '\0'){
printf("%c",str1[i]);
i++;
}
printf("\n");

return 0;
}
String example
#include<stdio.h>
int main(){

char str1[] = "PDS theory";


char str2[11] = "PDS theory";
char str3[] = {'P','D','S',' ','t','h','e','o','r','y','\0'};
char str4[11] = {'P','D','S',' ','t','h','e','o','r','y','\0'};

printf("%s\n",str1);
printf("%s\n",str2);
printf("%s\n",str3);
printf("%s\n",str4);

return 0;
}
String example
#include<stdio.h>
int main(){

char str1[] = "PDS theory";


char str2[11] = "PDS theory";
char str3[] = {'P','D','S',' ','t','h','e','o','r','y','\0'};
char str4[11] = {'P','D','S',' ','t','h','e','o','r','y','\0'};

puts(str1);
puts(str2);
puts(str3);
puts(str4);

return 0;
}
String example: input
#include<stdio.h>
int main(){

char str[20];
printf("Enter your string: ");
scanf("%s",str); // input: PDS theory
puts(str);

return 0;
}

What is the output ?


String example: input
#include<stdio.h>
int main(){

char str[20];
printf("Enter your string: ");
scanf("%s",str); // input: PDS theory
puts(str);

return 0;
}

PDS
String example: input
#include<stdio.h>
int main(){

const int size = 20;


char str[size];
printf("Enter your string: "); // input: PDS theory
int i = 0;
while(i < size-1){
scanf("%c",&str[i]);
if(str[i] == '\n'){
break;
}
i++;
}
str[i] = '\0';
puts(str);

return 0;
}
String example: input
#include<stdio.h>
int main(){

const int size = 20;


char str[size];
printf("Enter your string: "); // input: PDS theory
int i = 0;
while(i < size-1){
scanf("%c",&str[i]);
if(str[i] == '\n'){
break;
}
i++;
}
str[i] = '\0';
puts(str);
PDS theory
return 0;
}
String example: input
#include<stdio.h>
int main(){

const int size = 20;


char str[size];
printf("Enter your string: ");
gets(str);
puts(str);

return 0;
}
String example: input
#include<stdio.h>
int main(){

const int size = 20;


char str[size];
printf("Enter your string: ");
gets(str);
puts(str);

return 0;
}

warning: this program uses gets(),


which is unsafe.
String example: input
#include<stdio.h>
int main(){

const int size = 20;


char str[size];
printf("Enter your string: ");
gets(str);
puts(str);

return 0;
}

warning: this program uses gets(),


which is unsafe.

it is highly recommended that you use


fgets(3) instead
String example: input
#include<stdio.h>
int main(){

const int size = 20;


char str[size];
printf("Enter your string: ");
fgets(str, size, stdin);
puts(str);

return 0;
}
String example: length
#include<stdio.h>
/* finding length of a sentence */
int main(){
const int SIZE = 20;
char sentence[SIZE];
int i = 0;
int len_sentence = 0;

printf("Enter a sentence: \n");


fgets(sentence,SIZE,stdin);

/*
Write your code here
*/

printf("Length of the sentence: %d\n",len_sentence);

return 0;
}
String example: length
#include<stdio.h>
/* finding length of a sentence */
int main(){
const int SIZE = 20;
char sentence[SIZE];
int i = 0;
int len_sentence = 0;

printf("Enter a sentence: \n");


fgets(sentence,SIZE,stdin);

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


len_sentence++;
}
printf("Length of the sentence: %d\n",len_sentence);

return 0;
}
String example: length: string.h
#include<stdio.h>
#include<string.h>
/* finding length of a sentence */
int main(){
const int SIZE = 20;
char sentence[SIZE];

printf("Enter a sentence: \n");


fgets(sentence,SIZE,stdin);

printf("Length of the sentence: %lu\n",strlen(sentence));

return 0;
}
String example: comparing two strings
#include<stdio.h>
#include<string.h>
/* comparing two sentences */
int main(){
const int SIZE = 40;
char sentence1[SIZE];
char sentence2[SIZE];
int sameFlag = 1;

printf("Enter first sentence: \n");


fgets(sentence1, SIZE, stdin);
printf("Enter second sentence: \n");
fgets(sentence2, SIZE, stdin);

if(strlen(sentence1) != strlen(sentence2)){
sameFlag = 0;
}
else{
/* Write your code here */
}

if(sameFlag){
printf("The two sentences are same\n");
}
else{
printf("The two sentences are different\n");
}

return 0;
}
String example: comparing two strings
#include<stdio.h>
#include<string.h>
/* comparing two sentences */
int main(){
const int SIZE = 40;
char sentence1[SIZE];
char sentence2[SIZE];
int sameFlag = 1;
int i;

printf("Enter first sentence: \n");


fgets(sentence1, SIZE, stdin);
printf("Enter second sentence: \n");
fgets(sentence2, SIZE, stdin);

if(strlen(sentence1) != strlen(sentence2)){
sameFlag = 0;
}
else{
for( i = 0; i < strlen(sentence1); i++){
if(sentence1[i] != sentence2[i]){
sameFlag = 0;
break;
}
}
}

if(sameFlag){
printf("The two sentences are same\n");
}
else{
printf("The two sentences are different\n");
}

return 0;
}
String example: comparing two strings
#include<stdio.h>
#include<string.h>
/* comparing two sentences */
int main(){
const int SIZE = 40;
char sentence1[SIZE];
char sentence2[SIZE];

printf("Enter first sentence: \n");


fgets(sentence1, SIZE, stdin);
printf("Enter second sentence: \n");
fgets(sentence2, SIZE, stdin);
if(!strcmp(sentence1, sentence2)){
printf("The two sentences are same\n");
}
else{
printf("The two sentences are different\n");
}

return 0;
}
String example: strcmp example
#include<stdio.h>
#include<string.h>
/* strcmp function*/
int main(){
char sentence1[] = "PDS";
char sentence2[] = "PDS theory";

printf("%d\n",strcmp(sentence1,sentence1));
printf("%d\n",strcmp(sentence1,sentence2));
printf("%d\n",strcmp(sentence2,sentence1));

return 0;
}
String example: strcmp example
#include<stdio.h>
#include<string.h>
/* strcmp function*/
int main(){
char sentence1[] = "PDS";
char sentence2[] = "PDS theory";

printf("%d\n",strcmp(sentence1,sentence1));
printf("%d\n",strcmp(sentence1,sentence2));
printf("%d\n",strcmp(sentence2,sentence1));

return 0;
}

0
-32
32
String example: strcpy example
#include<stdio.h>
#include<string.h>

int main(){
const int size = 20;
char sentence1[size] = "PDS";
char sentence2[size] = "PDS theory";

strcpy(sentence1, sentence2);
puts(sentence1);
return 0;
}
String example: strcpy example
#include<stdio.h>
#include<string.h>

int main(){
const int size = 20;
char sentence1[size] = "PDS";
char sentence2[size] = "PDS theory";

strcpy(sentence1, sentence2);
puts(sentence1);
return 0;
}

PDS theory
String example

Write a program to copy a source string to destination string


without using strcpy function
String example: strcat example
#include<stdio.h>
#include<string.h>

int main(){
const int SIZE = 40;
char sentence[SIZE] = "Programming";
strcat(sentence," in");
strcat(sentence," C");
puts(sentence);

return 0;
}
String example: strcat example
#include<stdio.h>
#include<string.h>

int main(){
const int SIZE = 40;
char sentence[SIZE] = "Programming";
strcat(sentence," in");
strcat(sentence," C");
puts(sentence);

return 0;
}

Programming in C
String example

Write a program to concatenate two strings


without using strcat function
Structure
Structure

Structure is used to represent a group of logically related data items

If data items are of same type, then we can use Arrays

Structure is used to represent a group of items of different types


Structure

Structure is used to represent a group of logically related data items

If data items are of same type, then we can use Arrays

Structure is used to represent a group of items of different types

Example:

Student Record: Name, Roll No, Address, Contact No., Program


Complex Number: real part, imaginary part
Structure

Structure is used to represent a group of logically related data items

If data items are of same type, then we can use Arrays

Structure is used to represent a group of items of different types

Example:

Student Record: Name, Roll No, Address, Contact No., Program


Complex Number: real part, imaginary part

The individual structure elements are called members

Structure is a user-defined data type


Structure example
struct < name of structure >{
<data type> <member 1>;
<data type> <member 2>;
. . .
};

struct complex{
int real;
int imaginary;
};
Structure example
#include<stdio.h>

struct complex{
int real;
int imag;
};

int main(){
struct complex A;

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


scanf("%d",&A.real);
scanf("%d",&A.imag);
printf("%d + i %d\n",A.real,A.imag);

return 0;
}
Structure example
#include<stdio.h>
struct is the C keyword
struct complex{
int real; Note the ; at the end of
int imag; structure definition
};
Members can be of any
int main(){ data type
struct complex A;
struct complex
printf("Enter a complex number\n"); is a new data type
scanf("%d",&A.real);
scanf("%d",&A.imag);
printf("%d + i %d\n",A.real,A.imag);

return 0;
}
Structure example

Structure Definition:

struct complex{ No memory is allocated


int real;
int imag; A new data type is defined
};

Structure variable Declaration: A is a variable of type


struct complex
struct complex A;
Memory is allocated for A
Structure example
#include<stdio.h>

struct complex{
int real;
int imag;
};

void printComplex(struct complex B){


printf("%d + i %d\n",B.real,B.imag);
}

int main(){

struct complex A;

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


scanf("%d",&A.real);
scanf("%d",&A.imag);
printComplex(A);

return 0;
}
Structure example
#include<stdio.h>

struct complex{
int real;
int imag;
};

void printComplex(struct complex B){


printf("%d + i %d\n",B.real,B.imag);
}

void getComplex(struct complex* B){


scanf("%d",&(*B).real);
scanf("%d",&(*B).imag);
}

int main(){

struct complex A;
printf("Enter a complex number\n");
getComplex(&A);
printComplex(A);

return 0;
}
Structure example
#include<stdio.h>

struct complex{
int real;
int imag;
};

void printComplex(struct complex B){


printf("%d + i %d\n",B.real,B.imag);
}

void getComplex(struct complex* B){


scanf("%d",&B->real);
scanf("%d",&B->imag);
}

int main(){

struct complex A;
printf("Enter a complex number\n");
getComplex(&A);
printComplex(A);

return 0;
}
Structure example : complex addition
#include<stdio.h>

struct complex{
int real;
int imag;
};

void printComplex(struct complex B){


printf("%d + i %d\n",B.real,B.imag);
}

void getComplex(struct complex* B){


scanf("%d",&B->real);
scanf("%d",&B->imag);
}

void addComplex(struct complex A, struct complex B, struct complex* C){


// Write your code here
}

int main(){

struct complex A, B, C;
printf("Enter complex number 1\n");
getComplex(&A);
printf("Enter complex number 2\n");
getComplex(&B);

addComplex(A,B,&C);
printComplex(C);

return 0;
}
Structure example : complex addition
#include<stdio.h>

struct complex{
int real;
int imag;
};

void printComplex(struct complex B){


printf("%d + i %d\n",B.real,B.imag);
}

void getComplex(struct complex* B){


scanf("%d",&B->real);
scanf("%d",&B->imag);
}

void addComplex(struct complex A, struct complex B, struct complex* C){


C->real = A.real + B.real;
C->imag = A.imag + B.imag;
}

int main(){

struct complex A, B, C;
printf("Enter complex number 1\n");
getComplex(&A);
printf("Enter complex number 2\n");
getComplex(&B);

addComplex(A,B,&C);
printComplex(C);

return 0;
}
Structure example : complex multiplication
#include<stdio.h>
struct complex{
int real;
int imag;
};
void printComplex(struct complex B){
printf("%d + i %d\n",B.real,B.imag);
}
void getComplex(struct complex* B){
scanf("%d",&B->real);
scanf("%d",&B->imag);
}
void productComplex(struct complex A, struct complex B, struct complex* C){
// Write your code here
}

int main(){

struct complex A, B, C;
printf("Enter complex number 1\n");
getComplex(&A);
printf("Enter complex number 2\n");
getComplex(&B);

productComplex(A,B,&C);
printComplex(C);

return 0;
}
Structure example : complex multiplication
#include<stdio.h>
struct complex{
int real;
int imag;
};
void printComplex(struct complex B){
printf("%d + i %d\n",B.real,B.imag);
}
void getComplex(struct complex* B){
scanf("%d",&B->real);
scanf("%d",&B->imag);
}
void productComplex(struct complex A, struct complex B, struct complex* C){
C->real = A.real * B.real - A.imag * B.imag;
C->imag = A.real * B.imag + A.imag * B.real;
}

int main(){

struct complex A, B, C;
printf("Enter complex number 1\n");
getComplex(&A);
printf("Enter complex number 2\n");
getComplex(&B);

productComplex(A,B,&C);
printComplex(C);

return 0;
}
Structure example : array of structure
#include<stdio.h>
struct complex{
int real;
int imag;
};

void printComplex(struct complex B){


printf("%d + i %d\n",B.real,B.imag);
}

void getComplex(struct complex* B){


scanf("%d",&B->real);
scanf("%d",&B->imag);
}

int main(){

struct complex A[5];


int i;
for(i = 0; i < 5; i++){
getComplex(&A[i]);
}
for(i = 0; i < 5; i++){
printComplex(A[i]);
}
return 0;
}
Structure example

Write a program to maintain the following records for 10 students:


Name, Roll Number, DOB, Program, CGPA.
- Write a function to enter each record
- Write a function to display each record
Dynamic Memory Allocation
Why Dynamic memory

For some problems, amount of data cannot be predicted in advance

Number of data items keep changing during runtime

Example:
Search for a key in a list of N elements

Our approach so far: assume a maximum possible value of N

Better approach: dynamic memory allocation


Dynamic memory allocation

Know how much memory is needed at runtime

Dynamically allocate only the amount of memory needed

C provides function to dynamically allocate memory:

malloc, calloc, realloc, free


Dynamic memory allocation

malloc : allocates requested number of bytes and returns a pointer to


the first byte of the allocated space.

calloc : allocates space for an array of elements, initializes them to


zero, and returns a pointer to the first byte of the memory

free : releases previously allocated memory space

Realloc : modifies the size of previously allocated space


malloc and free example
#include<stdio.h>
#include<stdlib.h>
int main(){

int* ptr;
int n,i;

printf("Enter number of elements: ");


scanf("%d",&n);

ptr = (int*) malloc(n * sizeof(int));


if(ptr == NULL){
printf("Error: memory not allocated\n");
}
else{
for(i = 0; i < n; i++){
scanf("%d",&ptr[i]);
}
for( i = 0; i < n; i++){
printf("%d ",ptr[i]);
}
printf("\n");
}
free(ptr);

return 0;
}
calloc and free example
#include<stdio.h>
#include<stdlib.h>
int main(){

int* ptr;
int n,i;

printf("Enter number of elements: ");


scanf("%d",&n);

ptr = (int*)calloc(n, sizeof(int));


if(ptr == NULL){
printf("Error: memory not allocated\n");
}
else{
for(i = 0; i < n; i++){
scanf("%d",&ptr[i]);
}
for( i = 0; i < n; i++){
printf("%d ",ptr[i]);
}
printf("\n");
}
free(ptr);

return 0;
}
realloc example
#include<stdio.h>
#include<stdlib.h>
int main(){

int* ptr;
int n = 5, i;
ptr = (int*)malloc( n * sizeof(int));

if(ptr == NULL){
printf("Error: memory not allocated\n");
}
else{
n = 10;
ptr = (int*)realloc( ptr, n * sizeof(int));

free(ptr);

return 0;
}
Dynamic memory example

Write a program that asks user to enter length for a name and
then to enter the name and print it
Dynamic memory example
#include<stdio.h>
#include<stdlib.h>
int main(){

int length;
printf("Enter maximum alphabets allowed in name: ");
scanf("%d",&length);

char *name = (char*) malloc(length * sizeof(char));

fgets(name,length*sizeof(char),stdin);
puts(name);

return 0;
}
Dynamic memory example

Write a program that asks user to enter number of products. Then for
each product it asks the user to enter product code and price.
Dynamic memory example
#include<stdio.h>
#include<stdlib.h>

struct product{
int product_code;
float product_price;
};

void printList(struct product* list, int n){


int i;
for(i = 0; i < n; i++){
printf("Product code: %d & Price: %f\n",list[i].product_code, list[i].product_price);
}
}

int main(){

int count, i;
printf("Enter number of products: ");
scanf("%d",&count);

struct product* productList = (struct product*) calloc(count, sizeof(struct product));


if(productList == NULL){
printf("Error: memory allocation failed\n");
}
else{
for( i = 0; i < count; i++){
printf("Enter product code for item %d: ",i+1);
scanf("%d",&(productList[i].product_code));
printf("Enter price for item %d: ",i+1);
scanf("%f",&(productList[i].product_price));
}
printList(productList, count);
}

return 0;
}
Dynamic memory and Linked List
#include<stdio.h>
#include<stdlib.h>

struct product{
int product_code;
float product_price;
struct product* next;
};

void printList(struct product* head){


while(head != NULL){
printf("Product code: %d & Price: %f\n",head->product_code, head->product_price);
head = head->next;
}
}

int main(){

int count, i;
printf("Enter number of products: ");
scanf("%d",&count);

struct product* first;


struct product* prev;

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


struct product* temp = (struct product*) malloc(sizeof(struct product));
if(temp == NULL){
printf("Error: memory allocation failed\n");
}
else{
printf("Enter product code for item %d: ",i+1);
scanf("%d",&(temp->product_code));
printf("Enter price for item %d: ",i+1);
scanf("%f",&(temp->product_price));
temp->next = NULL;
if( i == 0){
prev = temp;
first = temp;
}
else{
prev->next = temp;
prev = temp;
}
}

}
printList(first);

return 0;
}

You might also like