Assignment 4. Functions
C
Functions
In c, we
can divide a large program into the basic building blocks known as function.
The function contains the set of programming statements enclosed by {}. A
function can be called multiple times to provide reusability and modularity to
the C program. In other words, we can say that the collection of functions
creates a program. The function is also known as procedureor subroutinein other
programming languages.
Advantage
of functions in C
There are the following advantages of C functions.
1. By using functions, we can avoid rewriting same logic/code again and again in a program.
2. We can call C functions any number of times in a program and from any place in a program.
3. We can track a large C program easily when it is divided into multiple functions.
4. Reusability is the main achievement of C functions.
5. However, Function calling is always a overhead in a C program.
Function
Aspects
There are three aspects of a C function.
· Function declaration A function must be declared globally in a c program to tell the compiler about the function name, function parameters, and return type.
return_type function_name (argument list);
· Function call Function can be called from anywhere in the program. The parameter list must not differ in function calling and function declaration. We must pass the same number of functions as it is declared in the function declaration.
function_name (argument_list)
· Function definition It contains the actual statements which are to be executed. It is the most important aspect to which the control comes when the function is called. Here, we must notice that only one value can be returned from the function.
return_type function_name (argument list) {function body;}
The syntax of creating function in c language is given below:
return_type function_name(data_type parameter...){
//code
to be executed
}
Types
of Functions
There
are two types of functions in C programming:
1. Library Functions: are the functions which are declared in the C header files such as scanf(), printf(), gets(), puts(), ceil(), floor() etc.
2. User-defined functions: are the functions which are created by the C programmer, so that he/she can use it many times. It reduces the complexity of a big program and optimizes the code.
Return
Value :-
A C
function may or may not return a value from the function. If you don't have to
return any value from the function, use void for the return type.
Let's see a simple example of C function that doesn't return any value from the function.
1. Example without return value:
void
hello(){
printf("hello
c");
}
If you
want to return any value from the function, you need to use any data type such
as int, long, char, etc. The return type depends on the value to be returned
from the function.
Let's see a simple example of C function that returns int value from the function.
2. Example with return value:
int
get(){
return
10;
}
A function
may or may not accept any argument. It may or may not return any value. Based
on these facts, There are four different aspects of function calls.
· function without arguments and without return value
· function without arguments and with return value
· function with arguments and without return value
· function with arguments and with return value
Function
Arguments
If a
function is to use arguments, it must declare variables that accept the values
of the arguments. These variables are called the formal parameters of the
function.
Formal
parameters behave like other local variables inside the function and are
created upon entry into the function and destroyed upon exit.
While
calling a function, there are two ways in which arguments can be passed to a
function −
1. Call
by value
This
method copies the actual value of an argument into the formal parameter of the
function. In this case, changes made to the parameter inside the function have
no effect on the argument.
2.Call
by reference
This
method copies the address of an argument into the formal parameter. Inside the
function, the address is used to access the actual argument used in the call.
This means that changes made to the parameter affect the argument.
By
default, C uses call by value to pass arguments. In general, it means the code
within a function cannot alter the arguments used to call the function.
Recursion :-
Recursion
is the process of repeating items in a self-similar way. In programming
languages, if a program allows you to call a function inside the same function,
then it is called a recursive call of the function.
void recursion() {
recursion(); /* function calls itself */
}
int main()
{
recursion();
}
The C
programming language supports recursion, i.e., a function to call itself. But
while using recursion, programmers need to be careful to define an exit
condition from the function, otherwise it will go into an infinite loop.
Recursive
functions are very useful to solve many mathematical problems, such as
calculating the factorial of a number, generating Fibonacci series, etc.
Number
Factorial
The
following example calculates the factorial of a given number using a recursive
function −
#include
<stdio.h>
unsigned
long long int factorial(unsigned int i) {
if(i <= 1) {
return 1;
}
return i * factorial(i - 1);
}
int main() {
int i = 12;
printf("Factorial of %d is %d\n",
i, factorial(i));
return 0;
}
When the
above code is compiled and executed, it produces the following result −
Factorial
of 12 is 479001600
Fibonacci
Series
The
following example generates the Fibonacci series for a given number using a
recursive function −
#include
<stdio.h>
int
fibonacci(int i) {
if(i == 0) {
return 0;
}
if(i == 1) {
return 1;
}
return fibonacci(i-1) + fibonacci(i-2);
}
int main() {
int i;
for (i = 0; i < 10; i++) {
printf("%d\t\n", fibonacci(i));
}
return 0;
}
When the
above code is compiled and executed, it produces the following result −
0
1
1
2
3
5
8
13
21
34
Assignment:-
Exercise 1: To demonstrate menu driven programs and use of standard library functions
Set A . Write C programs for the following problems
1. Write a program, which accepts a character from the user and checks if it is an alphabet, digit or punctuation symbol. If it is an alphabet, check if it is uppercase or lowercase and then change
the case.
#include<stdio.h>
int main()
{
char ch;
printf("Enter Character : ");
scanf("\n %c",&ch);
if((ch>=65 && ch<=90 )|| (ch>=97 && ch<=122))
{
printf("\nIt is an Alphabet.:");
if(isupper(ch))
{
ch=tolower(ch);
printf("%c",ch);
}
else
{
ch=toupper(ch);
printf("%c",ch);
}
}
if(ch>=48 && ch<=57)
{
printf("\n'%c' is Digit.",ch);
}
if((ch>=58 && ch<=64) || (ch>=91 && ch<=96) || (ch>=33 && ch<=47) || (ch>=123 && ch<=126))
{
printf("\n'%c' is Punctuation Symbol.",ch);
}
return 0;
}
2. Write a menu driven program to perform the following operations till the user selects Exit.
Accept appropriate data for each option. Use standard library functions from math.h
i. Power
ii. Square Root
iii. Floor
iv. Ceiling
v. Exit
#include<stdio.h>
#include<math.h>
void main()
{
int ch;
double n,x,ans;
printf("\n1.Power\n2.square root\n3.Floor\n4.Ceil\n5.Exit");
while(ch!=5)
{
printf("\nEnter your Choise:");
scanf("%d",&ch);
switch(ch)
{
case 1:printf("\nEnter number and Power:");
scanf("%lf%lf",&x,&n);
ans=pow(x,n);
printf("\nPower is:%lf",ans);
break;
case 2:printf("\nEnter Number :") ;
scanf("%lf",&n);
ans=sqrt(n);
printf("\n %lf is square root of %lf",ans,n);
break;
case 3:printf("\nEnter Number:");
scanf("%lf",&n);
ans=floor(n);
printf("\n%lf floor is %lf",n,ans);
break;
case 4:printf("\nEnter Number:");
scanf("%lf",&n);
ans=ceil(n);
printf("\n%lf ceiling is %lf",n,ans);
break;
case 5:printf("\nExit");
exit(0);
}
}
}
Set B. Write C programs for the following problems
1. Accept two fractions (numerator, denominator) and perform the following operations till the user
selects Exit.
i. Addition
ii.Subtraction
iii.Multiplication
iv.EXIT
#include<stdio.h>
void main()
{
int n1,d1,n2,d2,ch;
float ans;
printf("\nEnter Numerator and denominator of First number");
scanf("%d%d",&n1,&d1);
printf("\nEnter Numerator and denominator of Secconds number");
scanf("%d%d",&n2,&d2);
printf("\n1.Addition\n2.Subtraction\n3.Multiplication\n4.Exit");
while(ch!=4)
{
printf("\nEnter your choise:");
scanf("%d",&ch);
switch(ch)
{
case 1:ans=(n1*d1+d1*n2)/d1*d2;
printf("\nAddition is %f",ans);
break;
case 2:ans=(n1*d1-d1*n2)/d1*d2;
printf("\nSubtraction is %f",ans);
break;
case 3:ans=(n1*n2)/d1*d2;
printf("\nMultiplication is %f",ans);
break;
}
}
}
Following operations till the user selects Exit.
iv. Distance between points
v. Slope of line between the points.
vi. Check whether they lie in the same quadrant.
vii. EXIT
#include<stdio.h>
#include<math.h>
void main()
{
double x1,y1,x2,y2,ans;
int ch;
printf("\nEnter Point A:");
scanf("%lf%lf",&x1,&y1);
printf("\nEnter Point B:");
scanf("%lf%lf",&x2,&y2);
printf("\n1.Distance\n2.Slop\n3.Quadrant\n4.Exit");
while(ch!=4)
{
printf("\nEnter your chosie:");
scanf("%d",&ch);
switch(ch)
{
case 1:ans=(x2-x1)*(x2-x1)+(y2-y1)*(y2-y1);
ans=sqrt(ans);
printf("\nDistance is %lf:",ans);
break;
case 2:ans=(y2-y1)/(x2-x1);
printf("\nSlop is %lf:",ans);
break;
case 3:if(x1>0 &&x2>0 &&y1>0 &&y2>0)
printf("\nIn same quadrant and in First quadrant:");
break;
}
}
}
Exercise 2:
int gcd(int, int);
int main()
{
int a, b, result;
printf("Enter the two numbers to find their GCD: ");
scanf("%d%d", &a, &b);
result = gcd(a, b);
printf("The GCD of %d and %d is %d.\n", a, b, result);
}
int gcd(int a, int b)
{
while (a != b)
{
if (a > b)
{
return gcd(a - b, b);
}
else
{
return gcd(a, b - a);
}
}
return a;
}
int power (int, int);
int main()
{
int pow, num;
long result;
printf("Enter a number: ");
scanf("%d", &num);
printf("Enter it's power: ");
scanf("%d", &pow);
result = power(num, pow);
printf("%d^%d is %ld", num, pow, result);
return 0;
}
int power (int num, int pow)
{
if (pow)
{
return (num * power(num, pow - 1));
}
return 1;
}
#include <math.h>
int rev(int, int);
int main()
{
int num, result;
int length = 0, temp;
printf("Enter an integer number to reverse: ");
scanf("%d", &num);
temp = num;
while (temp != 0)
{
length++;
temp = temp / 10;
}
result = rev(num, length);
printf("The reverse of %d is %d.\n", num, result);
return 0;
}
int rev(int num, int len)
{
if (len == 1)
{
return num;
}
else
{
return (((num % 10) * pow(10, len - 1)) + rev(num / 10, --len));
}
}
No comments:
Post a Comment