Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
16 views

C Programming Lab1

Uploaded by

ramgmail
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

C Programming Lab1

Uploaded by

ramgmail
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

C PROGRAMMING LABORATORY BPOPS103

PRINCIPLES OF PROGRAMMING USING C


LAB MANUAL

Algorithm is a solution to a problem that meets the following criteria.


1. A list of instructions, procedures, or formula that solves a problem.
2. Can be proven.
3. Something that always finishes and works.

Examples of how are algorithms used today


➢ Computers use algorithms to convert data (e.g. converting decimal into binary).
➢ Google search uses the Page Rank algorithm to sort search results.
➢ Encryption to encrypt and decrypt information and keep data safe is an algorithm.
➢ GPS uses algorithms to find the best route to a destination.
➢ There are dozens of sort algorithms that are used to sort data.
➢ Smart phones, Wi-Fi, and wireless communication use algorithms to communicate.
➢ E-mail spam detection uses algorithms to filter out bad e-mails.
➢ Data compression for getting information faster (e.g. YouTube video) use algorithms.

Application
➢ Textbooks and scientific publications related to computer science and numerical
computation
➢ often use pseudo code in description of algorithms, so that all programmers can
understand

Flowchart
A flowchart is a graphical representation of decisions and their results mapped out in individual
shapes. Flowcharts can provide a step-by- step diagram for mapping out complex situations, such
as programming code or troubleshooting problems

1 Dept of CSE,MYCEM
C PROGRAMMING LABORATORY BPOPS103

Steps to be followed to execute the programs in the laboratory:

1. Boot the system with Linux / Fedora operating system.


2. Open the terminal window.
3. At the command prompt give the command gedit <filename.c> and press enter key
and type the c program in the respective editor. <filename.c> is your actual filename with .c
extension.
4. Save the program and come out of the editor window.
5. Next step is to compile the program. To compile issue the command cc <filename.c> and
press enter key. If you have included math.h in your program, issue the command
cc<filename.c> -lm and press enter key.
6. If no errors in the program, the command prompt will be displayed, otherwise the error list
will be displayed on the screen. Edit the program, debug and recompile it till you get the
compilation without
errors.
7. Once the program is compiled without any errors, the program is ready for execution. To
execute the program give the command ./a.out at the command prompt and press enter.
8. Please don’t forget that your c programs and Linux commands are all case sensitive.

Programming Assignments

2 Dept of CSE,MYCEM
C PROGRAMMING LABORATORY BPOPS103

1) Simulation of a Simple Calculator.


2) Compute the roots of a quadratic equation by accepting the coefficients. Print
appropriate messages.
3) An electricity board charges the following rates for the use of electricity: for the first 200
units 80 paise per unit: for the next 100 units 90 paise per unit: beyond 300 units Rs 1 per
unit. All users are charged a minimum of Rs. 100 as meter charge. If the total amount is
more than Rs 400, then an additional surcharge of 15% of total amount is charged. Write a
program to read the name of the user, number of units consumed and print out the charges.
4). Write a C Program to display the following by reading the number of rows as input,

n th row
5) Implement Binary Search on Integers.
6) Implement Matrix multiplication and validate the rules of multiplication.
7) Compute sin(x)/cos(x) using Taylor series approximation. Compare your result with the
built-in library function. Print both the results with appropriate inferences.
8) Sort the given set of N numbers using Bubble sort.
9) Write functions to implement string operations such as compare, concatenate, and find
string length. Use the parameter passing techniques.
10) Implement structures to read, write and compute average- marks of the students, list
the students scoring above and below the average marks for a class of N students.
11) Develop a program using pointers to compute the sum, mean and standard deviation of
all elements stored in an array of N real numbers.
12) . Write a C program to copy a text file to another, read both the input file name and
target file name.

1) Simulation of a Simple Calculator.

3 Dept of CSE,MYCEM
C PROGRAMMING LABORATORY BPOPS103

Program
#include<stdio.h>
void main()
{
int op1, op2;
char operator;
printf("\nEnter the arithmetic expression\n");
scanf("%d%c%d", &op1, &operator, &op2);
switch(operator)
{
case '+': printf("\nResult = %d", op1 + op2);
break;
case '-': printf("\nResult = %d", op1 - op2);
break;
case '*': printf("\nResult = %d", op1 * op2);
break;
case '/': printf("\nResult = %f", (float) op1 / op2);
break;
case '%': printf("\nResult = %d", op1 % op2);
break;

}
}

Output
Enter the arithmetic expression
4+6
Result = 10
Enter the arithmetic expression
2-9
Result = -7
Enter the arithmetic expression
5*2
Result = 10
Enter the arithmetic expression
4/5
Result = 0.8
Enter the arithmetic expression

