0% found this document useful (0 votes)
4 views58 pages

Module 3

The document provides various C programming examples for algorithm development, including methods for calculating square roots, finding the smallest divisor of an integer, and determining the greatest common divisor (GCD) using the Euclidean algorithm. It also covers generating prime factors using the Sieve of Eratosthenes, creating pseudo-random numbers with a linear congruential method, and manipulating arrays through sorting, reversing, and removing duplicates. Additionally, it includes algorithms for partitioning arrays based on user-defined criteria.

Uploaded by

gowtham sam
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)
4 views58 pages

Module 3

The document provides various C programming examples for algorithm development, including methods for calculating square roots, finding the smallest divisor of an integer, and determining the greatest common divisor (GCD) using the Euclidean algorithm. It also covers generating prime factors using the Sieve of Eratosthenes, creating pseudo-random numbers with a linear congruential method, and manipulating arrays through sorting, reversing, and removing duplicates. Additionally, it includes algorithms for partitioning arrays based on user-defined criteria.

Uploaded by

gowtham sam
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/ 58

Algorithm Development:

Let us take specific examples, That is:

Suppose for example we do not know the square root of 36. If we guess 9 as
the square root of 36, it is too high because 9X9 =81 as per the equation
(1).Since our guess of 9 is too high, so we may try with 8. There 8x8 =64
which is still higher than 36 but better than our initial guess of 9.
The calculated above value 6.0152 =36.6025 which is only slightly greater than
the square value 36 that we are seeking. However, we shall assume this is a
good strategy and continue with the development of the algorithm.
Condition for terminating the loop:
As observed we know that the successive iterations produces, closer and
closer approximations to the square root.
or perhaps m/2 as our initial guess.

C Program to calculate square root by guessing and averaging


method:

#include <stdio.h>
#define ACCURACY 0.001 // tolerance : you can set by yourself according to
requirement

int main()
{
float number,guess,square_root;
printf("Enter a number to find square root of it:\n");
scanf("%f",&number);// storing the number
guess=number/2;// initializing guess number
while((guess*guess - number) > ACCURACY)
//loop runs until the square root is found
{
guess = (guess + number/guess )/2;// updating the guess number
}
square_root = guess;//assigning the value of guess number to square root.
printf("square root of %.2f = %.4f",number,square_root);//final answer
}
For example,

Divisors of 305 = {5, 7, 35, 61, 305, 427, 2135}


Smallest Divisor = 5

Divisors of 49 = {7, 49}


Smallest Divisor = 7
C Program to Find Smallest Divisor of an
Integer

#include <stdio.h>
#include<conio.h>
int smallestDivisor(int n);
void main()
{
int n;
printf("Enter the number whose smallest divisor needs to be calculated\n");
scanf("%d",&n);
int result=smallestDivisor(n);
printf("Smallest Divisor of %d is %d\n",n,result);
getch();
}
// Function to find the smallest divisor
int smallestDivisor(int n)
{
// if divisible by 2
if (n % 2 == 0)
return 2;

// iterate from 3 to square number limit of n


for (int i = 3; i * i <= n; i += 2)
{
if (n % i == 0)
return i;
}
return 1; //if not divisible by any of even or odd factors eg: 139
}

Output:
Case 1: Number is even

Case 2: Number is odd

Case 3: Number doesn’t have any other smallest divisor except 1


For example, let us take the numbers 18 and 30 whose greatest common divisor
needs to be finded.

This can be represented by segmentation as below:


We observe from the above representation that The Segment AB is common
divisor segment part for both numbers 18 and 36.

From the above representation, thus the problem of finding the GCD of
numbers 18 and 36 can be reduced to the below problem.

Sub Problem 1:
The above sub problem can be further reduced to another sub problem as shown
below.

Sub Problem 2:

By observing the above pattern, we can generalise an algorithm that finds


the greatest common divisor for any given 2 integers as follows:
// C program to demonstrate Basic Euclidean Algorithm for calculating
GCD of two numbers

