0% found this document useful (0 votes)
60 views25 pages

Session 3 - Module 3-Lectures 18-19

The document provides information on functions in C programming. It discusses different types of functions like built-in functions and user-defined functions. It also covers key concepts related to functions like arguments, return values, scope, and storage classes. The document contains code examples to demonstrate function definition, passing parameters, and accessing global and local variables from within functions. It also briefly discusses recursion and different storage classes like extern, auto, register and static.

Uploaded by

lordgaming2407
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
60 views25 pages

Session 3 - Module 3-Lectures 18-19

The document provides information on functions in C programming. It discusses different types of functions like built-in functions and user-defined functions. It also covers key concepts related to functions like arguments, return values, scope, and storage classes. The document contains code examples to demonstrate function definition, passing parameters, and accessing global and local variables from within functions. It also briefly discusses recursion and different storage classes like extern, auto, register and static.

Uploaded by

lordgaming2407
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 25

Session

Session 33 –– Module2-Revision
Module2-Revision
Module
Module 33

Principles of Programming Using C


BPOPS103
1st Sem Physics Cycle
Dr. P. N. Singh,
Professor(CSE/ISE), CMRIT, Bangalore
Sr. IEEE Member, Life members: CSI,ISTE,ISCA
Past-President, ICT-CS, Indian Science Congress – 2021-23
Revision of looping programs, user defined functions then
2-d/M-D array
Pascal’s triangle
/* Pascal's triangle - Dr. P. N. Singh */
Expected output: Plotting
#include <stdio.h> Pascal’s triangle
int main() {
int x,y,z,p; 1
for(x=0;x<9;x++) {
for(y=1;y<20-x;y++) 1 1
printf(" "); /* for blank spaces */
for(y=0;y<x;y++) { 1 2 1
if(x==0 || y== 0) p=1;
1 3 3 1
else p=p*(x-y)/y; /* For Binomial co-efficient */
printf("%4d",p); /* printing value taking 4 minimum spaces 1 4 6 4 1
*/
} 1 5 10 10 5 1
printf("\n");
} 1 6 15 20 15 6 1
return (0); 1 7 21 35 35
} 21 7 1
Square root of a number without using built-in function sqrt ()
⚫ The iterative method is called ”The Babylonian method or Hero's method long before Newton
invented his general procedure.
⚫ Here's how it works. Suppose you are given any positive number S. To find the square root of S, do
the following:
⚫ Make an initial guess. Guess any positive number x0.
⚫ Improve the guess. Apply the formula x1 = (x0 + S / x0) / 2. The number x1 is a better approximation
to sqrt(S).
⚫ Iterate until convergence. Apply the formula xn+1 = (xn + S / xn) / 2 until the process converges.
Convergence is achieved when the digits of xn+1 and xn agree to as many decimal places as you
desire.
⚫ Let's use this algorithm to compute the square root of S = 20 to at least two decimal places.
⚫ Initial guess is x0 = 10 (usually number /2 because square root will be <= half of the number)
⚫ Apply the formula: x1 = (10 + 20/10)/2 = 6. The number 6 is a better approximation to sqrt(20).
⚫ Apply the formula again to obtain x2 = (6 + 20/6)/2 = 4.66667.
⚫ The next iterations are x3 = 4.47619 and x4 = 4.47214.
⚫ Because x3 and x4 agree to two decimal places, the algorithm ends after four iterations. An estimate
for sqrt(20) is 4.47214
/* finding sqrt of a number without using sqrt() built in method*/
#include <stdio.h>
#include <math.h>
int main()
{
double num,x1,x2,diff;
printf("Enter any number : ");
scanf("%lf",&num);
x1=num/2.00;
x2=num/x1;
do {
x1=(x1+x2)/2.00;
x2 = num/x1;
diff=x1-x2;
}while(diff>0.0000001);
printf("Square root = %.3lf\n",x1);
return (0);
}
Recursion /* Fibonacci series using recursion */
/* GCD using recursion */ #include <stdio.h>
#include <stdio.h> int fibo(int n) {
int gcd(int a,int b) { if (n==1)
int rem=a%b; return (0);
if(rem==0)
return (b);
if (n==2)
else return (1);
return (gcd(b,rem)); return (fibo(n-1)+fibo(n-2));
} }
int main() { int main() {
int x,y,hcf; int n,x;
printf("Enter two numbers : "); printf("Enter nth term for Fibonacci series : ");
scanf("%d%d",&x,&y);
scanf("%d",&n);
hcf=gcd(x,y);
printf("GCD = %d\n",hcf);
for(x=1;x<=n;x++)
printf("LCM = %d\n",x*y/hcf); printf(" %d",fibo(x));
return (0); return (0);
} }
Enter nth term for Fibonacci series : 20
Enter two numbers : 45 10 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584
GCD = 5 4181
LCM = 90
cos(x) expansion by Taylor
series
Algorithm
1. Start
2. Input deg, n
3. Set x = deg * 3.142 / 180.0
4. result = sign, fact = 1, pow = 1
5. For i = 1 to n
6. sign = sign * -1
7. fact = fact * (2 * i - 1) * (2 * i)
8. pow = pow * x * x
9. result = result + sign * pow / fact
10. End for
11. print result
12. print result of cos(x) by library function
/* cos(x) expansion by Taylor's series and by built in method
x is radian, cox(x) = 1- x^2/2! + x^4/4! - x^6/6! + ..... Dr. P. N. Singh
*/
#include <stdio.h>
#include <math.h>
int main() { Enter degree : 60
int deg,n,i; Enter number of terms : 5
float x,result,s,fact,pow; 60 converted to 1.047 radian
printf("Enter degree : ");
fact = 2 simulating cos(1.047) radian = 0.452
scanf("%d",&deg);
printf("Enter number of terms : "); fact = 24 simulating cos(1.047) radian = 0.502
scanf("%d",&n); fact = 720 simulating cos(1.047) radian = 0.500
x=deg*3.142/180; /*converting degree to radian*/ fact = 40320 simulating cos(1.047) radian = 0.500
printf("%d converted to %0.3f radian\n",deg,x); fact = 3628800 simulating cos(1.047) radian = 0.500
result=s=fact=pow=1.00; Computed cos(60) by expansion = 0.500
for(i=1;i<=n;i++) By library cos(60) = 0.500
{
s=s* -1;
fact=fact*(2*i-1)*(2*i); /*Understand it*/
pow=pow*x*x;
result = result+s*pow/fact;
printf("fact = %.0f simulating cos(%.3f) radian = %.3f\
n",fact,x,result);
}
printf("Computed cos(%d) by expansion = %.3f\n", deg,result);
printf("By library cos(%d) = %.3f\n",deg,cos(x));
return (0);
}
How’s that?