4 Dept of CSE,MYCEM
C PROGRAMMING LABORATORY BPOPS103

8/4
Result = 2
Enter the arithmetic expression
15%4
Result = 3

5 Dept of CSE,MYCEM
C PROGRAMMING LABORATORY BPOPS103

2) Compute the roots of a quadratic equation by accepting the coefficients. Print


appropriate messages.

6 Dept of CSE,MYCEM
C PROGRAMMING LABORATORY BPOPS103

PROGRAM
#include<stdio.h>
#include<math.h>
int main()
{
float x1, x2, a, b, c, disc;
printf("Enter the coefficients a, b and c\n");
scanf("%f%f%f",&a,&b,&c);
disc=(b*b)-(4*a*c);
if(disc == 0)
{
x1= -b/(2*a);
x2= -b/(2*a);
printf("The roots are real and equal\n");
printf("1st root = %f\n",x1);
printf("2nd root = %f\n",x2);
}
else if(disc > 0)
{
x1=(-b+sqrt(disc))/(2*a);
x2=(-b-sqrt(disc))/(2*a);
printf("The roots are real and distinct\n");
printf("1st root = %f\n",x1);
printf("2nd root = %f\n",x2);
}
else if(disc<0)
{
x1=-b/(2*a);
x2=sqrt(fabs(disc))/(2*a);
printf("The roots are imaginary\n");
printf("1st root = %f + i%f\n",x1,x2);
printf("2nd root = %f - i%f\n",x1,x2);
}
}

OUTPUT
user@user-System-Product-Name:~$ cc try.c -lm
user@user-System-Product-Name:~$ ./a.out
Enter the coefficients a, b and c
1
1

7 Dept of CSE,MYCEM
C PROGRAMMING LABORATORY BPOPS103

1
The roots are imaginary
1st root = -0.500000 + i0.866025
2nd root = -0.500000 - i0.866025
user@user-System-Product-Name:~$ ./a.out
Enter the coefficients a, b and c
123
The roots are imaginary
1st root = -1.000000 + i1.414214
2nd root = -1.000000 - i1.414214
user@user-System-Product-Name:~$ ./a.out
Enter the coefficients a, b and c
441
The roots are real and equal
1st root = -0.500000
2nd root = -0.500000

user@user-System-Product-Name:~$ ./a.out
Enter the coefficients a, b and c
1 -5 6
The roots are real and distinct
1st root = 3.000000
2nd root = 2.000000

8 Dept of CSE,MYCEM
C PROGRAMMING LABORATORY BPOPS103

3) An electricity board charges the following rates for the use of electricity: for the first 200
units 80 paise per unit: for the next 100 units 90 paise per unit: beyond 300 units Rs 1 per
unit. All users are charged a minimum of Rs. 100 as meter charge. If the total amount is
more than Rs 400, then an additional surcharge of 15% of total amount is charged. Write a
program to read the name of the user, number of units consumed and print out the charges.

PROGRAM

#include<stdio.h>
void main()
{
char name[25];
int units;
float charges=0.0;
printf("Enter Customer Name and Number of Units:\n");
scanf("%s %d",name,&units);
if(units>0 && units<=200)
charges= 100+(0.80*units);
else if(units>=201 && units<=300)
charges = 100+160+(0.90 *(units-200));
else if(units>300)
charges= 100 + 250+(1.0 * (units-300));
printf("Customer Name=%s\n",name);
if(charges>400)
{
charges=charges + 0.15*charges;
printf("Total Charges=%f\n",charges);
}
else
printf("Total Charges=%f\n",charges);
}

Output
Enter Customer Name and Number of Units:
ravi
100
Customer Name=ravi
Total Charges=180.000000

9 Dept of CSE,MYCEM
C PROGRAMMING LABORATORY BPOPS103

4). Write a C Program to display the following by reading the number of rows as input,

1
121
12321
1234321
-------------------------- n th row
PROGRAM

#include<stdio.h>
int main()
{
int i,j,n,k,m;
printf("Input number of rows :\n");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(j=1;j<=n-i;j++)
{
printf(" ");
}
for(k=1;k<=i;k++)
{
printf("%d",k);
}
for(m=i-1;m>=1;m--)
{
printf("%d",m);
}
printf("\n");
}
return 0;
}

10 Dept of CSE,MYCEM
C PROGRAMMING LABORATORY BPOPS103

OUTPUT
./a.out
Input number of rows :
4
1
121
12321
1234321
user@user-System-Product-Name:~$ ./a.out
Input number of rows :
5
1
121
12321
1234321
123454321

11 Dept of CSE,MYCEM
C PROGRAMMING LABORATORY BPOPS103

5) Implement Binary Search on Integers.

PROGRAM

#include<stdio.h>
void main()
{
int a[100], n, i, mid, low, high, found, key;
printf("\nEnter the number of elements : ");
scanf("%d",&n);
printf("\nEnter the elements in ascending order : ");
for(i=0; i<n; i++)
scanf("%d", &a[i]);
printf("\nEnter the key element : ");
scanf("%d", &key);
found = 0;
low = 0;
high = n-1;
while(low <= high)
{
mid = (low+high)/2;
if(key == a[mid])
{
found = 1;
break;
}
else if(key < a[mid])
high = mid-1;
else
low = mid+1;
}
if(found==1)
printf("\nKey element %d found at position %d\n", key, mid+1);
else
printf("\nKey element not found\n");

12 Dept of CSE,MYCEM
C PROGRAMMING LABORATORY BPOPS103

OUTPUT
./a.out

Enter the number of elements : 5

Enter the elements in ascending order : 23 45 67 89 99

Enter the key element : 45

Key element 45 found at position 2

13 Dept of CSE,MYCEM
C PROGRAMMING LABORATORY BPOPS103

6) Implement Matrix multiplication and validate the rules of multiplication.

14 Dept of CSE,MYCEM
C PROGRAMMING LABORATORY BPOPS103

PROGRAM

#include<stdio.h>

15 Dept of CSE,MYCEM
C PROGRAMMING LABORATORY BPOPS103

#include<stdlib.h>
void main()
{
int i, j, a[10][10], b[10][10], c[10][10], k, r1, c1, r2, c2;
printf("Enter the array size of 1st matrix");
scanf("%d%d", &r1,&c1);
printf("Enter the array size of 2nd matrix");
scanf("%d%d",&r2,&c2);
if(c1!=r2)
{

printf("Matrix multiplication is not possible");


exit(0);
}

else
{
printf("Enter the elements of 1st matrix");
for(i=0; i<r1; i++)
{
for(j=0;j<c1;j++)
{
scanf("%d", &a[i][j]);
}
}
printf("Enter the elements of 2nd matrix");
for(i=0; i<r2; i++)
{
for(j=0; j<c2; j++)
{
scanf("%d", &b[i][j]);
}
}
for(i=0; i<r1; i++)
{
for(j=0; j<c2; j++)
{
c[i][j]=0;

16 Dept of CSE,MYCEM
C PROGRAMMING LABORATORY BPOPS103

for(k=0; k<c1; k++)


{
c[i][j]=c[i][j]+(a[i][k]*b[k][j]);
}
}
}
}
printf("The resultant matrix is\n");
for(i=0; i<r1; i++)
{
for(j=0; j<c2; j++)
{
printf("%d\t", c[i][j]);
}
printf("\n");
}
}
OUTPUT
./a.out
Enter the array size of 1st matrix2 2
Enter the array size of 2nd matrix2 2
Enter the elements of 1st matrix1 2
34
Enter the elements of 2nd matrix1 2
34
The resultant matrix is
7 10
15 22
user@user-System-Product-Name:~$ ./a.out
Enter the array size of 1st matrix2 3
Enter the array size of 2nd matrix2 3
Matrix multiplication is not possible

7) Compute sin(x)/cos(x) using Taylor series approximation. Compare your result with the
built-in library function. Print both the results with appropriate inferences.

17 Dept of CSE,MYCEM
C PROGRAMMING LABORATORY BPOPS103

EXPLANATION

PROGRAM
#include<stdio.h>
#include<math.h>
void main()
{
int i;
float degree,x,term,sum;
printf("enter the value in degrees\n");
scanf("%f",&degree);
x=degree*3.142/180;
term=x;
sum=term;
for(i=3;i<=20;i=i+2)
{
term= -term*x*x/((i-1)*i);
sum=sum+term;
}
printf("MYSIN(%f)=%f\n",degree,sum);
printf("Using built-in library function,SIN(%f)=%f\n",degree,sin(x));
}

18 Dept of CSE,MYCEM
C PROGRAMMING LABORATORY BPOPS103

OUTPUT

Program - cos(x) using Taylor Series

#include<stdio.h>
#include<math.h>
float my_cos(float x, int n);
int fact(int n);
void main()
{
int x, n;
float rad, res;
printf("ENTER THE DEGREE : ");
scanf("%d",&x);
printf("ENTER THE NUMBER OF TERMS : ");
scanf("%d", &n);
rad=x*(3.142/180);
res=my_cos(rad , n);
printf("my_cos(%d) = %f\n", x , res);
printf("Library cos(%d) = %f", x , cos(rad));
}
float my_cos(float x, int n)

19 Dept of CSE,MYCEM
C PROGRAMMING LABORATORY BPOPS103

{
int i;
float sum=0;
for(i=0; i<=n; i=i+2)
{
if(i%4==0)
sum=sum+pow(x , i)/fact(i);
else
sum=sum-pow(x , i)/fact(i);
}
return sum;
}
int fact(int n)
{
if(n==0)
return 1;
else
return n*fact(n-1);
}

OUTPUT
ENTER THE DEGREE : 60
ENTER THE NUMBER OF TERMS : 10
my_cos(60) = 0.499882
Library cos(60) = 0.499882
ENTER THE DEGREE : 0
ENTER THE NUMBER OF TERMS : 10
my_cos(0) = 1.000000
Library cos(0) = 1.000000
ENTER THE DEGREE : 90
ENTER THE NUMBER OF TERMS : 10
my_cos(90) = -0.000204
Library cos(90) = -0.000204

8) Sort the given set of N numbers using Bubble sort.


Explanation
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent

20 Dept of CSE,MYCEM
C PROGRAMMING LABORATORY BPOPS103

elements if they are in wrong order.


Example: First Pass:
( 5 1 4 2 8 ) –>( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps
since 5 > 1.
( 15 4 2 8 ) –>( 14 5 2 8 ), Swap since 5 > 4
( 1 4 5 2 8 ) –>( 1 4 2 5 8 ), Swap since 5 > 2
( 1 4 2 5 8 ) –>( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5), algorithm
does
not swap them.
Second Pass:
( 1 4 2 5 8 ) –>( 1 4 2 5 8 )
( 14 2 5 8 ) –>( 12 4 5 8 ), Swap since 4 > 2
( 1 2 4 5 8 ) –>( 1 2 4 5 8 )
( 1 2 4 5 8 ) –>( 1 2 4 5 8 )
Now, the array is already sorted, but our algorithm does not know if it is completed. The
algorithm needs one whole pass without any swap to know it is sorted.
Third Pass:
( 1 2 4 5 8 ) –>( 1 2 4 5 8 )
( 12 4 5 8 ) –>( 12 4 5 8 )
( 1 2 4 5 8 ) –>( 1 2 4 5 8 )
( 1 2 4 5 8 ) –>( 1 2 4 5 8 )

PROGRAM
#include<stdio.h>
void main()
{
int a[10], n, i, j, temp;
printf("Enter the number of elements\n");
scanf("%d",&n);
printf("Enter the array elements\n");
for(i=0; i<n; i++)
scanf("%d", &a[i]);
for(j=1; j<n; j++)
{
for(i=0; i<n-j; i++)
{
if(a[i]> a[i+1])
{

21 Dept of CSE,MYCEM
C PROGRAMMING LABORATORY BPOPS103

temp=a[i];
a[i]=a[i+1];
a[i+1]=temp;
}
}
}
printf("The sorted array is\t");
for(i=0; i<n; i++)
printf("%d\t", a[i]);

OUTPUT
Enter the number of elements 7
Enter the array elements 12 23 10 13 15 1 8
The sorted array is 1 8 10 12 13 15 23

9) Write functions to implement string operations such as compare, concatenate, and find
string length. Use the parameter passing techniques.
#include<stdio.h>

22 Dept of CSE,MYCEM
C PROGRAMMING LABORATORY BPOPS103

int mystrlen(const char *str)


{
int i=0;
while (str[i]!= '\0') i++;
return i;
}
int mystrcmp(const char *s1, const char *s2)
{
int i=0;
while (s1[i]==s2[i] && s1[i]!= '\0') i++;
return s1[i] - s2[i];
}
void mystrcat(char *dest, const char *src)
{
int i=0, j=0;
j = mystrlen(dest);
while (src[i] != '\0' ) dest[j++] = src[i++];
dest[j++] = '\0';
}
int main()
{
int len1, len2, a;
char str1[30], str2[30];
printf("\nEnter two strings\n");
printf("\nString 1 : ");
scanf("%s", str1);
printf("\nString 2 : ");
scanf("%s", str2);
len1 = mystrlen(str1);
len2 = mystrlen(str2);
printf("\nLength of String %s is %d", str1, len1);
printf("\nLength of String %s is %d", str2, len2);
a = mystrcmp(str1, str2);
if(a == 0)
printf("\nTwo strings are equal");
else if(a > 0)
printf("\nString %s is greater than String %s ", str1, str2);
else

23 Dept of CSE,MYCEM
C PROGRAMMING LABORATORY BPOPS103

printf("\nString %s is greater than String %s ", str2, str1);


mystrcat(str1, str2);
printf("\nConcatenated String is %s", str1);
}

OUTPUT
Enter two strings
String 1 : ramesh
String 2 : ramesh
Length of String ramesh is 6
Length of String ramesh is 6
Two strings are equal
Concatenated String is rameshramesh

Enter two strings


String 1 : sam
String 2 : samantha
Length of String sam is 3
Length of String samantha is 8
String samantha is greater than String sam
Concatenated String is samsamantha

10) Implement structures to read, write and compute average- marks and the students
scoring above and below the average marks for a class of N students.