#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,rem;
clrscr();
printf("enter any two numbers:");
scanf("%d%d",&a,&b);
while(b!=0) //check for b=0 condition because in a/b ,b should not equal to
zero
{
rem=a % b;
a=b;
b=rem;
}
printf("GCD of two numbers is:%d\n",a);
getch();
}
Output:
Algorithm(Sieve of Eratosthenes for generating prime factors of a number)

1. Accept the number whose prime factors need to be calculated.


2. Increment the accepted number by 2.
3. Initialise all elements of the prime array to their respective position numbers.
4. Initialise all even position elements of the prime array to 2.
5. Check the remaining odd positions starting from 3rd position in prime array
with multiples of 3,5,7 and so on ,in order to generate prime factors.
6. While the entered number is not equal to 1 repeatedly do:
6. a. Initialise factor variable to the value at prime[number](obtained from
step 5).
6. b. Print each prime factor
6. c Divide the number by the obtained factor in step 6.a to obtain the new
number for next iteration.

C Program to generate prime factors of a number by Sieve of Eratostenes


method:

#include <stdio.h>

int primes[100001];
void sieveOfEratosthenes(int N)

N+=2; //increment N value by 2.

primes[1] = 1;

for (int i=2; i<=N; i++)

primes[i] = i; //initialising prime number array to the value of i until Nth


position starting from 2.

for (int i=4; i<N; i+=2)

primes[i] = 2; //setting even positions of prime number array =2 or omitting


even numbers

for (int i=3; i*i<N; i++)

if (primes[i] == i)

for (int j=i*i; j<N; j+=i) //incrementing j with 3 to check prime number
array positions at multiples of 3 everytime

if (primes[j]==j)

primes[j] = i; //generating prime factors

}//end of function

int findPrimeFactors(int num)

sieveOfEratosthenes(num);

int factor;
while(num != 1)

factor = primes[num];

printf("Factor is %d and \n", factor);

num /= factor;

return num;

void main()

int n, c=0;

printf("Enter the value of n\n");

scanf("%d",&n);

c=findPrimeFactors(n);

printf("%d",c);

getch();

Output:
Pseudo Random Number Generator
(PRNG) by linear congruential method.

There are many methods for generating pseudo random numbers,one such
method is linear congruential method.
generated before the sequence begins to repeat.

Example:

m=4096, b=853,a=109;