/* to print 1 to 10 without using semicolon */


#include <stdio.h>
#define N 10
int main(int num)
{
if(num <= N && printf("%d ", num) && main(num+1)) { }
}
Module 3

Functions: Introduction using functions, Function definition, function


declaration, function call, return statement, passing parameters to functions,
scope of variables, storage classes, recursive functions.

Arrays: Declaration of arrays, accessing the elements of an array, storing


values in arrays, Operations on arrays, Passing arrays to functions, two
dimensional arrays, operations on two-dimensional arrays, two
dimensional arrays to functions, multidimensional arrays, applications
of arrays.
Functions in C
⚫ A function is a self-contained block of statements that performs a coherent task of some kind.
Mathematical definition of a function is like that “A function f(x) returns value for the argument x.”
y = f(x)
⚫ Functions are classified of two types – In-built function and User/Programmer defined functions. A
function name is followed by a pair of ( ).
⚫ A function may or may not have arguments. Arguments are written within parentheses separating
by , (comma).
⚫ A function may or may not return a value. void function does not return a value (Procedure). It
can return one, one and only one value.
⚫ In-built library Functions examples - printf( ), scanf( ) etc.
⚫ Programmer defined function/User defined function(UDF) - main( ) and may be like sort( ), fact( )
etc.
⚫ Yes, main( ) is a user defined function which is specially recognised function in C. Every program
must have a function main( ) to indicate where the program has to begin its execution.
⚫ We know the concept that larger programs are splitted in smaller self contained components each
of which has some unique, identification purpose. “Functions are building blocks of a program”
⚫ It is modular approach to program development. It becomes easy to test & debug. C also permits
nesting of functions.
Storage class – extern, auto, register, static
Scope – local or global (auto and extern)
Global – storage class extern: #include <stdio.h>
• Identifiers defined outside of a function extern int g = 100;
are by default gobal (whether extern is void func(int a, int b) {
written or not). printf("in func Value of global g = %d\n",g);
• They will be publically available to all the printf("In func a = %d b = %d\n",a,b);
functions and may be corrupted/modified a=40; b= 50; g=200;
by any of the functions. printf("In func changed value a = %d b=%d g = %d\n",a,b,g);
}
Local – storage class auto:
int main() {
• Identifiers defined inside a function are int a=20,b=30; /* auto int a= 20, b=30 */
by default local (whether auto is written or printf("In main a = %d b=%d g = %d\n",a,b,g);
not). func(a,b); /* calling func with a=20 & b= 30 */
• No way local variables defined within a printf("in main after function call a = %d b= %d g=%d\n",a,b,g);
function will be modified by other return (0);
function. }
• Scope of a local variable is within the
block only or the function in which it is In main a = 20 b=30 g = 100
in func Value of global g = 100
defined In func a = 20 b = 30
In func changed value a = 40 b=50 g = 200
in main after function call a = 20 b= 30 g=200
Storage class – extern, auto, register, static
register –scope local
Storage clasds register – (local) #include <stdio.h>
void func(){
• Registers are built-in register char c;
memory with CPU for(c='a';c<=122;c++)
printf(" %c",c);
• Should be stored in a register
}
instead of RAM. This means int main() {
that the variable has a func();
maximum size equal to the return (0);
register size (usually one word) }
and can't have the unary '&'
operator applied to it (as it does
not have a memory location). abcdefghijklmnopqrstuvwxyz
Storage class – extern, auto, register, static
static –scope local
Storage class static – (local) #include <stdio.h>
• static variables have a property int func()
of preserving their value even {
after they are out of their static int k=0; /* check with removing static */
k++;
scope! (but not constant) So return (k);
we can say that they are }
initialized only once and exist int main() {
till the termination of the int x, sum=0;
program. Thus, no new for(x=1;x<=5;x++)
sum+=func();
memory is allocated because printf("sum = %d\n",sum);
they are not re-declared. return (0);
• Static variables are by default }
initialized to 0 but not again
Sum = 15
reinitialized to 0
Taking odd and even numbers from array and putting in ODD[] and EVEN array.
/* putting odd and even numbers in ODD[] and EVEN arrays */
#include <stdio.h>
int main() {
int x,arr[100],ODD[50],EVEN[50],size,p,q; Size of the array : 10
printf("\nSize of the array : "); Enter element 1 : 33
scanf("%d",&size); Enter element 2 : 4
for(x=0;x<size;x++) {
Enter element 3 : 55
printf("Enter element %d : ", x+1);
scanf("%d",&arr[x]); Enter element 4 : 6
} Enter element 5 : 77
/*putting odd and even numbers in 2 separate arrays*/ Enter element 6 : 65
p=0; /* index of ODD array */ Enter element 7 : 76
q=0; /* index of EVEN array */ Enter element 8 : 23
for(x=0;x<size;x++) Enter element 9 : 34
if(arr[x] %2 ==0) { EVEN[q]=arr[x]; q++; }
Enter element 10 : 55
else {ODD[p]=arr[x]; p++; }

printf("\nArray with odd numbers:\n"); Array with odd numbers:


for(x=0;x<p;x++) 33 55 77 65 23 55
printf(" %d",ODD[x]); Array with even numbers:
4 6 76 34
printf("\nArray with even numbers:\n");
for(x=0;x<q;x++)
printf(" %d",EVEN[x]);

return (0);
}
Actual argument, formal argument
⚫ Formal #include <stdio.h>
Arguments/Parameters int interest (int p, int t, int r) { /* formal arguments */
: Which appears in the return (p*r/100*t);
called function }
(Receives the int main ( )
argument) {
⚫ Actual int inter, amt, pri,terms,rate;
Arguments/Parameters printf("Enter principle, terms & rate of interest" );
: That appears in scanf("%d%d%d", &pri, &terms,&rate);
calling function inter=interest(pri,terms,rate); /*Actual arguments */
⚫ Actual argument will amt=pri+inter;
replace the formal printf("Interest = %d Amount=%d\n",inter,amt);
argument return (0);
}
2-Dimensional Array