24 Dept of CSE,MYCEM
C PROGRAMMING LABORATORY BPOPS103

PROGRAM
#include<stdio.h>
struct student
{
char name[20];
char usn[10];
int marks;
};
void main()
{
int i,n,total=0;
struct student s[10];
float avg = 0.0;
printf("\nEnter the number of students : ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\nEnter the details of Student %d\n",i+1);
scanf("%s%s%d", s[i].name, s[i].usn, &s[i].marks);
total = total + s[i].marks;
}
avg = (float) total / n;
printf("\nThe average marks for the class is : %f\n", avg);
for(i=0; i<n; i++)
{
if(s[i].marks >avg)
printf("\nThe student %s has scored above average\n",s[i].name);
else if (s[i].marks <avg)
printf("\nThe student %s has scored below average\n",s[i].name);
}
}

OUTPUT
Enter the number of students : 3
Enter the details of Student 1
Raju
4AD17CS036
67

25 Dept of CSE,MYCEM
C PROGRAMMING LABORATORY BPOPS103

Enter the details of Student 2


Sahana
4AD17CS405
77

Enter the details of Student 3


Manasa
4AD17CS025
83
The average marks for the class is :75.67
The student Raju has scored below average
The student Sahana has scored above average
The student Manasa has scored above average

11) Develop a program using pointers to compute the sum, mean and standard deviation of
all elements stored in an array of N real numbers.
#include<stdio.h>

26 Dept of CSE,MYCEM
C PROGRAMMING LABORATORY BPOPS103

#include<math.h>
int main()
{
float a[50],

*ptr, sum=0, mean, std, sumstd=0;

int i,n;
printf("Enter the number of elements in the array\n");
scanf("%d",&n);
printf("Enter the elements in the array\n");
for(i=0;i<n;i++)
{
scanf("%f",&a[i]);
}
ptr= a;
for(i=0;i<n;i++)
{
sum= sum+ *ptr;
ptr++;
}
mean= sum/n;
ptr= a;
for(i=0;i<n;i++)
{
sumstd= sumstd+ pow((*ptr-mean),2);
ptr++;
}
std= sqrt(sumstd/n);
printf("Sum is %0.2f\n",sum);
printf("Mean is %0.2f\n",mean);
printf("Standard deviation is %0.2f\n",std);
return 0;
}

OUTPUT
user@user-System-Product-Name:~$ ./a.out
Enter the number of elements in the array

27 Dept of CSE,MYCEM
C PROGRAMMING LABORATORY BPOPS103

5
Enter the elements in the array
10 20 30 40 50
Sum is 150.00
Mean is 30.00
Standard deviation is 14.14

12) Write a C program to copy a text file to another, read both the input file name and
target file name.

28 Dept of CSE,MYCEM
C PROGRAMMING LABORATORY BPOPS103

PROGRAM
#include<stdio.h>
#include<stdlib.h>
void main()
{
FILE *fp1,*fp2;
int ch;
char fname1[100], fname2[100];
printf("\nEnter File name to be copied\n");
scanf("%s",fname1);
fp1 = fopen(fname1,"r");
if(fp1 == NULL)
{
printf("\nInput File %s doesn’t exist\n", fname1);
exit(0);
}
printf("\nEnter target File name\n");
scanf("%s",fname2);
fp2 = fopen(fname2,"w");
while((ch=fgetc(fp1)) != EOF)
{
fputc(ch,fp2);
}
printf("\nFile %s successfully created\n",fname2);
fclose(fp1);
fclose(fp2);
}

OUTPUT
user@user-System-Product-Name:~$ ./a.out

Enter File name to be copied


try.c

Enter target File name


try1.c

File try1.c successfully created

29 Dept of CSE,MYCEM
C PROGRAMMING LABORATORY BPOPS103

user@user-System-Product-Name:~$ ./a.out

Enter File name to be copied


rt.c

Input File rt.c doesn’t exist

30 Dept of CSE,MYCEM

You might also like