Sei sulla pagina 1di 22

A Manual of Lab Programming: C Programming Lab Cycle I& II

Amruta Institute of Engineering & Management Sciences


Near Toyota Kirloskar, Off Mysore Rd, Bidadi-562 109

Department of Computer Science and Engineering
Department of Information Sciences and Engineering
Computer Prog ramming Laborator y
I Year BE, All Branches
Lab Manual – Cycle I & II

Unversity Seat No. :


Name of the Student :
Branch :
Semester :
Section :

Prepared and Programmed


by
Mahesh Lohith K.S
Aravinda C.V

Amruta Institute of Engineering & Management Sciences, Bangalore-562 109 1


A Manual of Lab Programming: C Programming Lab Cycle I& II

Contents

Cycle : 1
1)Solving Quadratic Equation for roots

2)GCD and LCM of two numbers using Euclid's algorithm

3)Reversing number to check for Palindrome

4)Evaluating polynomial using Horner's rule

5)Replacing blanks in a string with a single blank

6)Binary Search

7)Bubble Sort

8)Word Length of the Host Machine

Cycle : 2
1)Tylor series and exponential value of 0.5

2)Matrix Multiplication

3)Parallel program to add elemments of two arrays

4)Rotating integers to right by n places

5)Program with function to check for prime

6)Parallel program for generating primes using Sieve-

Eratosthenes method

7)Reversing strings

8)First occurance of any char of string2 in string1

Amruta Institute of Engineering & Management Sciences, Bangalore-562 109 2


A Manual of Lab Programming: C Programming Lab Cycle I& II

Program 1:
/*Design, develop and execute a program in C to find and output
all the roots of a given quadratic equation, for non-zero
coefficients.*/
/*compile this program using the command gcc quadratic.c -lm*/