Pseudo Random Numbers, that is ,Sequence of x(i.e x0,x1,x2…x(m-1) is


calculated by linear congruential method as follows:

Every pseudo random number of x sequence(i.e x0,x1,x2…x(m-1) generated


will be in the range 0 to m-1.

This is done by applying the linear-congruential formula , x= ax+b mod m

C program to generate pseudo-random number

#include<stdio.h>

#include<conio.h>

// m=4096, a=109,b=853

//a-multiplier b-increment m-modulus


void main()

long int m,a,b,i=0,f=0;

printf("Enter the values for m , a and b\n");

scanf("%d%d%d",&m,&a,&b);

while(i<=(m-1))

f=((a*f+b)% m);

printf("Pseudo Random number %d is %ld \n",i+1,f);

i=i+1;

getch();

Output:

Inputs: m=4096, a=109,b=853


And so on until (m-1)th number that is total 4095 pseudo random numbers
are generated.
C Program to for raising a number to a larger power

#include<stdio.h>

#include<conio.h>

void main()

int x;

int n;

printf("Enter the value of x\n");

scanf("%d",&x);

printf("Enter the value of n\n");

scanf("%d",&n);

int result=power(x,n);

printf("Product of %d raised to %d = %d",x,n,result);

getch();

}
int power(int x,int n)

int product=1;

int psequence=x;

while(n!=0)

if(n % 2==1)

product = product * psequence;

n=n/2;

psequence=psequence*psequence;

return product;

Output:

Array Techniques
Example : Above array stores the marks of 5 students.

Array Order Reversal

Algorithm Development
C program to reverse the elements of an array:
#include<stdio.h>
#include<conio.h>
void main()
{
int a[100], i, j, Size, Temp;
printf("\nPlease Enter the size of an array: ");
scanf("%d",&Size);
printf("Inserting %d elements into the array\n",Size);
for (i = 0; i < Size; i++)
{
scanf("%d", &a[i]);
}

j = Size - 1; // Assigning j to Last array element


i = 0; // Assigning i to first array element

while (i < j)
{
Temp = a[i];
a[i] = a[j];
a[j] = Temp;
i++;
j--;
}

printf("\nResult Reverse array is: ");


for(i = 0;i < Size; i++)
{
printf("%d \t", a[i]);
}

getch();
}

Output:
C Program for array counting or histogramming
#include <stdio.h>
#include<conio.h>
void main()
{
//Initialize array
int arr[] = {100, 20, 80, 30, 21, 25, 78, 99, 100};

//Calculate length of array arr


int length = sizeof(arr)/sizeof(arr[0]);

//Array fr will store frequencies of element


int fr[length];
int visited = -1;

for(int i = 0; i < length; i++)


{
int count = 1;
for(int j = i+1; j < length; j++)
{
if(arr[i] == arr[j])
{
count++;
//To avoid counting same element again
fr[j] = visited;
}
}
if(fr[i] != visited)
fr[i] = count;
}

//Displays the frequency of each element present in array


printf("---------------------\n");
printf(" Element | Frequency\n");
printf("---------------------\n");
for(int i = 0; i < length; i++)
{
if(fr[i] != visited)
{
printf(" %d", arr[i]);
printf(" | ");
printf(" %d\n", fr[i]);
}
}
printf("---------------------\n");
getch();
}
Output:
C program that returns the maximum of all numbers in an array.
#include <stdio.h>
#include<conio.h>
void main()
{
int n;
double arr[100];
printf("Enter the size of array in between (1 to 100): ");
scanf("%d", &n);
for (int i = 0; i < n; ++i)
{
printf("Enter number %d: ", i + 1);
scanf("%d", &arr[i]);
}
// storing the largest number to arr[0]
for (int i = 1; i < n; ++i)
{
if (arr[0] < arr[i])
{
arr[0] = arr[i]; //storing maximum number in the first location of the array
}
}
printf("Largest element = %d", arr[0]);
getch();
}
Output:
C Program to remove duplicate element from an ordered array
#include <stdio.h>
#include <conio.h>
void main ()
{
// declare local variables
int arr[20], i, j, k,temp, size;

printf (" Define the number of elements in an array: ");


scanf (" %d", &size);
printf (" \n Enter %d elements of an array: \n ", size);
// use for loop to enter the elements one by one in an array
for ( i = 0; i < size; i++)
{
scanf (" %d", &arr[i]);
}
for (i = 0; i < size; ++i) //sorting the array
{
for (j = i + 1; j < size; ++j)
{
if (arr[i] > arr[j])
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
printf("Printing ordered array \n");
for (i = 0; i < size; ++i)
printf("%d\t", arr[i]);
// use nested for loop to find the duplicate elements in array
for ( i = 0; i < size; i ++)
{
for ( j = i + 1; j < size; j++)
{
// use if statement to check duplicate element
if ( arr[i] == arr[j])
{
// delete the current position of the duplicate element
for ( k = j; k < size - 1; k++)
{
arr[k] = arr [k + 1];
}
// decrease the size of array after removing duplicate element
size--;
// if the position of the elements is changes, don't increase the index j
j--;
}
}
}
/* display an array after deletion or removing of the duplicate elements */
printf ("\n Ordered Array contents after deletion of the duplicate elements:
");
// for loop to print the array
for ( i = 0; i < size; i++)
{
printf (" %d \t", arr[i]);
}
getch();
}

Output:
Write a C Program that partitions the given elements of an array
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,p,a[50],n,x,temp;
printf("Enter size of the array\n");
scanf("%d",&n);
printf("Entering the %d elements of the array\n",n);
for(i=0;i<n;i++)
{
printf("Enter element %d \n",i+1);
scanf("%d",&a[i]);
}
printf("Entered elements are\n");
for(i=0;i<n;i++)
{
printf("%d\t",a[i]);
}
printf("\n");
printf("Enter the element of array for partitioning\n");
scanf("%d",&x);
i=0;
j=n-1;
while(a[i]<=x)
i=i+1;
while(a[j]>x)
j=j-1;
if(a[j]>x)
j=j-1;
while(n>0 && i<=j)
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
i=i+1;
j=j-1;
while(a[i]<=x)
i=i+1;
while(a[j]>x)
j=j-1;
p=j;
}
printf("partitioned position is %d\n",p);
printf(" Array after partitioning as per given element %d is\n",x);
for(i=0;i<n;i++)
printf("%d\t",a[i]);
getch();
}

Output:
C Program to partition the array as per kth smallest entered element:
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,l,u,a[50],n,x,k,temp;
printf("Enter size of the array\n");
scanf("%d",&n);
printf("Entering the %d elements of the array\n",n);
for(i=0;i<n;i++)
{
printf("Enter element %d \n",i);
scanf("%d",&a[i]);
}
printf("Entered elements are\n");
for(i=0;i<n;i++)
{
printf("%d\t",a[i]);
}
printf("\n");
printf("Enter position for kth smallest element\n");
scanf("%d",&k);
l=0;
u=n-1;
while(n>0 && l<u)
{
i=l;
j=u;
x=a[k];
while(i<=k && j>=k)
{
while(a[i]<x)
i=i+1;
while(x<a[j])
j=j-1;
temp=a[i];
a[i]=a[j];
a[j]=temp;
i=i+1;
j=j-1;
}
if(j<k)
l=i;
if(i>k)
u=j;
}
printf(" Array after partitioning as per %d th smallest element\n",k);
for(i=0;i<n;i++)
printf("%d\t",a[i]);
printf("\n");
printf(" The %d th smallest element in the partitioned array is %d \n",k,x);
getch();
}

Output:
Multiplication of Matrices
To multiply 2 matrices, we are taking input from the user for row number, column number,
first matrix elements and second matrix elements. Then we are performing multiplication on
the matrices entered by the user.

In matrix multiplication first matrix first row elements are multiplied by all column
elements of second matrix. Similarly, second row elements of first matrix are multipled by
all column elements of second matrix and so on.

Let's try to understand the matrix multiplication of 2*2 and 2*3 matrices by the figure given
below:

C Program to multiply 2 matrices:


#include <stdio.h>
#include<stdio.h>
void main()
{
int m, n, p, q, c, d, k, sum = 0;
int first[10][10], second[10][10], multiply[10][10];
printf("Enter the number of rows and columns of first matrix\n");
scanf("%d%d", &m, &n);
printf("Enter the elements of first matrix\n");
for ( c = 0 ; c < m ; c++ )
{
for ( d = 0 ; d < n ; d++ )
{
scanf("%d", &first[c][d]);
}
}
printf("Enter the number of rows and columns of second matrix\n");
scanf("%d%d", &p, &q);
if ( n != p )
printf("Matrices with entered orders can't be multiplied with each
other.\n");
else
{
printf("Enter the elements of second matrix\n");
for ( c = 0 ; c < p ; c++ )
{
for ( d = 0 ; d < q ; d++ )
{
scanf("%d", &second[c][d]);
}
}
for ( c = 0 ; c < m ; c++ )
{
for ( d = 0 ; d < q ; d++ )
{
for ( k = 0 ; k < p ; k++ )
{
sum = sum + first[c][k]*second[k][d];
}
multiply[c][d] = sum;
sum = 0;
}
}
printf("Product of entered matrices:-\n");
for ( c = 0 ; c < m ; c++ )
{
for ( d = 0 ; d < q ; d++ )
{
printf("%d\t", multiply[c][d]);
}
printf("\n");
}
}//end of else
getch();
}
Output:

You might also like