Wednesday, October 7, 2020

Assignment 4. Functions

 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;

}

}

}


2. Accept x and y coordinates of two points and write a menu driven program to perform the

 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:

Objective:  To demonstrate writing C programs in modular way (use of user defined functions)

Set A. Write C programs for the following problems
1. Write a function isEven, which accepts an integer as parameter and returns 1 if the number is
even, and 0 otherwise. Use this function in main to accept n numbers and check if they are
even or odd.

#include<stdio.h>
int isEven(int);
void main()
{
int num,n,c;
int i;
printf("How many number ? \n");
scanf("%d",&num);
for(i=1;i<=num;i++)
{
scanf("%d",&n);
c=isEven(n);
if(c==1)
printf("Even number\n");
else
printf("Odd number\n");
 
}
}
int isEven(int x)
{
if(x%2==0)
return 1;
else
return 0;
}

2. Write a function, which accepts a character and integer n as parameter and displays the next n
characters.

#include <stdio.h>
int display(char);
int main()
{
 char ch,c;
 printf("Enter character:");
 scanf("%c", &ch);
 display(ch);
}
int display(char ch)
{
 int n,i;
 printf("how many next char:");
 scanf("%d",&n);
 printf("\nYou entered:\t%c\n", ch);
 printf("Next character :");
 for(i=0;i<n;i++)
 {
  ch=ch+1;
     printf("\t%c", ch);
 }
 return 0;
}

Set B . Write C programs for the following problems
1. Write a function isPrime, which accepts an integer as parameter and returns 1 if the number is
prime and 0 otherwise. Use this function in main to display the first 10 prime numbers.

#include <stdio.h>
int isPrime(int n);
void main()
{
    int  i=2,j=0 ,flag;
    printf("First 10 prime number are : ");
while(j!=10)
    {
        flag = isPrime(i);
        if(flag == 1)
        {
            j++;
            printf("%d ",i);
  }
  i++;  
    }
     
}
int isPrime(int n)
{
    int j, flag = 1;
    for(j=2; j <= n/2; ++j)
    {
        if (n%j == 0)
        {
            flag =0;
            break;
        }
    }
    return flag;
}


2. Write a function that accepts a character as parameter and returns 1 if it is an alphabet, 2 if it is adigit and 3 is it is a special symbol. In main, accept characters till the user enters EOF and use
the function to count the total number of alphabets, digits and special symbols entered.

#include <stdio.h>
#include <stdlib.h>
void calc();
void main()
{
 calc();
}
void calc()
{
    char    str[100];
    int cd,ca,csc,cs;
    int c;
 
    cd=ca=csc=cs=0;
 
    printf("Enter a string: ");
    gets(str);
 
    for(c=0;str[c]!=NULL;c++)
    {
 
        if(str[c]>='0' && str[c]<='9')
            cd++;
        else if((str[c]>='A' && str[c]<='Z')||(str[c]>='a' && str[c]<='z'))
            ca++;
        else if(str[c]==' ')
            cs++;
        else
            csc++;
    }
 
    printf("\nDigits: %d \nAlphabets: %d \nSpaces: %d \nSpecial Characters: %d",cd,ca,cs,csc);
 
}

3. Write a function power, which calculates x^y. Write another function, which calculates n! UsingFor loop. Use these functions to calculate the sum of first n terms of the Taylor series: sin(x) = x – x^3/3!  + x^ 5 /5! 
#include<stdio.h> #include<math.h> void calc(); void main() { calc(); } void calc() { int x,i; int fact = 1,num; float sum=0; printf("\nEnter the value of x in the series : "); scanf("%d",&x); printf("\nEnter the number of terms in the series : "); scanf("%d",&num); for(i=1;i<num;i++) { fact = fact*i; sum = sum + (pow(x,i)/fact) ; } sum= sum +1; printf("\nThe sum of the taylor series is : %.2f\n\n",sum); }


Exercise 3: Objective: To demonstrate Recursion.

Set A . Write C programs for the following problems
1. Write a recursive C function to calculate the sum of digits of a number.
Use this function in main to accept a number and print sum of its digits.

#include <stdio.h> int sum (int a); int main() { int n, res; printf("Enter the number: "); scanf("%d", &n); res = sum(n); printf("\nSum of digits in %d is %d\n", n, res); return 0; } int sum (int n) { if (n != 0) { return (n % 10 + sum (n / 10)); } else { return 0; } }

2. Write a recursive C function to calculate the GCD of two numbers.
Use this function in main.The GCD is calculated as :
gcd(a,b) = a if b = 0
         = gcd (b, a mod b) otherwise

#include <stdio.h>
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;
}

3. Write a recursive C function to calculate x^y
(Do not use standard library function)

#include <stdio.h>
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;
}


Set B . Write C programs for the following problems
1. Write a recursive function to calculate the nth Fibonacci number. Use this function in main to Display the first n Fibonacci numbers. The recursive definition of nth Fibonacci number is as follows:
fib(n) = 1 if n = 1 or 2
           = fib(n-2) + fib(n-1) if n>2

#include <stdio.h>
int fib(int n);
void main()
{
    int n;
    int res;
 
    printf("Enter the nth number in Fibonacci  series: ");
    scanf("%d", &n);
    if (n < 0)
    {
        printf("\nFibonacci of negative number is not possible.\n");
    }
    else
    {
        res = fib(n);
        printf("\nThe %d number in Fibonacci series is %d\n", n, res);
    }
     
}
int fib(int n)
{
    if (n == 0)
    {
        return 0;
    }
    else if (n == 1)
    {
        return 1;
    }
    else
    {
        return(fib(n - 1) + fib(n - 2));
    }
}

2. Write a recursive function to calculate the sum of digits of a number till you get a single digit number.
Example: 961 -> 16 -> 5. (Note: Do not use a loop)

#include <stdio.h>
int sumOfDigits(int num);

int main()
{
    int num, sum;
    
    printf("Enter any number to find sum of digits: ");
    scanf("%d", &num);
    
    sum = sumOfDigits(num);
    
    printf("Sum of digits of %d = %d", num, sum);
    
    return 0;
}

int sumOfDigits(int num)
{
       if(num == 0)
        return 0;
        
    return ((num % 10) + sumOfDigits(num / 10));
}

3. Write a recursive C function to print the digits of a number in reverse order. Use this function in main to accept a number and print the digits in reverse order separated by tab.
Example: 3456     6     4     5     3
(Hint: Recursiveprint(n) = print n if n is single digit number
                                         = print n % 10 + tab + Recursiveprint( n/10)

#include <stdio.h>
#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