Declaration of Two-dimensional array:


syntax:
type arrayname[rowsize][columnsize];
Examples:
int stud[16][5]; /* 2D array to initialize by program */
Initialization of Two-dimensional array: #include<stdio.h>
int main()
Examples:
{
int marks[3][3] = { int arr[3][4];
{26,57,66}, int i, j;
{56,77,48}, for(i = 0; i < 3; i++)
{76,54,82} for(j = 0; j < 4; j++) {
}; printf("Enter value for row %d col %d : ",i+1,j+1);
scanf("%d",&arr[i][j]);
int a5][4]={{0}}; }
Here first element is initialized to zero and rest of the
return (0);
elements will be initialized to zero. }
int marks[3][3] = { {12},{0},{0}};
Here first element of each row is explicitly initialized to 12
while other elements are automatically initialized to zero.
Sum and avg of Each row: marks in 6 papers
/* finding sum and average of each row
Enter marks for student 1 paper 1 : 55
n students appeared in p papers*/
#include <stdio.h> Enter marks for student 1 paper 2 : 45
#define n 5 Enter marks for student 1 paper 3 : 65
#define p 6 Enter marks for student 1 paper 4 : 67
int main() Enter marks for student 2 paper 1 : 65
{ Enter marks for student 2 paper 2 : 54
int marks[n][p],r,c,sum[n];
Enter marks for student 2 paper 3 : 55
float avg[n];
for(r=0;r<n;r++) Enter marks for student 2 paper 4 : 87
{ Enter marks for student 3 paper 1 : 78
sum[r]=0; Enter marks for student 3 paper 2 : 88
for(c=0;c<p;c++) Enter marks for student 3 paper 3 : 81
{ Enter marks for student 3 paper 4 : 63
printf("Enter marks for student %d paper %d : ",r+1,c+1);
Enter marks for student 4 paper 1 : 43
scanf("%d",&marks[r][c]);
sum[r]+=marks[r][c]; Enter marks for student 4 paper 2 : 61
} Enter marks for student 4 paper 3 : 72
avg[r]=(float)sum[r]/c; Enter marks for student 4 paper 4 : 54
} Enter marks for student 5 paper 1 : 55
printf("student p1 p2 p3 p4 sum avg\n"); Enter marks for student 5 paper 2 : 66
for(r=0;r<n;r++)
Enter marks for student 5 paper 3 : 66
{
printf("%5d",r+1); Enter marks for student 5 paper 4 : 65
for(c=0;c<p;c++) student p1 p2 p3 p4 sum avg
printf("%4d",marks[r][c]); 1 55 45 65 67 232 58.00
2 65 54 55 87 261 65.25
printf("%5d%7.2f\n",sum[r],avg[r]); 3 78 88 81 63 310 77.50
}
4 43 61 72 54 230 57.50
return(0);
} 5 55 66 66 65 252 63.00
Sum and average of each row and columns
/* finding sum and average of each row and columns */ Enter marks for student 1 paper 1 : 55
#include <stdio.h>
#define n 5
Enter marks for student 1 paper 2 : 66
#define p 6 Enter marks for student 1 paper 3 : 76
int main() { Enter marks for student 1 paper 4 : 75
int marks[n][p],r,c,rsum[n],csum[p];
float ravg[n],cavg[p];
Enter marks for student 2 paper 1 : 65
for(r=0;r<n;r++) { Enter marks for student 2 paper 2 : 64
rsum[r]=0; Enter marks for student 2 paper 3 : 57
for(c=0;c<p;c++) {
printf("Enter marks for student %d paper %d :
Enter marks for student 2 paper 4 : 78
",r+1,c+1); Enter marks for student 3 paper 1 : 89
scanf("%d",&marks[r][c]); Enter marks for student 3 paper 2 : 91
rsum[r]+=marks[r][c];
}
Enter marks for student 3 paper 3 : 85
ravg[r]=(float)rsum[r]/p; Enter marks for student 3 paper 4 : 67
} Enter marks for student 4 paper 1 : 54
for(c=0;c<p;c++) {
csum[c]=0;
Enter marks for student 4 paper 2 : 55
for(r=0;r<n;r++) Enter marks for student 4 paper 3 : 66
csum[c]+=marks[r][c]; Enter marks for student 4 paper 4 : 77
cavg[c]=(float)csum[c]/n;
}
Enter marks for student 5 paper 1 : 88
printf("student p1 p2 p3 p4 p5 p6 sum avg\n"); Enter marks for student 5 paper 2 : 76
for(r=0;r<n;r++) { Enter marks for student 5 paper 3 : 78
printf("%5d",r+1);
for(c=0;c<p;c++)
Enter marks for student 5 paper 4 : 54
printf("%4d",marks[r][c]); student p1 p2 p3 p4 Sum Avg
printf("%5d%7.2f\n",rsum[r],ravg[r]); 1 55 66 76 75 272 68.00
}
printf(" ");
2 65 64 57 78 264 66.00
for(c=0;c<p;c++) 3 89 91 85 67 332 83.00
printf("%5d",csum[c]); 4 54 55 66 77 252 63.00
printf("\n ");
for(c=0;c<p;c++)
5 88 76 78 54 296 74.00
printf("%7.2f",cavg[c]); Sum 351 352 362 351
return(0); Avg 70.20 70.40 72.40 70.20
}
Identity Matrix
⚫ a square matrix in which all the elements of the
principal diagonal are ones and all other elements
are zeros.
⚫ The effect of multiplying a given matrix by an
identity matrix is to leave the given matrix
unchanged.
2-Dimensional array-Transposing a matrix
#include <stdio.h>
int main() {
int r,c,temp,mat1[4][4]; Enter 4x4 matrix:
printf("Enter 4x4 matrix:\n"); 4567
for(r=0;r<4;r++) 2135
for(c=0;c<4;c++) 6784
scanf("%d",&mat1[r][c]); 4567
The Transposed Matrix
4 2 6 4
/* Transposing */ 5 1 7 5
for(r=0;r<4;r++) 6 3 8 6
for(c=r+1;c<4;c++) { /* c=r+1 is the logic, c=0 is foolish*/ 7 5 4 7
temp=mat1[r][c];
mat1[r][c]=mat1[c][r];
mat1[c][r]=temp;
}
printf("The Transposed Matrix\n");
for(r=0;r<4;r++) {
for(c=0;c<4;c++)
printf("%4d",mat1[r][c]);
printf("\n");
}
return (0);
}
Addition of matrices
/* Addition of matrices */
#include<stdio.h> Enter matrix a (4x4):
int main() 2345
{ 4532
int a[4][4],b[4][4],c[4][4],i,j; 1324
printf("Enter matrix a (4x4):\n"); 5643
Enter matrix b (4x4):
for(i=0;i<4;i++)
2457
for(j=0;j<4;j++) 4357
scanf("%d",&a[i][j]); 3257
6543
printf("Enter matrix b (4x4):\n"); Resultant Matrix:
for(i=0;i<4;i++) 4 7 9 12
for(j=0;j<4;j++) { 8 8 8 9
4 5 7 11
scanf("%d",&b[i][j]);
11 11 8 6
c[i][j]=a[i][j]+b[i][j];
}
printf("Resultant Matrix:\n");
for(i=0;i<4;i++) {
for(j=0;j<4;j++)
printf("%5d",c[i][j]);
printf("\n");
}
return (0);
}
Multiplication of matrices
/* Multiplication of matrices – mnp concept Dr. P. N.
Singh */
#include<stdio.h>
int main()
{
int a[100][100],b[100][100],c[100][100],i,j,k,m,n,p;
printf("Enter total rows and cols of matrix a : ");
scanf("%d%d",&m,&n); Enter total rows and cols of
printf("Total column of matrix b : "); matrix a : 3 4
scanf("%d",&p); Total column of matrix b : 4
printf("Enter matrix a - %d x %d:\n",m,n);
for(i=0;i<m;i++)
Enter matrix a - 3 x 4:
for(j=0;j<n;j++) 2345
scanf("%d",&a[i][j]); 2134
4356
printf("Enter matrix b - %d x %d:\n",n,p); Enter matrix b - 4 x 4 :
for(i=0;i<n;i++)
3245
for(j=0;j<p;j++)
scanf("%d",&b[i][j]); 2345
1232
printf("Resultant Matrix:\n"); 4356
for(i=0;i<m;i++) { Resultant Matrix:
for(j=0;j<p;j++) { 36 36 57 63
c[i][j]=0;
27 25 41 45
for(k=0;k<n;k++)
47 45 73 81
c[i][j] += a[i][k] * b[k][j];
printf("%5d", c[i][j]);
}
printf("\n");
}
return (0);
}
Reference

⚫ NPTEL-IIT lecture series (array operations)


⚫ https://www.youtube.com/watch?v=TXcz8FTulzY

You might also like