#include <stdio.h>
#include <math.h>
void main()
{
float a,b,c,disc,x1,x2,realpart,imagpart;
system("clear");
printf("Enter the Co-efficients of the Quadratic Equation: ");
scanf("%f%f%f",&a,&b,&c);
//a has to be a non-zero value//
if((a*b*c)==0)
printf("\n The input co-efficients does not form a Perfect
Quadratic Equation\n");
else
{
disc=b*b-4*a*c;
/*if disc is zero the roots are equal*/
if (disc==0)
printf("\nThe equal roots are x1=%4.2f and x2=%4.2f\n",-b/
(2*a),-b/(2*a));
else if (disc > 0)
{
/*if the disc is greater than 0 the roots are real*/
x1 = (-b + sqrt(disc))/(2*a);
x2 = (-b - sqrt(disc))/(2*a);
printf("\nthe Real roots are x1=%4.2f and x2=%4.2f\n"
,x1,x2);
}
else if (disc < 0)
{
/*if the disc is less than 0 the roots are imaginary*/
printf("\nThe roots are imaginary\n");
realpart = -b/(2*a);
imagpart = sqrt(fabs(disc))/(2*a);
printf("\nThe roots are x1=%4.2f+i%4.2f and x2=%4.2f-i
%4.2f \n", realpart,imagpart,realpart,imagpart);
}
}
}

Amruta Institute of Engineering & Management Sciences, Bangalore-562 109 3


A Manual of Lab Programming: C Programming Lab Cycle I& II

Program: 2

/*Design, develop and execute a program in C to implement Euclid’ s


algorithm to find the GCD and LCM of two integers and to output
the results along with the given integers.*/

#include<stdio.h>
int gcd_rec(int,int);
void main()
{
int firstno,secondno,gcd;
system("clear");
printf("Enter the two no.s to find GCD and LCM:");
scanf("%d%d",&firstno,&secondno);
if(firstno*secondno!=0)
{
gcd=gcd_rec(firstno,secondno);
printf("\nThe GCD of %d and %d is %d\n",firstno,secondno,gcd);
printf("\nThe LCM of %d and %d is %d\n",firstno,secondno,
(firstno*secondno)/gcd);
}
else
printf("One of the enterd no. is zero:Quitting\n");
}

/*Function for Euclid's Procedure*/


int gcd_rec(int x, int y)
{
if (y == 0)
return x;
return gcd_rec(y, x % y);
}

Amruta Institute of Engineering & Management Sciences, Bangalore-562 109 4


A Manual of Lab Programming: C Programming Lab Cycle I& II

Program: 3

/*Design, develop and execute a program in C to reverse a given


four digit integer number and check whether it is a palindrome or
not. Output the given number with suitable message.*/

#include<stdio.h>
void main()
{
long int num,revnum=0,rem,quo;
system("clear");
printf("Enter a no. to reverse:");
scanf("%ld",&num);
quo=num;
if(num!=0)
{
while (quo > 0)
{
rem = quo % 10;/*finding the reminder*/
quo = quo / 10;/*finding the quotient*/
revnum =revnum*10 + rem;/*reversing in steps*/
}
printf("\nThe reverse of no. %ld is %ld\n",num,revnum);
if(num==revnum)
printf("\nThe no. %ld is a Palindrome\n",num);
else
printf("\nThe no. %ld is not a Palindrome\n",num);
}
else
printf("\nThe entered number is 0: Quitting\n");
}

Amruta Institute of Engineering & Management Sciences, Bangalore-562 109 5


A Manual of Lab Programming: C Programming Lab Cycle I& II

Program: 4

/*Design, develop and execute a program in C to evaluate the given


polynomial f(x) = a4x4 + a3x3 + a2x2 + a1x1+ a0 for given value of x
and the coefficients using Horner’ s method.*/

#include <stdio.h>

//prototype declaration
double horner_rule(float *, int , float);

//Main function where the co-efficients are read and the function
horner's rule is called*/
int main()
{
int array_len=5;
float co_effs[array_len];
int counter;
float x;
system("clear");
printf("Enter the Co-efficients of a 4th degree polynomial:");
for(counter=0;counter<array_len;++counter)
{
scanf("%f",&co_effs[counter]);
}
printf("Enter the value of x:");
scanf("%f",&x);
printf("%5.1lf\n", horner_rule(co_effs, counter,x));
return 0;
}

//function to apply horner's rule


double horner_rule(float *co_effs, int s, float x)
{
int i;
double res = 0.0;

for(i=s-1; i>=0; i--)


{
res = res * x + co_effs[i];
}
return res;
}

Amruta Institute of Engineering & Management Sciences, Bangalore-562 109 6


A Manual of Lab Programming: C Programming Lab Cycle I& II

Program: 5

/*Design, develop and execute a program in C to copy its input to


its output,replacing each string of one or more blanks by a single
blank*/

#include<stdio.h>
void main()
{
char string[' '];
int i=0,flag=0;
system("clear");
printf("Enter the string to be copied to the output:");
gets(string);
system("clear");
printf("\nThe entered string is:%s\n",string);
while(string[i] != '\0')
{

if(string[i]==' ')
flag=flag+1;
else
flag=0;
if(flag<=1)
printf("%c",string[i]);
++i;
}
printf("\n");
}

Amruta Institute of Engineering & Management Sciences, Bangalore-562 109 7


A Manual of Lab Programming: C Programming Lab Cycle I& II

Program: 6
/*Design, develop and execute a program in C to input N integer
numbers in ascending order into a single dimensional array and
perform a binary search for a given key integer number and report
success or failure in the form of a suitable message.*/
#include<stdio.h>
void main()
{
int array_len,i,mid,low,high,ser_no,flag=0;
int no_array[20];
system("clear");
printf("Enter the width of array : ");
scanf("%d",&array_len);
printf("\nEnter %d sorted elemens: ",array_len);
for(i=0;i<array_len;++i)
scanf("%d",&no_array[i]);
printf("\nEntered %d elements are:",array_len);
for(i=0;i<array_len;++i)
printf("%d ",no_array[i]);
/*bin search part*/
printf("\n\nEnter the No. to be searched:");
scanf("%d",&ser_no);
low =0;
high = array_len-1;
mid=(low+high)/2;
while(low<= high)
{

if (no_array[mid]==ser_no)
{
flag=1;
break;
}
else
if(no_array[mid]>=ser_no)
high = mid-1;
else
low = mid+1;
mid = (low + high)/2;
}
if(flag==0)
printf("\nThe no. %d not found\n",ser_no);
else
printf("\nThe no. %d found at location %d\n",ser_no,mid+1);
}

Amruta Institute of Engineering & Management Sciences, Bangalore-562 109 8


A Manual of Lab Programming: C Programming Lab Cycle I& II

Program: 7
/*Design, develop and execute a program in C to input N integer
numbers into a single dimensional array, sort them in ascending
order using bubble sort technique and print both the given array
and the sorted array with suitable headings*/

#include<stdio.h>
void swap(int [], int, int);
void main()
{
int a[100],n,i,j,temp;
system("clear");
printf("Enter the width of the array of numbers:");
scanf("%d",&n);
//reading the nos. to be sorted//
printf("\nEnter %d Nos to sort: ",n);
for(i=0;i<n;++i)
scanf("%d",&a[i]);
system("clear");
printf("\nEntered %d Nos are:",n);
for(i=0;i<n;++i)
printf("%d ",a[i]);
//sorting//
for(i=1;i<n;i++)
for(j=0;j<n-i;j++)
if(a[j] > a[j+1])
{
swap(a[],j,j+1);
}

//printing the sorted nos.//


printf("\nThe nos after sorting:");
for(i=0;i<n;++i)
printf("%d ",a[i]);
printf("\n");
}

void swap(int b[], int i, int j)


{
int temp;
temp=b[i];
b[i]=b[j];
b[j]=temp;
}

Amruta Institute of Engineering & Management Sciences, Bangalore-562 109 9


A Manual of Lab Programming: C Programming Lab Cycle I& II

Program: 8

/*Design, develop and execute a program in C to compute and print


the word length on the host machine.*/

#include<stdio.h>
void main()
{
int count=0;
int unsigned word;
/*All bits of the word are set to one by taking one's
complement of zero*/
word=~0;
system("clear");
/*Counting Word Length using bitwise shift operator*/
while(word!=0)
{
word=word<<1;
++count;
}
printf("\nThe length of the word on the host machine is:
%d\n",count);

Amruta Institute of Engineering & Management Sciences, Bangalore-562 109


10
A Manual of Lab Programming: C Programming Lab Cycle I& II

Program: 9
/*Design, develop and execute a program in C to calculate the
approximate value of exp(0.5) using the Taylor Series expansion
for the exponential function. Use the terms in the expansion until
the last term is less than the machine epsilon defined FLT_EPSILON
in the header file <float.h>. Also print the value returned by the
Mathematical function exp( ).*/

//Macro Definitions//
#include<stdio.h>
#include<math.h>
#include<float.h>

/Function Prototypes//
double power(float, int);
double exponential(void);
long int factorial(int);

void main()

{
system("clear");
printf("The value of FLT_EPSILON from float.h is \
%0.9lf\n",FLT_EPSILON);
printf("The exponential value of 0.5 using Tylor Series is
%0.9lf\n",exponential());
printf("The exponetial value of 0.5 using function exp() from
math.h is %0.9lf\n",exp(0.5));
}

//function to calculate the integer power of a real number


double power(float x, int pow)
{
float prod=1;
int i;
for(i=1;i<=pow;++i)
prod=prod*x;
return(prod);
}

Amruta Institute of Engineering & Management Sciences, Bangalore-562 109


11
A Manual of Lab Programming: C Programming Lab Cycle I& II

//function for tylor series


double exponential(void)
{
double expovalue,sum=1,prevterm;
int pow=1;
while((fabs(sum)-fabs(prevterm)) > FLT_EPSILON)
{
prevterm=sum;
sum = sum + power(0.5,pow)/factorial(pow);
pow = pow + 1;
}
return(sum);
}

//function to calculate the factorial of a number

long int factorial(int number)


{
if(number == 1)
return(1);
else
return(number*factorial(number-1));
}

Amruta Institute of Engineering & Management Sciences, Bangalore-562 109


12
A Manual of Lab Programming: C Programming Lab Cycle I& II

Program : 10
/*Design, develop and execute a program in C to read two matrices
A (M x N) and B (P x Q) and compute the product of A and B if the
matrices are compatible for multiplication. The program must print
the input matrices and the resultant matrix with suitable headings
and format if the matrices are compatible for multiplication,
otherwise the program must print a suitable message. (For the
purpose of demonstration, the array sizes M, N, P, and Q can all
be less than or equal to 3)*/

#include<stdio.h>
/* Declaration of function prototypes*/
void readmat(int [][10], int, int);
void writemat(int [][10],int, int);
void matmul(int [][10], int [][10],int [][10],int,int,int);

void main()
{
int mat1[' '][10],mat2[' '][10],resultmat[' '][10],row1,col1,
row2, col2;
printf("Enter the No. of Rows and No. of Columns of Matrces 1
and 2:");
scanf("%d%d%d%d",&row1,&col1,&row2,&col2);
if( col1!=row2)
printf("\nThe two matrices cannot be multiplied:\n");
else
{
printf("Enter the %d elements of first matrix:",row1*col1);
readmat(mat1,row1,col1);
printf("Enter the %d elements of second matrix:",row2,col2);
readmat(mat2,row2,col2);
matmul(mat1,mat2,resultmat,row1,col2,row2);
system("clear");
printf("\nThe elements of the first matrix are:\n");
writemat(mat1,row1,col1);
printf("\nThe elements of the second matrix are:\n");
writemat(mat2,row2,col2);
printf("\nThe elements of the resultant matrix are:\n");
writemat(resultmat,row1,col2);
printf("\n");
}
}

Amruta Institute of Engineering & Management Sciences, Bangalore-562 109


13
A Manual of Lab Programming: C Programming Lab Cycle I& II

/*Function for reading a matrix*/


void readmat (int a[][10], int row, int col)
{
int count1,count2;
for(count1=0;count1<row;++count1)
for(count2=0;count2<col;++count2)
scanf("%d",&a[count1][count2]);
}

/*Function for writing a matrix*/


void writemat (int a[][10], int row, int col)
{
int count1,count2;
for(count1=0;count1<row;++count1)
{
for(count2=0;count2<col;++count2)
printf("%d ",a[count1][count2]);
printf("\n");
}
}

/*Function for Multiplying two matrices*/


void matmul(int a[][10], int b[][10], int c[][10],int row1, int
col2, int common)
{
int count1,count2,count3,sum;
for(count1=0;count1<row1;++count1)
for(count2=0;count2<col2;++count2)
{
sum=0;
for(count3=0;count3<common;++count3)
sum=sum+a[count1][count3]*b[count3][count2];
c[count1][count2]=sum;
}
}

Amruta Institute of Engineering & Management Sciences, Bangalore-562 109


14
A Manual of Lab Programming: C Programming Lab Cycle I& II

Program : 11
/* Design, develop and execute a parallel program in C to
add, elementwise,two one-dimensional arrays A and B of N
integer elements and storethe result in another one-
dimensional array C of N integer elements.*/
/*Compile this program with gcc -fopenmp filename*/

#include<stdio.h>
void main()
{
intfirstarray[100],secondarray[100],resultarray[100],width, count;
int chunk = 5,trdid;//trdid is for thread id//
system("clear");
printf("Enter the width of the two arrays: ");
scanf("%d",&width);
printf("Enter %d elements of first array: ",width);
for(count=0;count<width;++count)
scanf("%d",&firstarray[count]);
printf("Enter %d elements of second array: ",width);
for(count=0;count<width;++count)
scanf("%d",&secondarray[count]);
system("clear");
printf("The %d elements of first array are: ",width);
for(count=0;count<width;++count)
printf("%d ",firstarray[count]);
printf("\nThe %d elements of second array are: ",width);
for(count=0;count<width;++count)
printf("%d ",secondarray[count]);
#pragma omp parallel
{
#pragma omp for schedule(dynamic,chunk)
for(count=0;count<width;++count)
{
trdid=omp_get_thread_num();
resultarray[count]=firstarray[count] + secondarray[count];
printf("element:%d Thread ID:%d\n",resultarray[count],trdid);
}
}

printf("\nThe %d elements of result array are: ",width);


for(count=0;count<width;++count)
printf("%d ",resultarray[count]);
printf("\n");
}
Amruta Institute of Engineering & Management Sciences, Bangalore-562 109
15
A Manual of Lab Programming: C Programming Lab Cycle I& II

Program : 12

/*Design and develop a function rightrot (x, n) in C that returns


the value of the integer x rotated to the right by n bit
positions as an unsigned integer. Invoke the function from the
main with different values for x and n and print the results with
suitable headings.*/

#include<stdio.h>

int rightrot(unsigned int, int);

void main()
{
unsigned int num;
int places,shiftnum;
system("clear");
printf("Enter a number to rotate right: ");
scanf("%d",&num);
printf("\nEnter the number of places to be shifted thru: ");
scanf("%d",&places);
shiftnum=rightrot(num,places);
printf("\nThe no. %d after rotating thru %d plces is %d",num,
places,shiftnum);
printf("\n");
}

int rightrot(unsigned int passnum, int passplaces)


{
int i;
for(i=1;i<=passplaces;++i)
if(passnum%2==0)
passnum=passnum>>1;
else
{
passnum=passnum>>1;
passnum=passnum + 32768;
}
return(passnum);
}

Amruta Institute of Engineering & Management Sciences, Bangalore-562 109


16
A Manual of Lab Programming: C Programming Lab Cycle I& II

Program : 13
/*Design and develop a function isprime (x) that accepts an
integer argument and returns 1 if the argument is prime and 0
otherwise. The function must use plain division checking approach
to determine if a given number is prime. Invoke this function from
the main with different values obtained from the user and print
appropriate messages.*/
/*Compile this program using command gcc -lm filename*/

#include<stdio.h>
#include<math.h>

int isprime(int);

main()
{
int prime[10];
int noele,ret_val,count,primeno;
system("clear");
//input the no. of elements to be read
printf("Enter the no. of elements to Check for prime: ");
scanf("%d",&noele);
//read the elements
printf("Enter %d elements to check whether they are prime:
",noele);
for(count=0;count < noele;++count)
scanf("%d",&prime[count]);
system("clear");
//writing the elements to be checked whether they are prime.
printf("The entered elements are: ");
for(count=0;count < noele;++count)
printf("%d ",prime[count]);
printf("\n");
//to check whether the elements are prime or not
for(count=0;count < noele;++count)
{
ret_val=isprime(prime[count]);
if (ret_val==1)
printf("The number %d is a prime no.\n",prime[count]);
else
printf("The number %d is not a prime no.\n",prime[count]);
}

Amruta Institute of Engineering & Management Sciences, Bangalore-562 109


17
A Manual of Lab Programming: C Programming Lab Cycle I& II

//Function to check whether the no. is prime


int isprime(int p)
{
int count,flag=1;
for(count=2;count<=sqrt(p);count++)
{
if((p%count)==0)
{
flag=0;
break;
}
}
return(flag);
}

Amruta Institute of Engineering & Management Sciences, Bangalore-562 109


18
A Manual of Lab Programming: C Programming Lab Cycle I& II

Program : 14

/*Design, develop and execute a parallel program in C to determine


and print the prime numbers which are less than 100 making use of
algorithm of the Sieve of Eratosthenes*/
/*Compile this program using gcc -fopenmp -lm filename*/

#include<stdio.h>
#include<math.h>
#include<omp.h>

main()
{
int i,j,prime[101],range;
system("clear");
printf("Enter the Range of elements to search for primes:");
scanf("%d",&range);
for(i=1;i<=range;++i)
prime[i]=1;
printf("\n");
for(i=2;i<=sqrt(range);i++)
if (prime[i]!=0)
{
#pragma omp parallel for
for (j=i*i;j<=range;j+=i)
prime[j]=0;
}
system("clear");
printf("The prime nos up to %d are: ",range);
for(i=2;i<range;++i)
if (prime[i])
printf("%d ",i);
printf("\n");

Amruta Institute of Engineering & Management Sciences, Bangalore-562 109


19
A Manual of Lab Programming: C Programming Lab Cycle I& II

Program : 15
/*Design and develop a function reverses (s) in C to reverse the
string s in place. Invoke this function from the main for
different strings and print the original and reversed strings.*/

#include<stdio.h>

void reverse(char *word);


int lenstr(char *word);
void swap(char *word,int lbound,int rbound);'

void main(int argc,char *argv[])


{
char *word;
int count=1;
system("clear");
while(count < argc)
{
word =argv[count];
printf("The entered string is %s\n",word);
reverse(word);
printf("The string after reversing is %s\n",word);
++count;
}
}

//function to reverse the word


void reverse(char *word)
{
int count;
for (count = 0; count<=(lenstr(word)/2)-1; ++count)
{
swap(word,count,(lenstr(word)-count-1));
}
}

//function to count the length of the word


int lenstr(char * word)
{
int count;
for(count = 0; word[count]!='\0';count++);
return(count);
}

Amruta Institute of Engineering & Management Sciences, Bangalore-562 109


20
A Manual of Lab Programming: C Programming Lab Cycle I& II

//function to swap the contents two character locations


void swap(char *word,int lbound, int rbound)
{
char temp;
temp=word[lbound];
word[lbound]=word[rbound];
word[rbound]=temp;
}

Amruta Institute of Engineering & Management Sciences, Bangalore-562 109


21
A Manual of Lab Programming: C Programming Lab Cycle I& II

Program : 16
/*Design and develop a function match any (s1,s2) which returns
the first location in the string s1 where any character from the
string s2 occurs, or – 1 if s1 contains no character from s2. Do
not use the standard library function which does a similar job!
Invoke the function match any (s1. s2) from the main for different
strings and print both the strings and the return value from the
function match any (s1,s2).*/
#include<stdio.h>
int matchany(char [], char []);
void main()
{
char firstr[' '],secstr[' '];
int place,placecount=-1;
system("clear");
printf("Enter the first string: ");
scanf("%s",firstr);
printf("Enter the second string: ");
scanf("%s",secstr);
place=matchany(firstr,secstr);
if(place==-1)
printf("Any character of \'%s\' is not found in any place
in\'%s\'\n",secstr,firstr);
else
printf("The first occurance of any character of \'%s\' in \'%s\'
is in place %d\n",secstr,firstr,place);
}

int matchany(char firstr[],char secstr[])


{
int flag=100,count1,count2,placecount=-1;
for(count1=0;firstr[count1]!='\0';++count1)
for(count2=0;secstr[count2]!='\0';++count2)
if(secstr[count2]==firstr[count1])
{
if(flag > count1)
flag=count1+1;
placecount++;
}
if (placecount==-1)
return placecount;
else
return flag;
}

Amruta Institute of Engineering & Management Sciences, Bangalore-562 109


22

Potrebbero piacerti anche