Week 11
Week 11
Objective: Explore the Functions, sub-routines, scope and extent of variables, doing some
experiments by parameter passing using call by value. Basic methods of numerical integration
Suggested Experiments/Activities:
Tutorial 11: Functions, call by value, scope and extent
Lab 11: Simple functions using call by value, solving differential equations using Eulers
theorem.
i) Write a C function to calculate NCR value.
ii) Write a C function to find the length of a string.
iii) Write a C function to transpose of a matrix.
iv) Write a C function to demonstrate numerical integration of differential equations
using Euler’s method
Source Code:
//C program to calculate the value of nCr
#include <stdio.h>
int fact(int z); /* Function Prototype */
int main()
void main()
{
int N,R,NCR;
printf("Enter the value for N and R \n");
scanf("%d%d",&N,&R);
NCR=fact(N)/(fact(R)*fact(N-R)); /* Function Call */
printf("The value of NCR is:%d",NCR);
}
/* Function Definition */
int fact(int z)
{
int f=1,i;
if(z==0)
{
return(f);
}
else
{
for(i=1;i<=z;i++)
{
f=f*i;
}
}
return(f);
}
Output:
ii) Write a C function to find the length of a string.
Aim: To write a C function to find the length of a string.
Source Code:
#include <stdio.h>
int mystrlen(char s[30]); /* Function Prototype */
int main()
{
char s[30];
int i,length;
printf("Enter a string: ");
gets(s);
length=mystrlen(s); /* Function Call */
printf("Length of string:%d",length);
return 0;
}
/* Function Definition */
int mystrlen(char s[30])
{
int i,length=0;
for(i=0;s[i]!='\0';i++)
{
length++;
}
return(length);
}
Output:
iii) Write a C function to transpose of a matrix.
Aim: To write a C function to transpose of a matrix.
Source Code:
#include <stdio.h>
void transpose(int arr[10][10],int m,int n) //Function Definition
{
int i,j;
printf("\nAfter transpose the elements are...\n");
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
printf("%d ",arr[j][i]);
}
printf("\n");
}
}
int main()
{
int arr[10][10],i,j,m,n;
printf("Enter the number of rows and columns:\n");
scanf("%d%d",&m,&n);
printf("\nEnter the elements of the matrix:\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&arr[i][j]);
}
}
printf("\nThe elements in the matrix are:\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("%d ",arr[i][j]);
}
printf("\n");
}
transpose(arr,m,n); //Function Call
return 0;
}
Output:
iv) Write a C function to demonstrate numerical integration of differential equations
using Euler’s method
Aim: To write a C function to demonstrate numerical integration of differential equations using
Euler’s method
General Formula
Pseudocode:
Source Code:
#include <stdio.h>
int main()
{
// Initial conditions
double x0=0.0;
double y0=1.0;
Output: