0% found this document useful (0 votes)
18 views13 pages

Unit 4

The document discusses modular programming in C, highlighting its benefits such as easier testing and reusability of functions. It explains the types of functions, including built-in and user-defined, and details the concepts of call by value and call by reference. Additionally, it covers recursion, sorting algorithms like bubble sort, insertion sort, and selection sort, and provides examples of C programs for each concept.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views13 pages

Unit 4

The document discusses modular programming in C, highlighting its benefits such as easier testing and reusability of functions. It explains the types of functions, including built-in and user-defined, and details the concepts of call by value and call by reference. Additionally, it covers recursion, sorting algorithms like bubble sort, insertion sort, and selection sort, and provides examples of C programs for each concept.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Programming

for
Problem Solving

UNIT - 4

Rajesh Tripathi
SIET

1
Q. What is modular programming in c? Explain.

Ans.- Modular programming is a software design technique that increases the extents to which software is
composed from separate parts , called the modules or functions. Modular programming can often be performed
even where language lacks explicit syntax or semantics to support modules.

Segmenting a program into manageable chunks is a very important aspect to programming; following
are the reasons for segmenting:

1. Dividing the program into a number of separate functions allow each function to be written and
tested separately.
2. Several separate functions are easier to handle and understand than huge function.
3. Libraries are sets of functions that people tend to use all the time.

Advantage:

 Modules can be written and tested separately


 Modules can be reused
 Large projects can be developed in parallel
 Reduces length of program, making it more readable
 Promotes the concept of abstraction
 A module hides details of a task
 We just need to know what this module does
 We don’t need to know how it does it

Functions in C :

The function is a self contained block of statements which performs a coherent task of a same kind. C program
does not execute the functions directly. It is required to invoke or call that functions. When a function is called
in a program then program control goes to the function body. Then, it executes the statements which are
involved in a function body. Therefore, it is possible to call function whenever we want to process that
functions statements.

Types of functions :

There are 2(two) types of functions as:

1. Built in Functions/ pre defined function


2. User Defined Functions
1. Built in Functions : These functions are also called as 'library functions'. These functions are provided by
system. These functions are stored in library files. e.g.

 scanf()
 printf()
 strcpy
 strlwr
 strcmp
 strlen
 strcat

2. User Defined Functions :

2
The functions which are created by user for program are known as 'User defined functions'.
Syntax:

Structure of a Function

There are two main parts of the function. The function header and the function body.

int sum(int x, int y)


{
int ans = 0; //holds the answer that will be returned
ans = x + y; //calculate the sum
return ans //return the answer
}

Function Declaration/Function Prototype

Just as you can’t use a variable without first telling the compiler what it is, you also can’t use a functions
without telling the compiler about it, There are two ways to do this . The approach we show here is declare the
function before it is called. The other approach is to define it before it”s called. ; we’ll examine that next.) in the
Table program, the functions starline() is declared in the line.

Void starline ( );

The declaration tells the compiler that at some later point we plan to present a function called starline. The
keyword void specifies that the function has no return value, and the empty parentheses indicate that it takes no
arguments.

Notice that the functions declarations is terminated with a semicolon It is a complete statement in itself.

Function declarations are also called prototypes, since they provide a model or blueprint for the function. They
tell the compiler,” a function that looks like this is coming up later in the program, so it’s all right if you see
references to it before you see the function itself.”

Calling the Function

The function is called (or invoked) three times from main (). Each of the three calls look like this:

Starline():

This is all we need to call a function name, followed by parentheses. The syntax of the call is very similar to
that of declaration, except that the return type is not used. A semicolon terminates the call. Executing the call
statement causes the function to execute; that is, control is transferred to the function, the statement in the
function definition are executed, and then control returns
to the statement following the function call.

Function Definition

Finally, we come to the functions its self, which is referred to as the functions definition, The definition
contains the actual code for the function. Here’s the definition for starline( ) .

3
void starline ( )
{
for ( intj=0, j < 45; j++ )
cout << "*" ;
cout << endl;
}

The definition consists of a line called the decelerator, followed by the function body , The function body is
composed of the statements that make up the function, delimited by braces.

The decelerator must agree with the declaration: It must use the same function name, have the same argument
types in the same order (if there are arguments), and have the same return type.

void main()
{
// Function prototype
<return_type><function_name>([<argu_list>]);

// Function Call
<function_name>([<arguments>]);
}
// Function definition
<return_type><function_name>([<argu_list>]);
{
<function_body>;
}

Program :
/* Program to demonstrate function.
#include <stdio.h>
#include <conio.h>

void add()
{
int a, b, c;
clrscr();
printf("\n Enter Any 2 Numbers : ");
scanf("%d %d",&a,&b);
c = a + b;
printf("\n Addition is : %d",c);
}
void main()
{
void add();
add();
getch();}

Output :
Enter Any 2 Numbers : 23 6
Addition is : 29

4
While calling a function, there are two ways that arguments can be passed to a function:

1. Call by Value
2. Call by Refrence

Q. What is call by value and call by reference? Give examples.

Call by value: In the call by value method, the called function creates a new set of variables and copies
the values of the arguments into them.
Example: Program showing the Call by Value method

void swap(int x, int y)


{
int temp;
temp = x;
x = y;
y = temp;
printf("Swapped values are a = %d and b = %d", x, y);
}

void main()
{
int a = 7, b = 4;
swap(a, b);
printf("Original values are a = %d and b = %d", a, b);
printf("The values after swap are a = %d and b = %d", a, b);
}

Output:
Original Values are a = 7 and b = 4
Swapped values are a = 4 and b = 7

The values after swap are a = 7 and b = 4


This happens because when function swap() is invoked, the values of a and b gets copied onto x and y.
The function actually swaps x and y while the values of the original ariables a and b remain intact.

Call by reference: In the call by reference method, instead of passing values to the function being
called, references/pointers to the original variables are passed.
Example: Program showing the Call by Reference method

void swap(int *x, int *y)


{
int temp;
temp = *x;
*x = *y;
*y = temp;
printf("Swapped values are a = %d and b = %d", *x, *y);
}

5
void main()
{
int a = 7, b = 4;
swap(&a, &b);
printf("Original values are a = %d and b = %d",a,b);
printf("The values after swap are a = %d and b = %d",a,b);
}
Output:
Original Values are a = 7 and b = 4
Swapped values are a = 4 and b = 7

The values after swap are a = 4 and b = 7

This happens because when function swap() is invoked, it creates a reference for the first incoming
integer a in x and the second incoming integer b in y. Hence the values of the original variables are
swapped.

By default, C uses call by value to pass arguments. In general, this means that code within a function cannot
alter the arguments used to call the function and above mentioned example while calling max() function used
the same method.

Q. What is recursion? Write a program to factorial of a given no. using recursion function.

Ans:- RECURSION:-Recursion is the process of repeating items in a self-similar way. Same applies in
programming languages as well where if a programming allows you to call a function inside the same function
that is called recursive call of the function as follows.

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 in infinite
loop.

Recursive function is very useful to solve many mathematical problems like to calculate factorial of a number,
generating Fibonacci series etc.

Number Factorial
Following is an example which calculate factorial for a given number using a recursive function:
#include <stdio.h>
int factorial(unsigned int i)
{
if(i <= 1)
{

6
return 1;
}
return i * factorial(i - 1);
}

int main()
{
int i = 15;
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 15 is 2004310016

Fibonacci Series

Following is another example which generates fibonacci series for a given number using a recursive function:

#include <stdio.h>

int fibonaci(int i)
{
if(i == 0)
{
return 0;
}
if(i == 1)
{
return 1;
}
return fibonaci(i-1) + fibonaci(i-2);
}

int main()
{
int i;
for (i = 0; i < 10; i++)
{
printf("%d\t%n", fibonaci(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

7
Sorting
Sorting is a process of ordering individual elements of a list according to their proper rank, either in ascending or
descending order. We can easily sort a list of elements by means of iteration /loop and ifif-condition
condition check
statements. Sorting algorithms can be implemented by any programming languages. One outer loop and one inner
loop inside the outer loop will do the purpose.

Bubble sort definition


Bubble sort compares the value of current node with the immediate next node and swaps according to the
requirement and goes till the last element.

Compare and swapping two elements like small soap bubbles and hence the name given as bubble sort.
/*C Program To Sort data in ascending order using bubble sort.*/

#include <stdio.h>

int main()

int data[100],i,n,j,temp;

