CSE 115 Lab on functions – Ara2
1. C program illustrating the difference between void and non-void function:
#include <stdio.h> //main function
// definition of a non-void function void main()
float computeSquare(float x) {
{ float m, n;
return x*x; printf("\nEnter a number: ");
} scanf("%f", &m);
//call computeSquare function on m
// definition of a void function n = computeSquare(m);
void printCube(float x) printf ("Square = %f", n);
{ //call printCube function on m
printf("Cube = %f", x*x*x); printCube(m);
} }
2. C program to determine if a given number is odd/even using function
#include <stdio.h> void main()
void oddEven(int x) {
{ int m;
if(x%2==0) printf("Even"); printf("\nEnter an integer: ");
else printf("Odd"); scanf("%d", &m);
} oddEven(m); //function call
}
Try yourself2: Write C program using a function to check if a given number is positive, negative, or zero.
3. C program to determine if a given number is prime using function
#include <stdio.h> int main()
int isPrime(int x) {
{ int m;
int i; printf("\nEnter an integer: ");
for(i=2;i<=x/2;i++) scanf("%d", &m);
{ int n = isPrime(m);
if(x%i==0) if(n==0)
return 0; printf("Not prime")
} else
return 1; printf("Prime");
} }
Try yourself 3: Write C program using a function to check if a given number is a perfect number.
4. C program to compute sum of all natural numbers between m and n (using function)
#include <stdio.h> int main()
int sum(int m, int n) {
{ int n;
int i, sum=0; printf("\nEnter 2 integers: ");
for(i=m;i<=n;i++) scanf("%d%d", &m, &n);
{
sum+=i; int s = sum(m,n);
} printf("sum=%d",s)
return sum; }
}
5. C program to compute the integer resulting from rounding a number n (using function)
#include <stdio.h> int main()
int round1(float n) {
{ float n;
int i=n; //integer part of n printf("\nEnter a number: ");
if(n-i>=0.5) return i+1; scanf("%f", &n);
else return i;
} int s = round1(n);
printf("%d",s)
}
Exercise:
1. Write a C program using 3 functions to compute diameter, circumference and area of a circle whose
radius is given by the user as the input.
2. Find the sum of the following series using a function: 12 + 22 + 32 + … + N2
Assignment:
1. Find the sum of the following series using user-defined function: 1/1! + 2/2! + 3/3! + …… +1/N!
2. Write a C code using functions that takes two integers: a and b as inputs and returns the value of ab.
3. Compute the sum of the following geometric progression using a function with 2 parameters r and n:
1 + r + r2 + … + rn (read the values of r and n from user)
4. Write a C program that reads an integer and returns the reverse of that number using function.
5. Write a C program using function that reads a floating point number n and an integer d and then
prints the rounded value of n up to d decimal places. E.g. for n=5.678 and d = 2; it should print 5.68