Unit 4 C Notes by Prof. Shahid Masood
Unit 4 C Notes by Prof. Shahid Masood
CABSMJ-1001
Problem Solving Using C
Unit - IV
CABSMJ-1001 [2024-25]
Recursion
Recursive function CABSMJ-1001
int rf(int n) [2024-25]
(finds sum of first n { int res;
Recursion natural numbers) if ( n==1 ) Base
condition
return 1;
It is a technique of defining a process res = n + rf(n-1);
in terms of itself. return res;
}
It is implemented by means of recursive function that:
calls itself repeatedly till base condition (called Direct recursion)
is satisfied or
calls another fn which calls the first fn. (called Indirect recursion)
Example
Computing the value of n! (n is a non-negative integer)
Iterative function:
Advantages of Recursion
Disadvantages of Recursion
Execution time is more due to:
maintenance of stack
multiple function calls & return overhead
Prob:
Recursive 0 if n=0
definition: sum(n) =
n%10 + sum(n/10) if n>0
Prob
Write a C program that reads the term number (n) and returns
the nth term of the Fibonacci series using a recursive function.
Assume that the Fibonacci series terms are numbered as below:
T1 T2 T3 T4 T5 T6 T7 T8 . . . . .
0, 1, 1, 2, 3, 5, 8, 13 . . . . .
Prob:
Write a C program that reads the no. of terms n (a positive
integer) and finds the sum of first n terms of the following
series using a recursive function.
1 + 4 + 9 + 16 + 25 + . . . . . upto n terms.
1 if n=1
sum(n) =
n*n + sum(n-1) if n>1
1 + 4 + 9 + 16 + 25 + . . CABSMJ-1001 [2024-25]
. upto n terms
sum(1) return 1
CABSMJ-1001 [2024-25]
Prob:
Write a C program that reads two positive integers a and b and
finds their greatest common divisor (GCD) using a recursive
function.
Prob:
lb ub
10 11 12 13 14
0 1 2 3 4
a[5]
CABSMJ-1001 [2024-25]
lb ub
10 11 12 13 14
0 1 2 3 4
a[5]
Solu:
C Recursive function
int sum(int a[], int ub)
{ if ( ub==0 )
return a[ub];
else
return (a[ub]+sum(a,ub-1));
}
Fn.call: sum(a,ub) /* output: 60 */
CABSMJ-1001 [2024-25]
int sum(int a[], int ub)
{ if ( ub==0 ) lb ub
return a[ub]; 10 11 12 13 14
else 0 1 2 3 4
return (a[ub]+sum(a,ub-1)); a[5]
}
sum(a,3) return(a[3]+sum(a,2)) = 46
sum(a,2) return(a[2]+sum(a,1)) = 33
sum(a,1) return(a[1]+sum(a,0)) = 21
sum(a,0) return(a[0]) = 10
CABSMJ-1001 [2024-25]
Storage
Classes
in C
CABSMJ-1001 [2024-25]
Storage Classes
In C programming, every variable has two properties:
1. Data type and
2. Storage class
i.e. every C variable not only has a data type but it also has
a storage class.
Storage Classes
Till now, we have been declaring variables in our C programs
by specifying their data type only, e.g.
int i;
float j;
char c;
If we don’t specify the storage class while declaring a
variable:
some default storage class is auto assumed by the compiler
depending upon the location of the variable declaration
in the program.
In C, general form of variable’s declaration statement is:
StorageClass DataType VarName; e.g. static int i;
CABSMJ-1001 [2024-25]
A block is a group of
Features of Storage Classes statements enclosed
within { and }.
Storage Memory
Default initial value Garbage
Scope (Accessibility) Accessible in the block in which the
variable is declared
Also known as internal variables
Life Till the control remains in the block in
which it is declared
CABSMJ-1001 [2024-25]
void main()
{ auto int a; /* auto var */
Automatic (auto) Variables { int b; /* auto var */
}
………..
}
Declared inside a block in which they are to be used.
They are created when control enters the block and auto
deleted when the block is exited (hence the name automatic).
Automatic variables can have the same variable names in
different blocks/functions. Value of such a variable in one
block is not affected by changing the value of another
variable in another block (this allows declaration and use of
same variable names in different functions/blocks in the program).
Default storage class of a variable declared inside a block is
auto (automatic).
CABSMJ-1001 [2024-25]
register Variables
local variables (variables inside a block) or formal
parameters of a function can be declared register
Accessible much faster than a memory variable (as register
access is faster than a memory access)
Program efficiency is improved.
optional
#include<stdio.h>
int a;
void add()
{ extern int a; /* writing extern int a; [optional] */
a = a+1;
printf("a=%d\n",a);
}
void sub()
{ extern int a; /* writing extern int a; [optional] */
a = a-1;
printf("a=%d\n",a); Output
} a=1
main()
a=2
{ extern int a;
a=1
add(); add();
sub(); sub();
a=0
}
CABSMJ-1001 [2024-25]
Ex.3: By default, extern (global) variable is accessible from the
point of its declaration onward.
#include<stdio.h>
/* extern int a; must be written here to */
void add()
/* access a in add() function, otherwise */
{ /* a will not be accessible in add() and */
a = a+1; /* we will get compilation error: */
printf("a=%d\n",a); /* “undefined symbol a in add()”. */
}
int a; /* a is accessible from here till end of program */
void sub()
{ a = a-1;
printf("a=%d\n",a); Output
} a=1
main() a=2
{ add(); add(); a=1
sub(); sub(); a=0
}
CABSMJ-1001 [2024-25]
static Variables
static Variables
Ex. Illustrates the Use of Local (or Internal) static variables
#include<stdio.h>
void add()
{ static int count; /* default initial value of count is 0 */
static int a = 50; /* both variables initialized only once */
printf("Fn.call no. %d\n",++count);
printf("a = %d\n",a);
Output
a = a+10;
Fn.call no.1
}
a = 50
main()
Fn.call no.2
{ add();
a = 60
add();
Fn.call no.3
add();
a = 70
}
CABSMJ-1001 [2024-25]
static Variables
Ex. Illustrates the Use of Global (or External) static variables
#include<stdio.h>
static int a = 100; /* a is static extern variable (accessible */
int addwitha(int x,int y) /* in this file only) */
{ return x+y+a;
}
main()
{ a = addwitha(10,20);
Output
printf("a = %d\n",a); a = 130
a = addwitha(10,20); a = 160
printf("a = %d\n",a);
}
CABSMJ-1001 [2024-25]
Dynamic
Memory
Allocation
CABSMJ-1001 [2024-25]
Memory Allocation
General form:
ptr = (cast-type *) malloc(byte-size);
void type pointer (to the allocated storage block with size
byte-size) returned by malloc() is type casted to cast-type.
ptr is a pointer of type cast-type.
Allocated storage block initially contains garbage value.
CABSMJ-1001 [2024-25]
p1
malloc() Library Function float type (4 bytes)
p2
int type (4 bytes)
Examples:
float *p1 = (float*) malloc(4); /* can store a float value */
int* p2 = (int*) malloc(sizeof(int)); /* can store an int value */
p2
int type (4 bytes)
Examples:
float *p1 = (float*) malloc(4); /* can store a float value */
int* p2 = (int*) malloc(sizeof(int)); /* can store an int value */
Prob:
Prob:
Write a C program that reads marks obtained in a test by n
students into a 1D dynamic array (for which storage is
allocated dynamically) and finds how many students have
secured marks >= average marks.
/* dynamicarray1.c */ CABSMJ-1001 [2024-25]
0 1 2 3 4 5 6 7 8 9
#include<stdio.h>
a
#include<stdlib.h>
main()
{ int n, *a, i, count=0; a+1 a+2
float avg, sum=0;
printf("Enter no. of students: ");
scanf("%d",&n); Output
a = (int*) malloc(n * sizeof(int)); Enter no. of students: 5
printf("Enter %d marks\n",n); Enter 5 marks
for (i=0; i<n; i++) 75
{ scanf("%d",(a+i)); /* or &a[i] */ 80
sum = sum + *(a+i); /* or a[i] */ 65
} 55
avg = sum / n; 80
printf("Average marks= %.2f\n",avg); Average marks= 71.00
for (i=0; i<n; i++) No. of students securing
if( *(a+i) >= avg ) count++; marks >= average marks= 3
free(a);
printf("No. of students securing marks >= average marks= %d",count);
}
CABSMJ-1001 [2024-25]
Prob:
Prob:
Write a C program that reads a string str and stores it in
reverse order in another string revstr for which storage is
allocated dynamically.
/* revstrdma.c */ CABSMJ-1001 [2024-25]
0 1 2 3 4 5 6 99
#include<stdio.h>
str[100] M U M B A I \0 ……..
#include<stdlib.h>
#include<string.h>
#define N 100 0 1 2 3 4 5 6
main() revstr I A B M U M \0
{ char str[N], *revstr; revstr+len
int len, i;
printf("Enter a string (max length %d characters)\n",N-1);
gets(str);
len = strlen(str);
revstr = (char *)malloc(sizeof(char)*(len+1));
if ( revstr == NULL ) /* check whether memory allocation is successful */
{ printf("Memory allocation failed. Exiting...");
exit(1); }
/* store str in revstr in reverse order */ Output
for (i = 0; i <= len-1; i++) Enter a string (max length 99 characters)
*(revstr+i) = str[len-1-i]; C Programming
*(revstr+len) = '\0'; Reversed string is
printf("Reversed string is\n"); gnimmargorP C
puts(revstr);
}
CABSMJ-1001
0 1 2 3 …..[2024-25]
n-1
**a 0
Allocating Storage for 1
: :
2D mxn Dynamic Array m-1
Array of ptrs to int of size m
To allocate a mxn int array:
first declare a pointer to pointer to an int,
then allocate 1D array of pointers to int of size m and store its
base address in the pointer to pointer:
Then allocate storage for m rows each of size n and store their
base addresses in the array of pointers:
Prob:
Output
Enter No. of rows and columns in the matrix: 3 4
Enter 3 x 4 matrix elements (row-wise)
1 2 3 4
5 6 7 8
1 2 3 4
Sum of all elements= 46
CABSMJ-1001 [2024-25]
Prob:
Write a C program that reads m names into a 2D char array
for which memory is allocated dynamically and finds the
longest/lengthiest name.
**name 0 A R I F A L I \0
1 M D R I Z W A N \0
2 S H AM I M A H M A D \0
: :
m-1 R AM K U M A R \0
Array of ptrs to char of size m
/* dynamicarray3.c */ **name 0
CABSMJ-1001 [2024-25]
A R I F A L I \0
#include<stdio.h>
1 M D R I Z W A N \0
#include<stdlib.h> S H AM I M A H M A D \0
2
#include<string.h>
:
main()
m-1 R A M K U M A R \0
{ int m, i, size, loc;
char **name, s[41]; Array of ptrs to char of size m
printf("How many names to be stored: ");
scanf("%d",&m);
name = (char**) malloc(m*sizeof(char*)); /* array of ptrs of size m */
fflush(stdin);
printf("Enter %d names\n",m);
for (i=0; i<m; i++)
{ gets(s);
size = strlen(s)+1;
name[i] = (char*) malloc(size*sizeof(char)); /* *(name+i) */
strcpy(name[i],s); /* *(name+i) */
}
Contd...
CABSMJ-1001 [2024-25]
Prob:
Write a C program that reads product data (name, qty, price)
of n products in a 1D array of structures for which the
storage is allocated dynamically.
Then the program allows searching by product-name and
displays the details of the product.
/* struct5.c */ CABSMJ-1001 [2024-25]
0 1 2 3 4 5 6
Note: 10 20 30 40 50 garbage
p
1. The new block may or may not begin at the same place as
the old one.
2. In case it is not able to find additional space in the same
region, it will create the new block in an entirely new
region and move the contents of the old block into the new
block.
3. It is necessary to test the success of reallocation operation
before proceeding further.
CABSMJ-1001 [2024-25]
0 1 2 3 4
Prob: a 1 2 3 4 5
Prob: str H Y D E R A B A D \n
Then it:
modifies the size of the storage block to store the second
string "SECUNDERABAD",
prints the contents of the modified storage block,
stores the second string in the block and prints it.
0 1 2 3 4 5 6 7 8 9 10 11 12
str S E C U N D E R A B A D \0
/* realloc2.c */ 0 1 2 3 4CABSMJ-1001
5 6 7 [2024-25]
8 9
#include<stdio.h> str
H Y D E R A B A D \n
#include<stdlib.h>
#include<string.h>
main()
{ char *s1="HYDERABAD", *s2="SECUNDERABAD" ,*str;
int size = strlen(s1)+1, newsize = strlen(s2)+1;
str = (char *) malloc(size*sizeof(char));
if ( str == NULL )
{ printf("Memory allocation failed");
exit(1); 0 1 2 3 4 5 6 7 8 9 10 11 12
} str H Y D E R A B A D \0 garbage
strcpy(str,s1);
printf("str contains: %s\n",str);
str = (char *) realloc(str,newsize*sizeof(char));
if ( str == NULL )
{ printf("Memory allocation failed");
exit(1);
} Contd...
CABSMJ-1001 [2024-25]
printf("Size of str modified.\n");
printf("str still contains: %s\n",str); /* old conents are intact */
strcpy(str,s2);
printf("str now contains: %s\n",str);
}
0 1 2 3 4 5 6 7 8 9 10 11 12
str H Y D E R A B A D \0 garbage
0 1 2 3 4 5 6 7 8 9 10 11 12
str S E C U N D E R A B A D \0
Output
str contains: HYDERABAD
Size of str modified.
str still contains: HYDERABAD
str now contains: SECUNDERABAD
CABSMJ-1001 [2024-25]
File
Handling or
File Management
in C
CABSMJ-1001 [2024-25]
Function Operation
name
fseek() To set the position to a desired point in the file.
ftell() Gives the current position in the file (in terms of
bytes from the start).
rewind() To set the position to the beginning of the file.
feof() To check whether eof (end-of-file) condition has
reached or not. It returns a non-zero (true) value
if file has reached to eof and zero otherwise.
ferror() To check whether an error has occurred on a file.
It returns a non-zero (true) value if error exists
and zero otherwise.
CABSMJ-1001 [2024-25]
Opening a File
General form to declare a FILE type pointer and opening a file:
FILE *fp;
fp = fopen("filename", "mode");
Closing a File
It would close the file associated with the FILE type pointer fp.
Note:
A file must be closed as soon as all operations on it have been
completed.
This ensures that:
all outstanding information associated with the file is
flushed out from the buffers, and
all links to the file are broken.
CABSMJ-1001 [2024-25]
General form:
fgets(str, n, fp); /* char str[n]; */
fgets() – Example:
FILE *fp;
char text[81];
fp = fopen("input.txt", "r");
fgets( text, 81, fp );
fputs() Function
General form:
fputs(str, fp);
Example:
FILE *fp;
char text[81];
printf("Enter text (80 char Max)\n");
gets(text);
fp = fopen("output.txt", "w");
fputs(text, fp); /* It doesn’t auto adds a newline to the output */
CABSMJ-1001 [2024-25]
fputc() Function
General form:
fputc(ch, fp);
Example:
FILE *fp;
char ch;
printf("Enter a character: ");
ch = getchar();
fp = fopen("output.txt", "w");
fputc(ch,fp);
CABSMJ-1001 [2024-25]
fprintf() Function
General form:
fprintf(fp,"format string", list);
Example:
FILE *fp;
char name[]="Asif Akhtar";
int age=20; float height=165.00;
fp = fopen("new.txt","w");
fprintf(fp,"%s %d %f", name, age, height);
CABSMJ-1001 [2024-25]
Prob:
Prob:
Write a C program that:
reads contents of a specified file (say, "input.txt")
displays it on the screen and
prints number of characters, number of sentences and
number of lines in the file.
/* filehandl2.c */ CABSMJ-1001 [2024-25]
Contents of input.txt file
#include<stdio.h>
#include<stdlib.h>
void main()
{ FILE *fp;
char ch, filename[31];
int nc=0, ns=0, nl=0;
printf("Enter filename: ");
gets(filename);
fp = fopen(filename,"r");
if (fp==NULL)
{ printf("File could not be opened...Exiting.");
exit(1); }
printf("Contents of file are:\n");
while( (ch=fgetc(fp)) != EOF ) /* fgetc() returns EOF when it reaches eof */
{ putchar(ch);
nc++;
if ( ch == '.' ) ns++; /* increment no. of sentences */
if ( ch == '\n') nl++; /* increment no. of lines */
} Contd...
CABSMJ-1001 [2024-25]
fclose(fp);
printf("\nNumber of characters= %d\n",nc);
printf("Number of sentences = %d\n",ns);
printf("Number of lines = %d\n",nl);
}
Output
Enter filename: input.txt
Contents of file are:
I am inputting some text.
It will be read by the program and
written into the specified file.
Number of characters= 94
Number of sentences = 2
Number of lines =3
CABSMJ-1001 [2024-25]
feof(fp)
Used to test EOF (end of file) condition for the specified file.
Returns a non-zero value, if eof has been reached; and returns
0 otherwise.
Example:
if ( feof(fp) != 0 ) /* if ( feof(fp) ) */
printf("End of data\n");
CABSMJ-1001 [2024-25]
ferror() Function
ferror(fp)
Used to test error status of the specified file.
Returns a non-zero value, if an error has been detected
during reading from or writing to the specified file; and
returns 0 otherwise.
Example:
if ( ferror(fp) != 0 ) /* if ( ferror(fp) ) */
printf("An error has occurred\n");
CABSMJ-1001 [2024-25]
Prob:
Write a C program that:
Reads some integer numbers from the keyboard until
CTRL+Z is pressed and writes them in a file named
"intdata.txt".
Then it reads them from the file "intdata.txt" and finds the
number of odd and number of even integers in the file.
CABSMJ-1001 [2024-25]
/* filehandl3.c */
#include<stdio.h>
#include<stdlib.h>
main()
{ FILE *fp;
int n;
int nodd=0, neven=0;
fp = fopen("intdata.txt","w");
printf("Enter some integer numbers (press ^Z in the end):\n");
while ( (scanf("%d",&n)) != EOF ) /* read until ^Z is encountered*/
{ fprintf(fp,"%d\n",n);
}
fclose(fp);
fp=fopen("intdata.txt","r");
if ( fp == NULL )
{ printf("File counld not be opened…Exiting");
exit(1);
} Contd...
/* or this while loop can be [2024-25]
CABSMJ-1001 written*/
while (1)
{ fscanf(fp,"%d",&n);
while( (fscanf(fp,"%d",&n)) != EOF ) if ( feof(fp)!=0 ) break;
{ if ( n%2 == 0 ) if (n%2 == 0)
neven++; neven++;
else nodd++; else nodd++;
} } /* feof() returns nonzero */
fclose(fp); /*when EOF has reached */
printf("Number of odd numbers = %d\n",nodd);
printf("Number of even numbers = %d\n",neven);
} Output
Enter some integer numbers (press ^Z in the end):
465436 54254 768 5463 86796
2341 46743 566 4653443 6877
^Z
Number of odd numbers = 5
Number of even numbers = 5
CABSMJ-1001 [2024-25]
Prob:
Suppose "intdata2.txt" contains some integer numbers. Write a
C program that:
reads some integer numbers from the keyboard until CTRL+Z
is pressed and
appends them in this file.
CABSMJ-1001 [2024-25]
If file already exists, the file is
/* filehandl3a.c */ opened with current contents
#include<stdio.h> safe.
main() If file does not exist, a new file is
{ FILE *fp; created.
int n; Operations possible: adding new
fp = fopen("intdata2.txt","a"); contents at the end of the file.
printf("Enter some integer numbers (press ^Z in the end):\n");
while ( (scanf("%d",&n)) != EOF )
{ fprintf(fp,"%d\n",n);
}
fclose(fp);
Output
}
Enter some integer numbers (press ^Z in the end):
5051 5052
5053
^Z
CABSMJ-1001 [2024-25]
fseek() Function
Used to move the file position to a desired location within the
file. Note: Position of first byte in the file is 0.
General form: No. of bytes to be From the location
moved (long int) specified by position
+ve offset means move forward, and –ve means move backwards.
Position can take one of the following 3 values:
Position Meaning
0 or SEEK_SET Beginning of file
1 or SEEK_CUR Current position
2 or SEEK_END End of file
CABSMJ-1001 [2024-25]
Note: If we attempt to move the file
position beyond the file boundaries, then
fseek() Function
an error occurs and fseek() returns -1.
If operation is successful, it returns 0. If an error occurs, it
returns nonzero value.
Examples of fseek() operations:
Statement Meaning
fseek(fp,0L,0); Go to the beginning of file - similar to rewind()
fseek(fp,0L,1); Stay at the current position (rarely used)
fseek(fp,0L,2); Go to the end of file (past the last character of the file)
fseek(fp,m,0); Move to mth byte from beginning
fseek(fp,m,1); Go forward by m bytes from current position
fseek(fp,-m,1); Go backwards by m bytes from current position
fseek(fp,-m,2); Go backwards by m bytes from the end
(positions the file to the mth character from the end)
CABSMJ-1001 [2024-25]
ftell() Function
Used to find the current file position of the file.
General form:
long n = ftell(fp);
rewind() Function
Resets the file position of the specified file to the beginning
of the file.
General form:
rewind(fp);
Prob:
Output
Enter digits 0 to 9 and press <ENTER>
0123456789
1. Print position of digits 0,3,6,9 in 0123456789
Position of 0 is 0
Position of 3 is 3
Position of 6 is 6
Position of 9 is 9
2. Read the digits in reverse order and print them
9876543210
CABSMJ-1001 [2024-25]
Prob:
Suppose a file "customers1.txt" contains some records about
customers as per the following format:
custid int (5 digits)
name 30 chars
phone no. 15 chars
Write a program to add new customers in the file.
CABSMJ-1001 [2024-25]
/* filehandl7a.c */
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
main()
{ int custid;
char name[31], phone[16], ans;
FILE *fp;
while (1)
{ printf("\nEnter customer details to be added\n");
printf("Enter custid (5 digits) or Enter 0 to exit : ");
scanf("%d",&custid);
if ( custid == 0 )
exit(0); /* normal program termination */
fflush(stdin);
printf("Enter name (Max 30 chars): ");
gets(name);
Contd...
CABSMJ-1001 [2024-25]
Prob:
Write a program to update phone number of customers by
custid in the file "customers1.txt" which contains customers
data as per the following format:
custid int (5 digits)
name 30 chars
phone no. 15 chars
.
/* filehandl7b.c */ CABSMJ-1001 [2024-25]
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
main()
{ int custid, custid2;
char name[31], phone[16], newphone[16], update, nl, found;
FILE *fp;
while (1)
{ found = 'F';
printf("\nEnter custid (5 digits) whose phone number to be updated\n");
printf("or enter 0 to exit\n");
scanf("%d",&custid2);
if ( custid2 == 0 )
exit(0); /* normal program termination */
fflush(stdin);
if ( (fp = fopen("customers1.txt","r+"))==NULL )
{ printf("File could not be opened");
exit(1); /* abnormal program termination */
}
Contd...
while( (fscanf(fp,"%5d",&custid))!=EOF ) CABSMJ-1001 [2024-25]
if ( found == 'F' )
printf("%d - not found\n",custid2);
fclose(fp);
} /* end of while (1) */
}
CABSMJ-1001 [2024-25]
Output
Enter custid (5 digits) whose phone number to be updated
or enter 0 to exit
10003
10003 Rashid Ali Khan +918743254765
Enter new phone number (Max 15 digits): +919358246255
Update phone number (y/n): y
Phone number updated...
The C
Preprocessor
CABSMJ-1001 [2024-25]
C Preprocessor
C Preprocessor
C Preprocessor Directives
C Preprocessor directives:
allow additional actions to be taken on the C source code
before it is compiled.
begin with the # symbol in column-1 (don’t require a
semicolon at the end).
Preprocessor directives are not part of the C language itself.
Commonly used preprocessor directives & their functions
Directive Function
1. Macro Substitution directives
#define Defines a macro substitution
#undef Undefines a previously defined macro
CABSMJ-1001 [2024-25]
Directive Function
2. File Inclusion directive
#include Specifies the file to be included
3. Compiler Control directives
#ifdef Tests for a macro definition
#ifndef Tests whether a macro is not defined
#if Used to test a compile-time condition
#else Specifies alternatives when #if test fails
#endif Specifies the end of #if
CABSMJ-1001 [2024-25]
1. Macro Substitution
It is a process that provides a string substitution.
It is achieved through #define preprocessor directive.
A simple example:
#define CUBE(x) ((x)*(x)*(x)) /* use parentheses as shown*/
If above macro is defined in a program then the preprocessor
would expand the following source code statements as:
C Source code After preprocessing
volume1= CUBE(side); volume1= ((side)*(side)*(side));
volume2= CUBE(a+b); volume2= ((a+b)*(a+b)*(a+b));
Known as macro calls
CABSMJ-1001 [2024-25]
Prob:
Write a C program that implements an argumented macro
BIG(x,y) which compares x with y and returns bigger value.
Then the program finds biggest among three given integers a,
b and c using this macro with arguments.
CABSMJ-1001 [2024-25]
/* preprocessor2.c */
#include<stdio.h>
#define BIG(x,y) ( ((x)>(y)) ? (x) : (y) )
main()
{ int a, b, c, big;
printf("Enter 3 integer numbers\n"); /* or we can write */
scanf("%d %d %d",&a,&b,&c); big = BIG(a,b);
big = BIG(BIG(a,b),c); big = BIG(big,c);
printf("Biggest number is: %d\n",big);
}
CABSMJ-1001 [2024-25]
General form:
#undef IDENTIFIER
Example:
/* file2.c */
/* present in the current folder */ bigger.c (after preprocessing)
int big(int x, int y)
{ if ( x>y ) return x; . . . . . . . . /* contents of stdio.h */
else return y; int big(int x, int y)
} { if ( x>y ) return x;
else return y;
/* bigger.c */ }
#include<stdio.h> main()
#include "file2.c" { int x = 10, y = 20, big1;
main() big1 = big(x,y);
{ int x = 10, y = 20, big1; printf("Bigger value=%d",big1);
big1 = big(x,y); }
Output
printf("bigger value=%d",big1);
} Bigger value=20
CABSMJ-1001 [2024-25]
Prob:
Write a function max(int a[],int n) that returns maximum
element and a function min(int a[],int n) that returns
minimum element in the array and save them in a file, say
myfun.c
Then write a C program that includes the myfun.c file, reads n
integer values in a 1D array and finds biggest and smallest
using the max() and min() functions.
/* myfun.c */ CABSMJ-1001 [2024-25]
Example-2
Write a C program to illustrate the use of compiler control
directives as below:
Define a macro: #define WHICH_PART 1
In the main(), test the value of WHICH_PART macro. If it is
equal to 1 then:
one set of statements (that compute the area of a
rectangle) are compiled
otherwise another set of statements (that compute the
volume of the rectangle) are compiled.
CABSMJ-1001 [2024-25]
/* preprocessor6.c illustrates conditional compiling of code */
#include<stdio.h>
#define WHICH_PART 1
main() Preprocessor will include this part
{ in the expanded code and it will be
compiled.
#if WHICH_PART==1
float l, b;
printf("Enter length and breadth of the room: "); Not included in
scanf("%f %f",&l, &b); the expanded
code and not
printf("Area of the room is = %f\n", l*b);
compiled.
#else
float l, b, h;
printf("Enter length, breadth and height of the room: ");
scanf("%f %f %f",&l, &b, &h);
printf("Volume of the room is = %f\n", l*b*h);
#endif
}
CABSMJ-1001 [2024-25]
Exercise #1.
Write a C program to find power of any given number (e.g. xn)
using recursion.
Exercise #2.
Write a C program to find sum of all odd numbers in given range
(for example, start=101 to end=120) using recursion.
Exercise #3.
Write a C program to find sum of all natural numbers between 1 to
n using recursion.
Exercise #4.
Write a C program that reads a positive integer n and counts the
number of digits in n using recursion.
Exercise #5.
Write a C program that reads a positive integer n and finds their
LCM using recursion.
CABSMJ-1001 [2024-25]
Exercise #6.
Write a C program that reads n integers in a 1D array (storage for
which is allocated using dynamic memory allocation) and prints
the mean (average) of the array elements.
Exercise #7.
Write a C program that reads n integers in a 1D array (storage for
which is allocated using dynamic memory allocation) and finds the
largest value using function.
Exercise #8.
Write a C program that reads the dimensions and elements of the
two matrices a and b for which memory is allocated dynamically
and finds their addition matrix c = a + b.
CABSMJ-1001 [2024-25]
Exercise #9.
Write symbolic constants for the binary arithmetic operators +, -, *
and /. Write a short program to illustrate the use of these symbolic
constatnts.
Exercise #10.
Define a macro ARGS that receives an integer array and the
number of elements in the array as function arguments. Write a
program that reads n integers in an array and computes the sum of
all elements of the array using function whose arguments are
ARGS.
CABSMJ-1001 [2024-25]
Exercise #11.
Write a C program that reads following data about fixed deposits
from the keyboard and appends it in a file named "fd.txt":
custid 10 chars
amount float (%10.2f)
rate float (%5.2f)
period (in years) float (%5.2f)
Exercise #12.
Write a C program that:
reads input from the file named "fd.txt" (created by the previous
program):
and displays a report showing final amounts to be paid to each
customer on maturity of his/her FD using the following formula:
Final amount = amount * ( 1+rate/100)years
FINAL AMOUNTS TO BE PAID ON MATURITY
Cust-id Amount Rate Period Final-amount
1234567891 100000.00 6.00 5.00 133822.52
1234567892 150000.00 5.00 2.00 165374.98
1234567893 200000.00 5.50 3.00 234848.23
CABSMJ-1001 [2024-25]
End of
Unit-IV