printf("Enter
"Enter the number of elements to be sorted: "");

scanf("%d",&n);

for(i=0;i<n;++i)

printf("%d. Enter element: ",i+1);

scanf("%d",&data[i]);

for(i=0;i<n-1;++i)

8
for(j=0;j<n-i-1;++j)

if(data[j]>data[j+1]) /* To sort in descending order, change > to < in this line. */

temp=data[j];

data[j]=data[ji+1];

data[j+1]=temp;

printf("In ascending order: ");

for(i=0;i<n;++i)

printf("%d ",data[i]);

return 0;

Enter the number of elements to be sorted: 6

1. Enter element: 12

2. Enter element: 3

3. Enter element: 0

4. Enter element: -3

5. Enter element: 1

6. Enter element: -9

In ascending order: -9 -3 0 1 3 13

insertion sort is based on the idea that one element from the input elements is consumed in each
iteration to find its correct position i.e, the position to which it belongs in a sorted array.

It iterates the input elements by growing the sorted array at each iteration. It compares the current element
with the largest value in the sorted array. If the current element is greater, then it leaves the element in its
place and moves on to the next element else it finds its correct position in the sorted array and moves it to
that position. This is done by shifting all the elements, which are larger than the current element, in the sorted
array to one position ahead

9
Algorithm for Insertion Sort in C
Let ARR is an array with N elements
1. Read ARR
2. Repeat step 3 to 8 for I=1 to N-1
3. Set Temp=ARR[I]
4. Set J=I-1
5. Repeat step 6 and 7 while Temp<ARR[J] AND J>=0
6. Set ARR[J+1]=ARR[J] [Moves element forward]
7. Set J=J-1
[End of step 5 inner
loop]
8. Set ARR[J+1]=Temp [Insert element in proper place]
[End of step 2 outer
loop]
9. Exit

//PROGRAM

#include<stdio.h>
int main()
{
int i,j,n,temp,a[30];
printf("Enter the number of elements:");
scanf("%d",&n);
printf("\nEnter the elements\n");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
for(i=1;i<=n-1;i++)
{
temp=a[i];
j=i-1;
while((temp<a[j])&&(j>=0))
{
a[j+1]=a[j]; //moves element forward
j=j-1;
}
a[j+1]=temp; //insert element in proper place
}
printf("\nSorted list is as follows\n");
for(i=0;i<n;i++)
{
printf("%d ",a[i]);
}
return 0;

10
}

Selection sort in C:
C program for selection sort to sort numbers. This code implements selection sort algorithm to arrange
numbers of an array in ascending order. With a little modification, it will arrange numbers in descending
order.

Selection sort algorithm implementation in C

#include <stdio.h>
int main()
{
int array[100], n, c, d, position, swap;

printf("Enter number of elements\n");


scanf("%d", &n);

printf("Enter %d integers\n", n);

for (c = 0; c < n; c++)


scanf("%d", &array[c]);

for (c = 0; c < (n - 1); c++)


{
position = c;

for (d = c + 1; d < n; d++)


{
if (array[position] > array[d])
position = d;
}
if (position != c)
{
swap = array[c];
array[c] = array[position];
array[position] = swap;
}
}

printf("Sorted list in ascending order:\n");

for (c = 0; c < n; c++)


printf("%d\n", array[c]);

return 0;
}

11
program to find roots of a quadratic equation
C program to find roots of a quadratic equation: This program calculates roots of a quadratic equation. Coefficients are assumed
to be integers, but roots may not be real. Discriminant (b*b-4*a*c) decides the nature of roots. In the program, j stands for iota.

C programming code
#include <stdio.h>
#include <math.h>

int main()
{
int a, b, c, d;
double root1, root2;
printf("Enter a, b and c where a*x*x + b*x + c = 0\n");
scanf("%d%d%d", &a, &b, &c);

d = b*b - 4*a*c;

if (d < 0) { //complex roots


printf("First root = %.2lf + j%.2lf\n", -b/(double)(2*a), sqrt(-d)/(2*a));
printf("Second root = %.2lf - j%.2lf\n", -b/(double)(2*a), sqrt(-d)/(2*a));
}
else { //real roots
root1 = (-b + sqrt(d))/(2*a);
root2 = (-b - sqrt(d))/(2*a);

printf("First root = %.2lf\n", root1);


printf("Second root = %.2lf\n", root2);
}

return 0;
}

Linear search C program


#include <stdio.h>

int main()
{
int array[100], search, c, n;

printf("Enter number of elements in array\n");


scanf("%d", &n);

printf("Enter %d integer(s)\n", n);

for (c = 0; c < n; c++)


scanf("%d", &array[c]);

printf("Enter a number to search\n");

12
scanf("%d", &search);

for (c = 0; c < n; c++)


{
if (array[c] == search) /* If required element is found */
{
printf("%d is present at location %d.\n", search, c+1);
break;
}
}
if (c == n)
printf("%d isn't present in the array.\n", search);

return 0;
}

13

You might also like