sonucgn.files.wordpress.com€¦  · web view05/01/2018  · objectives: learn c programming...

82
Computer Programming Lab Objectives: Learn C Programming language To make the student solve problems, implement algorithms using C language. List of Experiments/Tasks 1. Practice DOS and LINUX Commands necessary for design of C Programs. 2. Study of the Editors, Integrated development environments, and Compilers in chosen Platform. 3. Write, Edit, Debug, Compile and Execute Sample C programs to understand the programming Environment. 4. Practice programs: Finding the sum of three numbers, exchange of two numbers, maximum of Two numbers, To read and print variable values of all data types of C language, to find the Size of all data types, to understand the priority and associatively of operators using Expressions, to use different library functions of C language. 5. Write a program to check whether the number is prime or not. 6. Write a program to find the series of prime numbers in the given range. 7. Write a program to find the maximum of a set of numbers. 8. Write a program to find the sum of the digits of a number. 9. Write a program to find the sum of positive and negative numbers in a given set of numbers. 10 Write a program to read two matrices and print their sum and product in the matrix form. 11. Write a program to read matrix and perform the following operations. i. Find the sum of Diagonal Elements of a matrix. ii. Print Transpose of a matrix. iii. Print sum of even and odd numbers in a given matrix. 12. Write a program to insert a substring in to a given string and delete few characters from the String. Don’t use library functions related to strings. 13. Write a program to split a „file‟ in to two files, say file1 and file2. Read lines into the „file‟ from standard input. File1 should consist of odd numbered lines and file2 should consist of even numbered lines. Kuppam Engineering College, Kuppam

Upload: others

Post on 28-Sep-2020

1 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: sonucgn.files.wordpress.com€¦  · Web view05/01/2018  · Objectives: Learn C Programming language. To make the student solve problems, implement algorithms using C language

Computer Programming Lab

Objectives: Learn C Programming language To make the student solve problems, implement algorithms using C language.

List of Experiments/Tasks

1. Practice DOS and LINUX Commands necessary for design of C Programs.2. Study of the Editors, Integrated development environments, and Compilers in chosen Platform.3. Write, Edit, Debug, Compile and Execute Sample C programs to understand the programmingEnvironment.4. Practice programs: Finding the sum of three numbers, exchange of two numbers, maximum of Two numbers, To read and print variable values of all data types of C language, to find the Size of all data types, to understand the priority and associatively of operators using Expressions, to use different library functions of C language.5. Write a program to check whether the number is prime or not.6. Write a program to find the series of prime numbers in the given range.7. Write a program to find the maximum of a set of numbers.8. Write a program to find the sum of the digits of a number.9. Write a program to find the sum of positive and negative numbers in a given set of numbers.10 Write a program to read two matrices and print their sum and product in the matrix form.11. Write a program to read matrix and perform the following operations.i. Find the sum of Diagonal Elements of a matrix.ii. Print Transpose of a matrix.iii. Print sum of even and odd numbers in a given matrix.12. Write a program to insert a substring in to a given string and delete few characters from theString. Don’t use library functions related to strings.13. Write a program to split a „file‟ in to two files, say file1 and file2. Read lines into the „file‟from standard input. File1 should consist of odd numbered lines and file2 should consist ofeven numbered lines.14. Write a program to implement numerical methods Lagrange‟s interpolation, Trapezoidal rule.15. Write a program to read two strings and perform the following operations without using built-in string Library functions and by using your own implementations of functions.i. String length determination ii .Compare Two Stringsiii. Concatenate them, if they are not equal iv. String reversing16. Write programs using recursion for finding Factorial of a number, GCD, LCM, and solvingTowers of Hanoi problem.17. Write a program to exchange two numbers using pointers.18. Write a program to read student records into a file. Record consists of rollno, name and marks of a student in six subjects and class. Class field is empty initially. Compute the class of astudent. The calculation of the class is as per JNTUA rules. Write the first class, second class,third class and failed students lists separately to another file.19. A file consists of information about employee salary with fields employee id, name, Basic,HRA, DA, IT, other-deductions, Gross and Net salary. Initially only employee id, name, andBasic have valid values. HRA is taken as 10% of the basic, DA is taken as 80% of basic, and IT is20% of the basic, other deductions is user specified. Compute the Gross and Net salary of theEmployee and update the file.

Kuppam Engineering College, Kuppam

Page 2: sonucgn.files.wordpress.com€¦  · Web view05/01/2018  · Objectives: Learn C Programming language. To make the student solve problems, implement algorithms using C language

Computer Programming Lab

20. Write a program to perform Base (decimal, octal, hexadecimal, etc) conversion.21. Write a program to find the square root of a number without using built-in library function.22. Write a program to convert from string to number.23. Write a program to implement pseudo random generator.24. Write a program to express a four digit number in words. For example 1546 should be written as one thousand five hundred and forty six.25. Write a program to generate a telephone bill. The contents of it and the rate calculation etcshould be as per BSNL rules. Student is expected to gather the required information throughthe BSNL website.26. Write a program to find the execution time of a program.27. Design a file format to store a person's name, address, and other information. Write a program to read this file and produce a set of mailing labels

Kuppam Engineering College, Kuppam

Page 3: sonucgn.files.wordpress.com€¦  · Web view05/01/2018  · Objectives: Learn C Programming language. To make the student solve problems, implement algorithms using C language

Computer Programming Lab

In LINUX Environment:-Compiling and Executing C program 1. Write and save the program Open a simple text editor like gedit or Vim. Here we are using gedit as it is very simple to use and it’s recommended for beginner programmers. Right Click on Desktop or any directory and select create new File – hello.c (.c extension is used to indicate that it’s a c program). Then write a simple program like this and for saving the program press Ctrl+S.

#include<stdio.h>

void main(){ printf("Hello! This is my first C program with Ubuntu 11.10\n"); /* Do something more if you want */}

2. Compile the programGCC (GNU Compiler Collection) is installed by default. To compile the program, open the terminal and move on to the target directory type the command – (where gcc implies compiler name, then it asks for the file name of the source program while -o option specifies the  file name of the output program)gcc hello.c -o hello1If there is no syntax/semantic error in you program then the compiler will successfully generate an executable file, otherwise fix the problem in the code.

3. Execute the programTo execute the program, you need to run -./hello1

Kuppam Engineering College, Kuppam

Page 4: sonucgn.files.wordpress.com€¦  · Web view05/01/2018  · Objectives: Learn C Programming language. To make the student solve problems, implement algorithms using C language

Computer Programming Lab

4(a). Write a c program to find the sum of three numbers

Aim:- to write a program find the sum of three numbers

Program Description:- In this program , we accept three numbers and find their sum.

Source Code:-#include<stdio.h>#include<conio.h>void main(){

int a,b,c,sum;clrscr();printf("\nEnter three numbers :");scanf("%d%d%d",&a,&b,&c);sum=a+b+c;printf("\n Sum of %3d,%3d and %3d is=%4d",a,b,c,sum);getch();

}

Input:-Enter three numbers :24 32 65

Output:- Sum of 24, 32 and 65 is= 121

Kuppam Engineering College, Kuppam

Page 5: sonucgn.files.wordpress.com€¦  · Web view05/01/2018  · Objectives: Learn C Programming language. To make the student solve problems, implement algorithms using C language

Computer Programming Lab

4(b). Write a c program to exchange of two numbers

Aim:- to write program to exchange of two numbers

Program Description:-In this program we exchange two numbers without using the third variable. The

process can be performed by using the third variable also.

Source Code:-#include<stdio.h>#include<conio.h>void main(){

int a,b;clrscr();printf("\nEnter two numbers :");scanf("%d%d",&a,&b);printf("\n Before swapping, values are a=%3d and b=%3d",a,b);a=a+b;b=a-b;a=a-b;printf("\n After swapping, values are a=%3d and b=%3d",a,b);getch();

}

Input:-Enter two numbers :7 9

Output:- Before swapping, values are a=7 and b=9 After swapping, values are a=9 and b=7

Kuppam Engineering College, Kuppam

Page 6: sonucgn.files.wordpress.com€¦  · Web view05/01/2018  · Objectives: Learn C Programming language. To make the student solve problems, implement algorithms using C language

Computer Programming Lab

4(c). Write a c program to find maximum of two numbers

Aim:- To write a program to find maximum of two numbers

Program Description:- In this program , by using the conditional operator we find the maximum of two numbers.

Source Code:-#include<stdio.h>#include<conio.h>void main(){

int a,b,max;clrscr();printf("\nEnter two numbers :");scanf("%d%d",&a,&b);max=(a>b)?a:b;printf("\n Maximum of %3d and %3dis=%3d",a,b,max);getch();

}

Input:-Enter two numbers :15 36

Output:-Maximum of 15 and 36 is= 36

Kuppam Engineering College, Kuppam

Page 7: sonucgn.files.wordpress.com€¦  · Web view05/01/2018  · Objectives: Learn C Programming language. To make the student solve problems, implement algorithms using C language

Computer Programming Lab

4(d). Write a c program to read and print variable values of all data types of C language and also find their sizes

Aim:- To write a program to read and print variable values of all data types of C language and also find their sizes.

Program Description:- In this program , we accept variables of all data types that are supported by c language and find their sizes by using sizeof() operator.

Source Code:-#include<stdio.h>#include<conio.h>void main(){

int a;long int l;unsigned int ul;float f;double d;char c;clrscr();printf("\nEnter a integer value :");scanf("%d",&a);printf("\nEnter an unsigned value :");scanf("%u",&ul);printf("\nEnter a long integer value :");scanf("%ld",&l);printf("\nEnter a float value :");scanf("%f",&f);printf("\nEnter a double value :");scanf("%lf",&d);flushall();printf("\nEnter a character :");c=getchar();//scanf("%c",&c);printf("\n Given values are:\n");printf("\n Integer =%4d and its size=%4d",a,sizeof(a));printf("\n Unsigned Integer =%4u and its size=%4d",ul,sizeof(ul));printf("\n Long Integer =%ld and its size=%4d",l,sizeof(l));printf("\n Float =%6.2f and its size=%4d",f,sizeof(f));printf("\n Double =%lf and its size=%4d",d,sizeof(d));printf("\n Character =%c and its size=%4d",c,sizeof(c));getch();

}

Kuppam Engineering College, Kuppam

Page 8: sonucgn.files.wordpress.com€¦  · Web view05/01/2018  · Objectives: Learn C Programming language. To make the student solve problems, implement algorithms using C language

Computer Programming Lab

Input:-Enter a integer value :6325Enter an unsigned value :-958Enter a long integer value :263547Enter a float value :36.2541Enter a double value :23.65874Enter a character :k

Output:-

Given values are:

Integer =6325 and its size= 2 Unsigned Integer =64578 and its size=2 Long Integer =263547 and its size=4 Float = 36.25 and its size= 4 Double =23.658740 and its size=8 Character =k and its size=1

Kuppam Engineering College, Kuppam

Page 9: sonucgn.files.wordpress.com€¦  · Web view05/01/2018  · Objectives: Learn C Programming language. To make the student solve problems, implement algorithms using C language

Computer Programming Lab

4(e). Write a c program to understand the priority and associativity of operators using expressions

Aim:- To write a program to understand the priority and associativity of operators using expressions

Program Description:-In this program , we demonstrate the use of precedence and associativity.Source Code:-

#include<stdio.h>#include<conio.h>void main(){

int r;clrscr();r=2+3*8;// Since multipliation is having higher priority than addition ,// multiplication is performed first and then additionprintf("\n Result of the above expression is=%d",r);

r=4*8/2+8;//Both multiplication and division has equal priority and// hence by using associativity rule , multiplication is performed//first and then division as the rule is from left to rightprintf("\n Result of the above expression is=%d",r);

}

Output:- Result of the expression is=26 Result of the expression is=24

Kuppam Engineering College, Kuppam

Page 10: sonucgn.files.wordpress.com€¦  · Web view05/01/2018  · Objectives: Learn C Programming language. To make the student solve problems, implement algorithms using C language

Computer Programming Lab

4(f). Write a c program to use different library functions of C language.

Aim:- To write a program to use different library functions of C language

Program Description:- In this program, we specify the use of various string and mathematical library

functions.

Source Code:-#include<stdio.h>#include<conio.h>#include<math.h>#include<string.h>void main(){

int n;float f;char name[20];clrscr();printf("\n Enter a number:");scanf("%d",&n);f=sqrt(n);printf("\n Square root of number=%6.4f",f);printf("\n Ceil value of above result= %f",ceil(f));printf("\n Floor value of above result= %f",floor(f));flushall();printf("\n Enter a name :");scanf("%s",name);printf("\n Length of the name=%d",strlen(name));printf("\n Given name in uppercase= %s",strupr(name));printf("\n Given name in lowercase= %s",strlwr(name));printf(" \n Reverse of the name= %s",strrev(name));

}

Input:- Enter a number:8 Square root of number=2.8284 Ceil value of above result= 3.000000 Floor value of above result= 2.000000 Enter a name : krishna Length of the name=7 Given name in uppercase= KRISHNA Given name in lowercase= krishna Reverse of the name= anhsirk

Kuppam Engineering College, Kuppam

Page 11: sonucgn.files.wordpress.com€¦  · Web view05/01/2018  · Objectives: Learn C Programming language. To make the student solve problems, implement algorithms using C language

Computer Programming Lab

Viva Questions

1. What is an identifier?2. What are the rules to be followed while declaring the variables?3. What is a format specifier (or) control string?4. How to find the size of a data type?5. What is precedence of operators?6. What is associativity of operators?7. What is the difference between user–defined and built-in functions?8. What are header files. ?

Kuppam Engineering College, Kuppam

Page 12: sonucgn.files.wordpress.com€¦  · Web view05/01/2018  · Objectives: Learn C Programming language. To make the student solve problems, implement algorithms using C language

Computer Programming Lab

5. Write a program to check whether the number is prime or not.

Aim :- to write a program to check whether the number is prime or not

Program Description:- In this program , we divide the given number by a set of values from 1 to given number.

If the number of factors for the given number is two (i.e.,it is divisible by 1 and itself),then the given number is considered as prime number.

Source Code:#include<stdio.h>#include<conio.h>void main(){

int n,i,k=0;clrscr();printf("\n Enter a number :");scanf("%d",&n);i=1;while(i<=n){

if(n%i==0) k++;i++;

}if(k==2)

printf("\n Given number is a prime number");else

printf("\n Given number is not a prime number");}

Input:- Enter a number : 6

Output:- Given number is not a prime number

Input:-Enter a number :11Output:- Given number is a prime number

Viva Questions1. What is the difference between entry-controlled loop and exit-controlled loop?2. What is the default scope of if – statement?3. What is the difference between initialization and assigning?4. What is the difference between = and ==?5. If(k) . Is this a valid condition. If yes .Specify the reason?

Kuppam Engineering College, Kuppam

Page 13: sonucgn.files.wordpress.com€¦  · Web view05/01/2018  · Objectives: Learn C Programming language. To make the student solve problems, implement algorithms using C language

Computer Programming Lab

6. Write a program to find the series of prime numbers in the given range

Aim:- To write a C program to generate all the prime numbers between 1 and n .

Program Description:- In this program , we divide a number with 2 to number less than one , if the remainder is 0 for any one of the above divisions , we conclude that it is not a prime number else it is a prime number. The process repeats for 2 to given n value.

Source Code :-#include<stdio.h>#include<conio.h>void main(){

int n,i,j,k=0;clrscr();printf("Enter n value upto where prime numbers to be found: ");scanf("%d",&n);if(n==0){ printf(" \n Invalid number entered");

}printf(“ \n Required prime numbers are :”);i=2;

while(i<=n) { k=0;

j=2;while(j<n) {

if(i%j==0) k=1;

j++;}

if(k==1) printf(“%4d” , i);

i++;}

}

Kuppam Engineering College, Kuppam

Page 14: sonucgn.files.wordpress.com€¦  · Web view05/01/2018  · Objectives: Learn C Programming language. To make the student solve problems, implement algorithms using C language

Computer Programming Lab

Input :-Enter n value upto where prime numbers to be found: 10

Output:-Required prime numbers are : 2 3 5 7

Viva Questions1. What do you mean by nesting of structures?2. Why we should use & in case of scanf() and why we are not using & in case of printf()?3. Which header file to be included to implement clrscr()?4. Why we have to include an header file?5. In c which is the terminating(or)delimiter operator?

Kuppam Engineering College, Kuppam

Page 15: sonucgn.files.wordpress.com€¦  · Web view05/01/2018  · Objectives: Learn C Programming language. To make the student solve problems, implement algorithms using C language

Computer Programming Lab

7. Write a program to find maximum and minimum of set of numbers

Aim:- To write a C program to find both the largest and smallest in a list of integers

Program Description:- In this program , we assume first number is both minimum as well as maximum. For minimum , we compare minimum value with all other elements in the list. If minimum value is greater than any other value , we make that number as minimum. For maximum , we compare maximum value with all other elements in the list. If maximum value is less than any other value , we make that number as maximum

Source Code :-#include<stdio.h>#include<conio.h>void main(){

int a[20],i,min,max,n;clrscr();printf("\n Enter no. of elements:");scanf("%d",&n);printf("\n Enter the elements :");for(i=1;i<=n;i++)

scanf("%d",&a[i]);min=max=a[1];for(i=2;i<=n;i++){

if(max<a[i]) max=a[i]; if(min>a[i]) min=a[i];

}printf("\n Given elements are:\n");for(i=1;i<=n;i++)

printf("%5d",a[i]);printf("\n Maximum Value is=%d",max);printf("\n Minimum Value is=%d",min);getch();

}Input:- Enter no. of elements:6 Enter the elements : 12 10 8 2 24 15

Output:- Given elements are: 12 10 8 2 24 15Maximum Value is=24Minimum Value is=2

Kuppam Engineering College, Kuppam

Page 16: sonucgn.files.wordpress.com€¦  · Web view05/01/2018  · Objectives: Learn C Programming language. To make the student solve problems, implement algorithms using C language

Computer Programming Lab

Viva Questions1. What is an array?2. Array is static. Explain why?3. What are the advantages and disadvantages of an array?4. What is a subscript?5. What is the default range of a subscript?

Kuppam Engineering College, Kuppam

Page 17: sonucgn.files.wordpress.com€¦  · Web view05/01/2018  · Objectives: Learn C Programming language. To make the student solve problems, implement algorithms using C language

Computer Programming Lab

8. Write a program to find the sum of digits of a number

Aim:- To write a C program to find the sum of digits of a number

Program Description:- In this program , for each iteration we divide the number by 10 and the remainder is added to a variable sum which is initialized to Zero and we reduce the number to quotient. The process repeats until n>0

Source Code :-#include<stdio.h>#include<conio.h>void main(){ int n ,r ,s=0;

clrscr();printf("\n Enter the number : ");scanf("%d",&n);

while(n>0) {

r=n%10; s=s+r; n=n/10;

} printf("\n Sum of the digits is = %4d",s);

getch(); }

Input:- Enter the number : 256

Output:- Sum of the digits is = 13

Viva Questions1. What are tokens?2. What is the range of integer data type?3. What are different data types available in c?4. What are preprocessor directives?5. What is the use of “include” preprocessor directive?

Kuppam Engineering College, Kuppam

Page 18: sonucgn.files.wordpress.com€¦  · Web view05/01/2018  · Objectives: Learn C Programming language. To make the student solve problems, implement algorithms using C language

Computer Programming Lab

9. Write a program to find the sum of positive and negative numbers in a given set ofNumbers.

Aim:- To write a program to find the sum of positive and negative numbers in a given set of numbers.

Program Description:- We identify each element of the array as positive or negative by comparing with zero. Then we separately store the sum of positive and negative values in two variables which are initialized to zero.

Source Code:-#include<stdio.h>#include<conio.h>void main(){

int a[20],n,sp=0,sn=0,i;clrscr();printf("\n Enter size of the array :");scanf("%d",&n);printf("\n Enter the values of array :");for(i=1;i<=n;i++)

scanf("%d",&a[i]);for(i=1;i<=n;i++){

if(a[i]<0) // negativesn=sn+a[i];

else // positivesp=sp+a[i];

}printf("\n In given numbers,sum of positive values :%d",sp);printf("\n In given numbers,sum of negative values :%d",sn);

}

Input:-Enter size of the array: 9Enter the values of array: 8 -5 4 2 -7 -23 65 -32 24

Output:- In given numbers, sum of positive values : 103 In given numbers, sum of negative values :-67

Viva Questions1. int a[20];

After declaring the above array, if we use only ‘a’(without subscript) , what it refers to.2. What do you mean by static memory allocation?3. What the difference is between prefix and postfix increment?4. What is the difference between unary and binary operators?5. What are membership operators?

Kuppam Engineering College, Kuppam

Page 19: sonucgn.files.wordpress.com€¦  · Web view05/01/2018  · Objectives: Learn C Programming language. To make the student solve problems, implement algorithms using C language

Computer Programming Lab

10.Write a program to read two matrices and print their sum and product in the matrix form.

Aim:- To write a program to read matrices and print their sum and product in the matrix form.

Program Description:- In this program , To find the Sum of two matrices, we add the corresponding elements. To find the product , we multiply first row elements of first matrix with first column elements of second matrix. We obtain the first element in the product matrix by adding all the above products. Then we multiply first row elements of first matrix with second column elements of second matrix. We obtain the second element in the product matrix by adding all the above products. Repeat the above process for remaining elements in matrix.

Source Code :-#include<stdio.h>#include<conio.h>void input(int a[8][8],int r,int c);void output(int a[8][8],int r,int c);void add(int a[8][8],int b[8][8],int s[8][8],int r,int c);void multiply(int a[8][8],int b[8][8],int s[8][8],int r,int c,int p);void main(){

int a[8][8],b[8][8],s[8][8],r1,c1,r2,c2,ch;clrscr();printf("\n Enter rows and columns of first matrix:");scanf("%d%d",&r1,&c1);printf("\n Enter rows and columns of second matrix:");scanf("%d%d",&r2,&c2);printf("\n Enter the elements of first matrix:");input(a,r1,c1);printf("\n Enter the elements of second matrix:");input(b,r2,c2);printf("\n Elements of first matrix are:");output(a,r1,c1);printf("\n Elements of second matrix are:");output(b,r2,c2);

if((r1==r2)&&(c1==c2)){

add(a,b,s,r1,c1);printf("\n Sum of the two matrices is:");output(s,r1,c1);

}else{

printf("\n Matrix addition is not possible");}if(c1==r2)

Kuppam Engineering College, Kuppam

Page 20: sonucgn.files.wordpress.com€¦  · Web view05/01/2018  · Objectives: Learn C Programming language. To make the student solve problems, implement algorithms using C language

Computer Programming Lab

{multiply(a,b,s,r1,c2,c1);printf("\n Product of the two matrices is:");output(s,r1,c2);

}else{

printf("\n Matrix multiplication is not possible");}

getch();}void input(int a[8][8],int r,int c){ int i,j; for(i=0;i<r;i++) for(j=0;j<c;j++) scanf("%d",&a[i][j]);}void output(int a[8][8],int r,int c){ int i,j; printf("\n"); for(i=0;i<r;i++) { for(j=0;j<c;j++) {

printf("%4d",a[i][j]); } printf("\n "); }}void add(int a[8][8],int b[8][8],int s[8][8],int r,int c){ int i,j; for(i=0;i<r;i++) for(j=0;j<c;j++)

s[i][j]=a[i][j]+b[i][j];}void multiply(int a[8][8],int b[8][8],int s[8][8],int r,int c,int p){ int i,j,k; for(i=0;i<r;i++) for(j=0;j<c;j++) {

s[i][j]=0;for(k=0;k<p;k++)s[i][j]=s[i][j]+(a[i][k]*b[k][j]);

}}

Kuppam Engineering College, Kuppam

Page 21: sonucgn.files.wordpress.com€¦  · Web view05/01/2018  · Objectives: Learn C Programming language. To make the student solve problems, implement algorithms using C language

Computer Programming Lab

Input:- Enter rows and columns of first matrix:3 3 Enter rows and columns of second matrix:3 3 Enter the elements of first matrix: 5 2 6 9 8 7 1 2 1 Enter the elements of second matrix:6 4 7 8 4 1 3 2 5

Output:- Elements of first matrix are: 5 2 6 9 8 7 1 2 1 Elements of second matrix are: 6 4 7 8 4 1 3 2 5 Sum of the two matrices is: 11 6 13 17 12 8 4 4 6Product of the two matrices is: 64 40 67 139 82 106 25 14 14

Viva Questions

1. What is a function?

2. C follows modular programming .Explain?

3. What are the advantages of functions?

4. How to declare and initialize a multi-dimensional array?

5. What is the difference row major and column major?

Kuppam Engineering College, Kuppam

Page 22: sonucgn.files.wordpress.com€¦  · Web view05/01/2018  · Objectives: Learn C Programming language. To make the student solve problems, implement algorithms using C language

Computer Programming Lab

11. Write a program to read matrix and perform the following operations.i. Find the sum of Diagonal Elements of a matrix.ii. Print Transpose of a matrix.iii. Print sum of even and odd numbers in a given matrix.

Aim:- To write a program to read matrix and perform operations on it.Program Description:- By interchanging rows and columns we can obtain transpose of a matrix. By adding the sum of elements where row subscript and column subscript values are equal . We can find the sum of principle diagonal elements .Similarly we can identify secondary diagonal elements and add to the above sum. By diving the number by 2 we can identify whether the element is even or odd .By identifying them we can find the sum of even and odd element values of the matrix.

Source Code:-#include<stdio.h>#include<conio.h>void main(){

int a[8][8],s=0,se=0,so=0,n,i,j;clrscr();printf("\n Enter the order of the matrix :");scanf("%d",&n);printf("\n Enter the elemens of the matrix :");for(i=1;i<=n;i++) for(j=1;j<=n;j++)

scanf("%d",&a[i][j]);for(i=1;i<=n;i++) for(j=1;j<=n;j++) {

if(a[i][j]%2==0) // even numberse=se+a[i][j];

elseso=so+a[i][j];

if( (i==j) || (i+j)==(n+1) ) //diagonal elementss=s+a[i][j];

}printf("\n Sum of all diagonal elements is :%d",s);printf("\n Sum of even numbers in matrix is :%d",se);printf("\n Sum of odd numbers in matrix is :%d",so);printf("\n Transpose of the given matrix is:\n");for(i=1;i<=n;i++) { for(j=1;j<=n;j++)

printf("%3d",a[j][i]); printf("\n"); } getch();

Kuppam Engineering College, Kuppam

Page 23: sonucgn.files.wordpress.com€¦  · Web view05/01/2018  · Objectives: Learn C Programming language. To make the student solve problems, implement algorithms using C language

Computer Programming Lab

}Input:-Enter the order of the matrix :3 Enter the elemens of the matrix : 5 2 6 8 1 9 4 3 2

Output:- Sum of all diagonal elements is :18 Sum of even numbers in matrix is :22 Sum of odd numbers in matrix is :18 Transpose of the given matrix is: 5 8 4 2 1 3 6 9 2

Viva Questions1. In a two dimensional array , what the first and second subscripts represents. ?2. What is the difference between structure and an array?3. Can we produce the array size at run time. Justify?4. What are different dynamic memory allocation functions. ?5. What do you mean by dynamic initialization of a variable. ?

Kuppam Engineering College, Kuppam

Page 24: sonucgn.files.wordpress.com€¦  · Web view05/01/2018  · Objectives: Learn C Programming language. To make the student solve problems, implement algorithms using C language

Computer Programming Lab

12. Write a program to insert a sub string in to a given string from a given position. Don’t use library functions related to strings.

Aim:- To insert a sub string in to a given string from a given position.

Program Description:- In this program , first we find the sub string length (n) and we shift the entire characters from insertion position to the end by n positions forward and then we insert the sub string into main string.

Source Code :- #include<stdio.h>#include<conio.h>#include<string.h>void insert(char mstr[],char sstr[],int);void main(){ char mstr[80],sstr[20]; int p; printf("\n Enter the main string :"); gets(mstr); printf("\n Enter sub string to be inserted :"); gets(sstr); printf("\n Enter the position where substring to be inserted :"); scanf("%d",&p); insert(mstr,sstr,p); printf("\n After inserting , the resultant string is :"); puts(mstr);}void insert(char mstr[80],char sstr[30],int p){ int l1,l2,i,j; l1=strlen(mstr); l2=strlen(sstr); for(i=l1;i>=p;i--) mstr[i+l2]=mstr[i]; for(i=p,j=0;j<l2;j++,i++) mstr[i]=sstr[j];}

Kuppam Engineering College, Kuppam

Page 25: sonucgn.files.wordpress.com€¦  · Web view05/01/2018  · Objectives: Learn C Programming language. To make the student solve problems, implement algorithms using C language

Computer Programming Lab

Input:- Enter the main string : This is a text Enter sub string to be inserted : sample Enter the position where sub string to be inserted : 9

Ouput:- After inserting , the resultant string is : This is a sample text

Viva Questions1. Which header file to be included in order to using string functions. ?2. What strcmp() returns. ?3. How does strcat() works. ?4. Specify any 8 string handling functions?5. What is a string constant?

Kuppam Engineering College, Kuppam

Page 26: sonucgn.files.wordpress.com€¦  · Web view05/01/2018  · Objectives: Learn C Programming language. To make the student solve problems, implement algorithms using C language

Computer Programming Lab

13. Write a program to split a ‘file’ in to two files, say file1 and file2. Read lines into the‘file’ from standard input. File1 should consist of odd numbered lines and file2 shouldconsist of even numbered lines.

Aim:- To split the files into two files

Program Description:- In this program we identify whether a line is odd numbered or even numbered by using a variable k which is initialized to 1. This variable is incremented by 1 when we encounter ‘\n’ character. The odd numbered lines of text is copied to one file and even numbered lines of text are copied to another file.

Source Code:-#include<stdio.h>#include<conio.h>void main(){

FILE *fp1,*fp2,*fp3;char ch;int k=1;clrscr();fp1=fopen("c:/myfile.txt","w");printf("\n Enter the contents of the file (press # at end):\n");ch=getchar();while(ch!='#'){ putc(ch,fp1); ch=getchar();}fclose(fp1);fp1=fopen("c:/myfile.txt","r");fp2=fopen("c:/file1.txt","w");fp3=fopen("c:/file2.txt","w");ch=' ';while(!feof(fp1)){

putc(ch,fp2);ch=getc(fp1);while(ch!='\n'&& !feof(fp1)) //odd numbered lines{ putc(ch,fp2); ch=getc(fp1);}if(ch=='\n'){ k++; if(k%2==0)// even numbered lines {

putc(ch,fp3);

Kuppam Engineering College, Kuppam

Page 27: sonucgn.files.wordpress.com€¦  · Web view05/01/2018  · Objectives: Learn C Programming language. To make the student solve problems, implement algorithms using C language

Computer Programming Lab

ch=getc(fp1); while(ch!='\n' && !feof(fp1)) { putc(ch,fp3); ch=getc(fp1); } k++;

}}

}fcloseall();

}Input:-Enter the contents of the file (press # at end) :This is adityaI am studying B.Tech first yearI joined in CSE departmentMy home town is TirupathiMy father is a farmerMy Mother is a house wifeMy brother is a chartered Accountant #

Output:-C:\>type myfile.txtThis is adityaI am studying B.Tech first yearI joined in CSE departmentMy home town is TirupathiMy father is a farmerMy Mother is a house wifeMy brother is a chartered Accountant

C:\>type file1.txtThis is adityaI joined in CSE departmentMy father is a farmerMy brother is a chartered Accountant

C:\>type file2.txtI am studying B.Tech first yearMy home town is TirupathiMy Mother is a house wife

Viva Questions1. What is a file2. What are drawbacks of a standalone applications?3. Why to use a file?4. What are different file opening modes?5. What is a binary file?

Kuppam Engineering College, Kuppam

Page 28: sonucgn.files.wordpress.com€¦  · Web view05/01/2018  · Objectives: Learn C Programming language. To make the student solve problems, implement algorithms using C language

Computer Programming Lab

14a. Write a program to implement numerical method - Lagrange’s interpolation

Aim:- to implement numerical method - Lagrange’s interpolationProgram Description:-Lagrange’s Interpolation Formula:

1. Newton-Gregory forward interpolation is applicable only to equally spaced values of the argument; it is not applicable for unequal spaced values of argument.

2. Lagrange’s interpolation formula for unequal intervals

Source Code:-#include<stdio.h>#include<conio.h>#include<stdlib.h>#include<math.h>#define n 5void main(){ float y[20],x[20],xinp,u,sum=0,prodd,prodn; int i,j;

clrscr();printf("Enter the values of Interpolation Points \n");for(i=0;i<n;i++)

scanf("%f",&x[i]);printf("Enter the corresponding values of Y \n");for(i=0;i<n;i++)

scanf("%f",&y[i]);printf(" Enter the value of x at which Y(x) is needed \n");

scanf("%f",&xinp);for(i=0;i<n;i++){

prodn=1.0;prodd=1.0;for(j=0;j<n;j++){

if(i==j) continue;prodn=prodn*(xinp-x[j]);prodd=prodd*(x[i]-x[j]);

}sum=sum +(prodn/prodd)*y[i];

}

Kuppam Engineering College, Kuppam

Page 29: sonucgn.files.wordpress.com€¦  · Web view05/01/2018  · Objectives: Learn C Programming language. To make the student solve problems, implement algorithms using C language

Computer Programming Lab

printf(" The value of y is %f\n",sum);getch();

}

Input:-Enter the values of Interpolation Points2 5 8 10 12Enter the corresponding values of Y4.4 6.2 6.7 7.5 8.7Enter the value of x at which Y(x) is needed : 7

Output:- The value of y is 6.486012

Kuppam Engineering College, Kuppam

Page 30: sonucgn.files.wordpress.com€¦  · Web view05/01/2018  · Objectives: Learn C Programming language. To make the student solve problems, implement algorithms using C language

Computer Programming Lab

14b. Write a program to implement numerical method- Trapezoidal rule.

Aim:- to implement numerical method- Trapezoidal rule

Program Description:-Numerical Integration: Numerical Integration is a process of evaluating a definite integral from a set of tabulated values of the integrand f(x).The three methods of numerical integration used are:

1. Trapezoidal Rule.2. Simpson’s 1/3 rule.3. Simpson’s 3/8 rule.

Trapezoidal Rule:According to trapezoidal rule,

Source Source Code:-#include<stdio.h>#include<conio.h>#include<math.h>float fun(float x){ return(1/(1+(x*x)));}

void main(){

float x0,x1,sum,result,h;int i,n,ch;clrscr();printf("\n Enter the lower and upper limits :");scanf("%f%f",&x0,&x1);printf("\nEnter the number of intervals :");scanf("%d",&n);h=(x1-x0)/n;sum=fun(x0)+fun(x1);for(i=1;i<n;i++) sum=sum+2*fun(x0+i*h);result=sum*h/2;printf("\n The Result is = %6.2f",result);getch();

}

Kuppam Engineering College, Kuppam

Page 31: sonucgn.files.wordpress.com€¦  · Web view05/01/2018  · Objectives: Learn C Programming language. To make the student solve problems, implement algorithms using C language

Computer Programming Lab

Input:- Enter the lower and upper limits :10 80 Enter the number of intervals :8

Output:- The Result is = 0.10

Viva Questions1. Can we call one function inside another function. ?2. By default how values does a function returns?3. What is the use of return()?4. What is the use of continue?5. While printing a float value , we used %6.2f .what you mean by that. ?

Kuppam Engineering College, Kuppam

Page 32: sonucgn.files.wordpress.com€¦  · Web view05/01/2018  · Objectives: Learn C Programming language. To make the student solve problems, implement algorithms using C language

Computer Programming Lab

15. Write a program to read two strings and perform the following operations without using built-in string Library functions and by using your own implementations of functions.i. String length determination ii .Compare Two Stringsiii. Concatenate them, if they are not equal iv. String reversing

Aim:- To write a program to read two strings and perform operations on them without using library functions.

Program Description:- We find the string length by comparing each character of the string and increment a variable whose initial value is 0 until we encounter a null character. Then this variable specifies the length of the string. Once we find the length we can perform reversing by printing the characters from last to first. Similarly by comparing the corresponding position characters in the given two strings , we can identify whether the given strings are equal or not.

Source Code:-#include<stdio.h>#include<conio.h>int stringlength(char *s);int stringcompare(char *s1,char *s2,int ,int)void stringconcatenate(char *s1,char *s2,int,int);void stringreverse(char *s,int);void main(){

char str1[20],str2[30];int n,i,k,l1,l2;clrscr();printf("\n Enter the first string:");scanf("%s",str1);printf("\n Enter the second string: ");scanf("%s",str2);l1=stringlength(str1);printf("\n Length of first string is=%d",l1);l2=stringlength(str2);printf("\n Length of Second string is=%d",l2);k=stringcompare(str1,str2,l1,l2);if(k==1)

printf("\n Two strings are equal\n");else{

printf("\n Two strings are not equal");printf("\n After concatenating two strings, resultant string is:");stringconcatenate(str1,str2,l1,l2);

}printf("\n Reverse of first string is=");stringreverse(str1,l1);printf("\n Reverse of second string is=");stringreverse(str2,l2);

Kuppam Engineering College, Kuppam

Page 33: sonucgn.files.wordpress.com€¦  · Web view05/01/2018  · Objectives: Learn C Programming language. To make the student solve problems, implement algorithms using C language

Computer Programming Lab

getch();}

int stringlength(char *str){

int k;for(k=0;str[k]!='\0';k++);return(k);

}int stringcompare(char *s1,char *s2,int l1,int l2){

int i,t=0;if(l1==l2){ for(i=0;i<l1;i++) if(s1[i]!=s2[i])

t=1; if(t==0) return(1); else return(0); } else return(0);

}

void stringconcatenate(char *s1,char *s2,int l1,int l2){

int i;char str[60];for(i=0;i<l1;i++) str[i]=s1[i];str[l1]=' ';l1++;for(i=0;i<l2;i++) str[l1+i]=s2[i];printf("%s",str);

}void stringreverse(char *s,int l){ int i; for(i=l-1;i>=0;i--)

printf("%c",s[i]);}

Kuppam Engineering College, Kuppam

Page 34: sonucgn.files.wordpress.com€¦  · Web view05/01/2018  · Objectives: Learn C Programming language. To make the student solve problems, implement algorithms using C language

Computer Programming Lab

Input:- Enter the first string : krishna Enter the second string : kishore

Output:- Length of first string is=7 Length of Second string is=7Two strings are not equal After concatenating two strings, resultant string is :krishna kishore Reverse of first string is=anhsirk Reverse of second string is=erohsik

Input:- Enter the first string:balu Enter the second string: baluOutput:- Length of first string is=4 Length of Second string is=4Reverse of first string is=ulab Reverse of second string is=ulab

Viva Questions1. How to access string by using pointers. ?2. What is the use of strrev()?3. What is the difference between upper case and lower case characters?4. C is a case sensitive language. Justify?5. What is the use of strlen()?

Kuppam Engineering College, Kuppam

Page 35: sonucgn.files.wordpress.com€¦  · Web view05/01/2018  · Objectives: Learn C Programming language. To make the student solve problems, implement algorithms using C language

Computer Programming Lab

16(a). Write program using recursion for finding the factorial of a number.

Aim:- To find the factorial of a number using recursion

Program Description:- In this program we compare whether n≤0.If the condition is true we return 0 otherwise we recursively call the same function by reducing the value of n by 1.

Source Code:-#include<stdio.h>#include<conio.h>int rfact(int n){

if(n==0 || n==1) return 1;else return(n*rfact(n-1));

}

void main(){

int n,f;clrscr();printf("\n Enter a number:");scanf("%d",&n);f= rfact(n);printf("Factorial of %3d is=%d ",n,f);getch();

}

Input:-Enter a number:5

Output:- Factorial of 5 is=120

Kuppam Engineering College, Kuppam

Page 36: sonucgn.files.wordpress.com€¦  · Web view05/01/2018  · Objectives: Learn C Programming language. To make the student solve problems, implement algorithms using C language

Computer Programming Lab

16(b). Write program using recursion for finding the GCD of two numbers.

Aim:- To find the GCD of two numbers using recursion

Program Description:- Let x, y be two values. If x mod y=0 we return y else we consider y value as x and x mod y as y. By using these new values of x and y we recursively call the same function.

Source Code:-#include<stdio.h>#include<conio.h>void main(){

int a,b,r;clrscr();printf("\n Enter two numbers:");scanf("%d%d",&a,&b);if(a>b) r=rgcd(a,b);else r=rgcd(b,a);printf("GCD of %3d and %3d is=%3d",a,b,r);getch();

}int rgcd(int x,int y){

if (x%y==0) return y;else return rgcd(y,(x%y));

}

Input:-Enter two numbers:8 2

Output:- GCD of 8 and 2 is= 2

Kuppam Engineering College, Kuppam

Page 37: sonucgn.files.wordpress.com€¦  · Web view05/01/2018  · Objectives: Learn C Programming language. To make the student solve problems, implement algorithms using C language

Computer Programming Lab

16(c). Write program using recursion for finding the LCM of two numbers.

Aim:- To find the LCM of two numbers using recursion.

Program Description:- We initialize a variable by 1. We divide this variable with the given two numbers. If both of the remainders are zero we return the variable otherwise we increment the variable by one.

Source Code:-#include<stdio.h>#include<conio.h>int lcm(int, int);

void main(){

int a, b, result;clrscr();printf("Enter two numbers: ");scanf("%d%d", &a, &b);result = lcm(a, b);printf("The LCM of %d and %d is %d\n", a, b, result);getch();

}int lcm(int a, int b){

static int common = 1;if (common % a == 0 && common % b == 0) return common;common++;lcm(a, b);return common;

}

Input:-Enter two numbers: 8 6

Output:-The LCM of 8 and 6 is 24

Kuppam Engineering College, Kuppam

Page 38: sonucgn.files.wordpress.com€¦  · Web view05/01/2018  · Objectives: Learn C Programming language. To make the student solve problems, implement algorithms using C language

Computer Programming Lab

16(d). Write program using recursion to solve the problem of Towers of Hanoi.

Aim:- To solve the problem of Towers of Hanoi by using recursion

Program Description:-Towers of Hanoi:

Problem: The Towers of Hanoi is a well known children’s game , played with three poles and a number of different sized disks. Each disk has a hole in the center , allowing it to be placed around any of the poles. Initially , the disks are placed on the leftmost pole in the order of decreasing as shown below:

Left center Right

Object of the Game: The Object of the game is to transfer the disks from the leftmost pole to the right most pole .

Rules of the Game: Only one disk is to be transferred at a time. Each disk must always be placed around one of the poles but not outside. A larger disk should not be placed on top of a smaller disk .

Solution of the Game: Assume that there are n disks, numbered from smallest to largest . If disks are initially stacked on the left pole , the problem of moving all n disks to the right pole can be stated in the following recursive manner.

1. Move the top n-1 disks from the left pole to the center pole.2. Move the nth disk from left pole to right pole3. Move the n-1 disks on the center pole to the right pole.

Source Code:-#include<stdio.h>#include<conio.h>void transfer(int,char,char,char);void main(){

int n,ch;clrscr();printf("\n Enter no. of disks:");scanf("%d",&n);transfer(n,'l','r','t');getch();

Kuppam Engineering College, Kuppam

Page 39: sonucgn.files.wordpress.com€¦  · Web view05/01/2018  · Objectives: Learn C Programming language. To make the student solve problems, implement algorithms using C language

Computer Programming Lab

}void transfer(int n, char from, char to,char temp){

if(n>0){

transfer(n-1,from,temp,to);printf("\n Move disk %3d from %3c to %3c",n-1,from,to);transfer(n-1,temp,to,from);

}}

Input:-Enter no. of disks:3

Output:- Move disk 0 from l to r Move disk 1 from l to t Move disk 0 from r to t Move disk 2 from l to r Move disk 0 from t to l Move disk 1 from t to r Move disk 0 from l to r

Viva Questions1. What is recursion?2. What are the advantage and disadvantages of using recursion?3. What type of problems can be solved by using recursion?4. What is the use of static storage class?5. What is the scope and lifetime of a static variable?

Kuppam Engineering College, Kuppam

Page 40: sonucgn.files.wordpress.com€¦  · Web view05/01/2018  · Objectives: Learn C Programming language. To make the student solve problems, implement algorithms using C language

Computer Programming Lab

17. Write a program to exchange two numbers using pointers.

Aim:- To exchange two numbers using pointers

Program Description:- We use call by reference to swap two numbers using pointers

Source Code:-#include<stdio.h>#include<conio.h>void exchange(int *,int *);void main(){

int a,b;clrscr();printf("\n Enter two numbers :");scanf("%d%d",&a,&b);printf("\n Before exchanging ,a=%d and b=%d",a,b);exchange(&a,&b);printf("\n After exchanging ,a=%d and b=%d",a,b);getch();

}void exchange(int *x,int *y){

int t;t=*x;*x=*y;*y=t;

}Input:-Enter two numbers :5 9

Output:- Before exchanging ,a=5 and b=9 After exchanging ,a=9 and b=5

Viva Questions1. What are different parameter passing techniques?2. What is the difference between call by value and call by reference?3. What are formal and actual parameters?4. What are the different types of functions?5. What is the default return type of a function?

Kuppam Engineering College, Kuppam

Page 41: sonucgn.files.wordpress.com€¦  · Web view05/01/2018  · Objectives: Learn C Programming language. To make the student solve problems, implement algorithms using C language

Computer Programming Lab

18. Write a program to read student records into a file. Record consists of roll no, name and marks of a student in six subjects and class. Class field is empty initially. Compute the class of a student. The calculation of the class is as per JNTUA rules. Write the first class, second class, third class and failed students lists separately to another file.

Aim:- To read student records into a file and Write the first class, second class, third class and failed students lists separately to another file as per JNTU rules.Program Description:- In this program we input the roll no , name and six subject marks of each student and calculate the grade of the student based on JNTU A rules.

Source Code:-#include<stdio.h>#include<conio.h>#include<string.h>struct student{ char rollno[10]; char name[15]; int sub[6]; char grade[15];}s[20];void main(){

int n,k,i,j,avg,d[20],f[20],se[20],t[20],fail[20],dc,fc,sc,tc,failc;FILE *fp;clrscr();printf("\n Enter no. of students :");scanf("%d",&n);printf("\n Enter students details :");for(i=1;i<=n;i++){

printf("\n Enter %d student details :",i);flushall();printf("\n Roll No :");gets(s[i].rollno);flushall();printf("Name=");gets(s[i].name);printf("\n Enter six subject Marks:");for(j=1;j<=6;j++) scanf("%d",&s[i].sub[j]);

}dc=fc=sc=tc=failc=0;for(i=1;i<=n;i++){

if(s[i].sub[1]<40 || s[i].sub[2]<40 ||s[i].sub[3]<40 ||s[i].sub[4]<40 ||s[i].sub[5]<40 ||s[i].sub[6]<40){

Kuppam Engineering College, Kuppam

Page 42: sonucgn.files.wordpress.com€¦  · Web view05/01/2018  · Objectives: Learn C Programming language. To make the student solve problems, implement algorithms using C language

Computer Programming Lab

failc++; fail[failc]=i; strcpy(s[i].grade,"Fail");}else{ avg=(s[i].sub[1]+s[i].sub[2]+s[i].sub[3]+s[i].sub[4]

+s[i].sub[5]+s[i].sub[6])/6;

if(avg>=70) {

dc++;d[dc]=i;strcpy(s[i].grade,"Distinction");

} else if(avg>=60) {

fc++;f[fc]=i;strcpy(s[i].grade,"First Class");

} else if(avg>=50) {

sc++;se[sc]=i;strcpy(s[i].grade,"Second Class");

} else {

tc++;t[tc]=i;strcpy(s[i].grade,"Third Class");

}}

} fp=fopen("Results.txt","w"); fputs("Details of Distinction students \n",fp); fputs("Roll No \t Name \t Grade \n",fp); for(i=1;i<=dc;i++) {

k=d[i]; fprintf(fp,"%10s%3s%4s\n",s[k].rollno,s[k].name,s[k].grade);

} fputs("\nDetails of First class students \n",fp); fputs("Roll No \t Name \t Grade \n\n",fp); for(i=1;i<=fc;i++) {

k=f[i]; fprintf(fp,"%12s%13s%13s\n",s[k].rollno,s[k].name,s[k].grade);

Kuppam Engineering College, Kuppam

Page 43: sonucgn.files.wordpress.com€¦  · Web view05/01/2018  · Objectives: Learn C Programming language. To make the student solve problems, implement algorithms using C language

Computer Programming Lab

} fputs("\nDetails of Second class students \n",fp); fputs("Roll No \t Name \t Grade \n",fp); for(i=1;i<=sc;i++) {

k=se[i]; fprintf(fp,"%12s%13s%13s\n",s[k].rollno,s[k].name,s[k].grade);

} fputs("\nDetails of Third class students \n",fp); fputs("Roll No \t Name \t Grade \n",fp); for(i=1;i<=tc;i++) {

k=t[i]; fprintf(fp,"%12s%13s%13s\n",s[k].rollno,s[k].name,s[k].grade);

} fputs("\nDetails of Failed students \n",fp); fputs("Roll No \t Name \t Grade \n",fp); for(i=1;i<=failc;i++) {

k=fail[i]; fprintf(fp,"%12s%13s%13s\n",s[k].rollno,s[k].name,s[k].grade);

}

}

Input:- Enter no. of students :5 Enter students details : Enter 1 student details : Roll No :108P1A0312 Name=Rakesh Enter six subject Marks:65 84 73 81 96 77

Enter 2 student details : Roll No :108P1A0318 Name=Bala Krishna Enter six subject Marks:42 36 58 64 55 48

Enter 3 student details : Roll No :108P1A0325 Name=Raghu Enter six subject Marks:78 84 77 45 55 42

Enter 4 student details : Roll No :108P1A0342 Name=Krishna Enter six subject Marks:42 47 43 40 45 51

Kuppam Engineering College, Kuppam

Page 44: sonucgn.files.wordpress.com€¦  · Web view05/01/2018  · Objectives: Learn C Programming language. To make the student solve problems, implement algorithms using C language

Computer Programming Lab

Enter 5 student details : Roll No :108P1A0355 Name=Radhika Enter six subject Marks:55 64 52 51 58 60

Output:-C:\TC3\BIN>type results.txtDetails of Distinction studentsRoll No Name Grade108P1A0312 Rakesh Distinction

Details of First class studentsRoll No Name Grade108P1A0325 Raghu First Class

Details of Second class studentsRoll No Name Grade108P1A0355 Radhika Second Class

Details of Third class studentsRoll No Name Grade108P1A0342 Krishna Third Class

Details of Failed studentsRoll No Name Grade108P1A0318 Bala Krishna Fail

Viva Questions1. What is an array of structures? 2. How to declare an array within the structure?3. How to open a file?4. What is the use of fputs()?5. What is the difference between structure and union. ?

Kuppam Engineering College, Kuppam

Page 45: sonucgn.files.wordpress.com€¦  · Web view05/01/2018  · Objectives: Learn C Programming language. To make the student solve problems, implement algorithms using C language

Computer Programming Lab

19. A file consists of information about employee salary with fields employeeid, name, Basic, HRA, DA, IT, other-deductions, Gross and Net salary. Initially only employeeid, name, and basic have valid values. HRA is taken as 10% of the basic, DA is taken as 80% of basic, IT is 20% of the basic, other deductions is user specified. Compute the Gross and Net salary of the employee and update the file.

Aim:- To write a program to accept employeeid , name and basic salary .Calculate HRA,DA,IT and other deductions as per the given conditions and finally to calculate net and gross salary.

Program Description:- We accept employeeid, name and basic salalry from the user and store these details in a file. When then calculate the allowances of an employee and update the employee file by including the allowances , net and gross salaries.

Source Code:-#include<stdio.h>#include<conio.h>#include<string.h>struct employ{ int empid; char name[15]; float basic; struct allowances

{float hra;float da;float ta;float pf;float it;

} a; float net; float gross;

}emp[20];int main(){

int n,i;FILE *fp;printf("\n Enter no. of Employees :");scanf("%d",&n);printf("\n Enter Employee details :");for(i=1;i<=n;i++){

printf("\n Enter %d employee details :",i);printf("\n Employee ID :");scanf("%d",&emp[i].empid);flush(stdin);printf("Name :");

Kuppam Engineering College, Kuppam

Page 46: sonucgn.files.wordpress.com€¦  · Web view05/01/2018  · Objectives: Learn C Programming language. To make the student solve problems, implement algorithms using C language

Computer Programming Lab

gets(emp[i].name);printf("\n Basic salary :");scanf("%f",&emp[i].basic);

}for(i=1;i<=n;i++){

emp[i].a.hra= (emp[i].basic * 20) /100;emp[i].a.da= (emp[i].basic * 80) /100;emp[i].a.ta= (emp[i].basic * 12) /100;emp[i].a.pf= (emp[i].basic * 21) /100;emp[i].a.it= (emp[i].basic * 10) /100;emp[i].net= emp[i].basic + emp[i].a.hra + emp[i].a.da +emp[i] .a.ta;emp[i].gross=emp[i].net - emp[i].a.pf-emp[i].a.it;

} fp=fopen("employeeDetails.txt","w"); fputs("Details of Employee are \n",fp); fputs("Employee ID \t Name \t Basic \t HRA \t DA \t TA \t PF \t IT \t Net \t Gross\n",fp); for(i=1;i<=n;i++)

fprintf(fp,"%6d\t%15s\t%6.2f\t%6.2f\t%6.2f\t%6.2f\t%6.2f\t%6.2f%6.2f%6.2f\n", emp[i].empid , emp[i].name , emp[i].basic ,emp[i].a.hra , emp[i].a.da , emp[i].a.ta , emp[i].a.pf , emp[i].a.it , emp[i].net , emp[i].gross);

return(0);}

Output:-Details of Employee are Employee ID Name Basic HRA DA TA PF IT Net Gross 1265 Kumar 5200.00 1040.00 4160.00 624.00 1092.00 520.00 11024.00 9412.00 9586 Krishna 6300.00 1260.00 5040.00 756.00 1323.00 630.00 13356.00 11403.00

Viva Questions1. What do you mean by structure within the structure?2. How to access inner and outer structure fields when we use structures within the

structures. ?3. How to create a pointer to a structure ?4. How to access pointer fields of a structure by using a structure variable?5. Can we pass a function as a argument to another function. Justify?

20. Write a program to perform Base (decimal, octal, hexadecimal, etc) conversion.

Kuppam Engineering College, Kuppam

Page 47: sonucgn.files.wordpress.com€¦  · Web view05/01/2018  · Objectives: Learn C Programming language. To make the student solve problems, implement algorithms using C language

Computer Programming Lab

Aim:- To perform Base (decimal, octal, hexadecimal, etc) conversion

Program description: In this program we input a decimal value and we convert that decimal value into binary, octal and hexa decimal value.

Source Code:#include<stdio.h>#include<conio.h>

void dec_bin(int decimal){ int r,q,bin[20],i=1,j; q=decimal; while(q!=0) {

bin[i++]=q%2; q=q/2;

} for(j=i-1;j>0;j--) printf("%d",bin[j]);}

void dec_oct(int decimal){ int r,q,oct[10],i=1,j; q=decimal; while(q!=0) { oct[i++]= q% 8; q=q/8; } for(j=i-1;j>0;j--) printf("%d",oct[j]);}

void dec_hex(int decimal){ int r,q,i=1,j,temp; char hexa[10]; q=decimal; while(q!=0) {

temp = q % 16;

//To convert integer into character if( temp < 10) temp =temp + 48;

Kuppam Engineering College, Kuppam

Page 48: sonucgn.files.wordpress.com€¦  · Web view05/01/2018  · Objectives: Learn C Programming language. To make the student solve problems, implement algorithms using C language

Computer Programming Lab

else temp = temp + 55;

hexa[i++]= temp; q=q/16;

} for(j=i-1;j>0;j--) printf("%c",hexa[j]);

}

void main(){

int decimal,octal;char hexa[20];long int bin;clrscr();printf("\n Enter a decimal value:");scanf("%d",&decimal);printf("\n Given decimal value is=%d",decimal);printf("\n Equivalent binary value:");dec_bin(decimal);printf("\n Equivalent Octal value:");dec_oct(decimal);printf("\n Equivalent Hexa decimal value:");dec_hex(decimal);

}

Output:- Enter a decimal value:188 Given decimal value is=188 Equivalent binary value:10111100 Equivalent Octal value:274 Equivalent Hexa decimal value:BC

Viva Questions1. If a value is preceded with ‘0X’ , it can be treated as which type of value. ?2. If a value is preceded with ‘0’ , it can be treated as which type of values. ?3. If a value is preceded with U,F .what do you mean by that?4. When to use %u format specified?5. What is the difference between signed and unsigned values. ?

21. Write a program to find the square root of a number without using built-in library

Kuppam Engineering College, Kuppam

Page 49: sonucgn.files.wordpress.com€¦  · Web view05/01/2018  · Objectives: Learn C Programming language. To make the student solve problems, implement algorithms using C language

Computer Programming Lab

function.

Aim:- to find the square root of a number without using built-in library function.

Program Description:- The square root of a number can be calculated by using the following procedure

Step1 :- Estimate - First find a number that is as close as square root of a given number by finding the perfect square roots in which the given number lies between.

Step 2:- Divide – divide the number by one of those square roots

Step 3:- Average – take the average of the result of step 2 and the root

Step 4:- Use the result of step 3 to repeat step2 and step 3 until we have a number htat is accurate enough.

Ex:- To Find the square root of 10 we use the above procedure1. Find the two perfect square numbers it lies between

32=9 , 42=16 So square root(10) lies between 3 and 4

2. Divide 10 by 3 , we get 3.333. Find average of 3.33 and 3 , we get 3.16674. Repeat step 2 i.e., divide 10 by 3.1667 ,we get 3.15795. Repeat step 3 i.e., find average of 3.1579 and 3.1667we get 3.16236. Try 3.1623 , we get 3.1623 ×3.1623=10.0001

If this is accurate enough we can stop the process otherwise repeat step2 and step3.

Source Code:-

#include<stdio.h>#include<conio.h>void main(){

float i,n,temp,avg,square;clrscr();printf("\n Enter a number :");scanf("%ld",&n);if(n>0){ for(i=o;i<=n/2;i++)

{square=i*i;if(square==n){

printf("\n The Square root of %6.0f is =%6.0f”,n,i); getch();

exit(0);

Kuppam Engineering College, Kuppam

Page 50: sonucgn.files.wordpress.com€¦  · Web view05/01/2018  · Objectives: Learn C Programming language. To make the student solve problems, implement algorithms using C language

Computer Programming Lab

}if(square>n) break;

}while(1){

temp=n/I;avg=(i+temp)/2;square=avg*avg;

if(square<=n+0.0001 && square >=n-0.0001){

printf("\n The Square root of %6.2f is =%6.4f”,n,avg);break;

}i=avg;

}}

getch();}

Input :-Enter a number :42

Output:-Square Root of 42 is=6.4807

Viva Questions1. What is the use of break statement?2. What is the use of exit()?3. What is unconditional branching statement?4. What are the different types of operators available in c?5. What is the difference between && and &?

22. Write a program to convert from string to number

Kuppam Engineering College, Kuppam

Page 51: sonucgn.files.wordpress.com€¦  · Web view05/01/2018  · Objectives: Learn C Programming language. To make the student solve problems, implement algorithms using C language

Computer Programming Lab

Aim:- To convert from string to number

Program Description :- In this program we input a string which consists of digits and optionally a minus sign at beginning for integers. For string containing other characters we can stop conversion as soon as a non digit character is encountered.

Source Code:-#include<stdio.h>int stringToInt(char[] );int main(){    char str[10];    int intValue;

printf("Enter any integer as a string: ");    scanf("%s",str);   intValue = stringToInt(str);

printf("Equivalent integer value: %d",intValue);    return 0;}

int stringToInt(char str[]){    int i=0,sum=0;    while(str[i]!='\0')

{         if(str[i]< 48 || str[i] > 57)

{             printf("Unable to convert it into integer.\n");

             return 0;         }         else

{             sum = sum*10 + (str[i] - 48);             i++;         }

    }    return sum;}

Input:-

Kuppam Engineering College, Kuppam

Page 52: sonucgn.files.wordpress.com€¦  · Web view05/01/2018  · Objectives: Learn C Programming language. To make the student solve problems, implement algorithms using C language

Computer Programming Lab

Enter any integer as a string: -125Equivalent integer value: -125

Output:-Enter any integer as a string: 12A3Unable to convert it into integer.Equivalent integer value: 0

Viva Questions1. What is the ASCII value of A and a?2. What is the ASCII value for 0?3. What is the function used to identify whether a character is digit or not. ?4. What is a function prototype?5. What is the difference if we declare a function above the main and within the main. ?

23. Write a program to generate pseudo random generator.

Kuppam Engineering College, Kuppam

Page 53: sonucgn.files.wordpress.com€¦  · Web view05/01/2018  · Objectives: Learn C Programming language. To make the student solve problems, implement algorithms using C language

Computer Programming Lab

Aim:- To write a program to generate pseudo random generator

Program Description:- We use rand() to create a pseudo random generator

Source Code:-#include<stdio.h>#include<conio.h>

void main(){ int i; clrscr();

for (i = 0; i < 10; i++) {

printf("random_number[%d]= %d\n", i + 1, rand()); }

}

Output:-random_number[1]= 346random_number[2]= 130random_number[3]= 10982random_number[4]= 1090random_number[5]= 11656random_number[6]= 7117random_number[7]= 17595random_number[8]= 6415random_number[9]= 22948random_number[10]= 31126

Viva Questions1. What is the use of rand()?2. What is the difference between round(),ceil() and floor()?3. List any 8 mathematical functions?4. conio.h stands for?5. What do you mean by console?

Kuppam Engineering College, Kuppam

Page 54: sonucgn.files.wordpress.com€¦  · Web view05/01/2018  · Objectives: Learn C Programming language. To make the student solve problems, implement algorithms using C language

Computer Programming Lab

24. Write a program to express a four digit number in words. For example 1546 should be written as one thousand five hundred and forty six.

Aim:- to express four digit number in words

Program Description:- In this program , we divide the number by 10 and identify the digits in various places and write the corresponding digit in words by using the switch statement.

Source Code:-#include<stdio.h>#include<conio.h>void printword(int);void printtensword(int);void printteenword(int);

void main(){

int n,r,i,th,hun,ten,unit;clrscr();printf("\n Enter a four digit number:");scanf("%d",&n);th=n/1000;hun=(n%1000)/100;ten=(n%100)/10;unit=n%10;if(n==0) printf(" Zero ");if(th>0){ printword(th); printf("thousand");}if(hun>0){ printword(hun); printf(" hundred and ");}if(ten>1 || unit==0) printtensword(ten);if(ten==1) printteenword(unit);// it depends on unit placeif(unit>0 && ten>1) printword(unit);getch();

}void printword(int ch){ switch(ch)

Kuppam Engineering College, Kuppam

Page 55: sonucgn.files.wordpress.com€¦  · Web view05/01/2018  · Objectives: Learn C Programming language. To make the student solve problems, implement algorithms using C language

Computer Programming Lab

{case 1: printf(" One ");

break;case 2: printf(" Two ");

break;case 3: printf(" Three ");

break;case 4: printf(" Four ");

break;case 5: printf(" Five ");

break;case 6: printf(" Six ");

break;case 7: printf(" Seven ");

break;case 8: printf(" Eight ");

break;case 9: printf(" Nine ");

break; }}

void printtensword(int ch){ switch(ch) {

case 2: printf(" Twenty ");break;

case 3: printf(" Thrirty ");break;

case 4: printf(" Forty ");break;

case 5: printf(" Fifty ");break;

case 6: printf(" Sixty ");break;

case 7: printf(" Seventy ");break;

case 8: printf(" Eighty ");break;

case 9: printf(" Ninty ");break;

}}void printteenword(int ch){ switch(ch) {

case 1: printf(" Eleven ");

Kuppam Engineering College, Kuppam

Page 56: sonucgn.files.wordpress.com€¦  · Web view05/01/2018  · Objectives: Learn C Programming language. To make the student solve problems, implement algorithms using C language

Computer Programming Lab

break;case 2: printf(" Twelve ");

break;case 3: printf(" Thrirteen ");

break;case 4: printf(" Forteen ");

break;case 5: printf(" Fifteen ");

break;case 6: printf(" Sixteen ");

break;case 7: printf(" Seventeen ");

break; case 8: printf(" Eighteen ");

break;case 9: printf(" Ninteen ");

break; }}

Input:-Enter a four digit number:3265Output:- Three thousand Two hundred and Sixty Five

Viva Questions

1. What is the use of Switch Statement?

2. What is the use of default expression in a switch statement?

3. Why to use break in case of switch?

4. What are the rules for case labels?

5. What is the use of comma operator?

Kuppam Engineering College, Kuppam

Page 57: sonucgn.files.wordpress.com€¦  · Web view05/01/2018  · Objectives: Learn C Programming language. To make the student solve problems, implement algorithms using C language

Computer Programming Lab

25. Write a program to generate telephone bill as per BSNL rules

Subscribercategory

Plan details and charges

<9991000-2999

30000 – 99999

>100000

Basic

Rural

Rent 70 120 200 280Free Calls 0 0 0 0

Call Charge

1.40 1.40 1.40 1.40

Urban

Rent 140 140 180 180Free Calls 0 0 0 0

Call Charge

1.40 1.40 1.40 1.40

Economy

Same for both

Rural & Urban

Rent 300 300 300 300Free Calls 225 225 225 225

Call Charge

1.20 1.20 1.20 1.20

Special

Same for both

Rural & Urban

Rent 425 425 425 425Free Calls 400 400 400 400

Call Charge

1.10 1.10 1.10 1.10

Special Plus

Same for both

Rural & Urban

Rent 975 975 975 975Free Calls 1000 1000 1000 1000

Call Charge

1.00 1.00 1.00 1.00

Super

Same for both

Rural & Urban

Rent 1450 1450 1450 1450Free Calls 1500 1500 1500 1500

Call Charge

0.90 0.90 0.90 0.90

Premium

Same for both

Rural & Urban

Rent 2450 2450 2450 2450Free Calls 3000 3000 3000 3000

Call Charge

0.80 0.80 0.80 0.80

Sulabh

Same for both

Rural & Urban

Rent 90 90 140 140Free Calls 0 0 0 0

Call Charge

1.20 1.20 1.20 1.20

Note:- The bill amount should include monthly rent , usage charges , service tax(12%) ,education CESS (2%), Higher Education CESS (1%)

Kuppam Engineering College, Kuppam

Page 58: sonucgn.files.wordpress.com€¦  · Web view05/01/2018  · Objectives: Learn C Programming language. To make the student solve problems, implement algorithms using C language

Computer Programming Lab

Aim:- To write a program to generate the telephone bill as per BSNL rules.

Program Description:- In this program , we used nested switch statement to calculate the rent , free calls and call charge. Finally we generate the telephone bill as per the BSNL rules

Source Code:#include<stdio.h>#include<conio.h>void main(){

int ctgy,ptgy,ncalls,tcalls,free_calls;float rent,call_charge,camt,amt,stax,ecess,hcess,total;char area_type,month[20],cname[20],cadd[40];clrscr();printf("\n Subscribers Categories:");printf("\n 1. 0-999");printf("\n 2. 1000-2999");printf("\n 3. 30000-99999");printf("\n 4. above 100000");printf("\n Select the category(1-4) :");scanf("%d",&ctgy);clrscr();printf("\n Plan Categories:");printf("\n 1. Basic");printf("\n 2. Economy");printf("\n 3. Special");printf("\n 4. Special Plus");printf("\n 5. Super");printf("\n 6. Premium");printf("\n 7. Sulab");printf("\n Select the plan category(1-7) :");scanf("%d",&ptgy);flushall();printf("\n Enter the area type(r/u):");scanf("%c",&area_type);switch(ctgy){case 1: switch(ptgy)

{case 1:if(area_type=='r')

rent=70; else

rent=140; free_calls=0; call_charge=1.40; break;case 7:rent=90;

Kuppam Engineering College, Kuppam

Page 59: sonucgn.files.wordpress.com€¦  · Web view05/01/2018  · Objectives: Learn C Programming language. To make the student solve problems, implement algorithms using C language

Computer Programming Lab

free_calls=0; call_charge=1.20; break;

}case 2: switch(ptgy)

{case 1:if(area_type=='r')

rent=120; else

rent=140; free_calls=0; call_charge=1.40; break;case 7:rent=90; free_calls=0; call_charge=1.20; break;}

case 3: switch(ptgy){

case 1:if(area_type=='r') rent=200;

else rent=180;

free_calls=0; call_charge=1.40; break;case 7:rent=140; free_calls=0; call_charge=1.20; break;

}case 4: switch(ptgy)

{case 1:if(area_type=='r')

rent=280; else

rent=180; free_calls=0; call_charge=1.40; break;case 7:rent=140; free_calls=0; call_charge=1.20; break;

}}switch(ptgy){

Kuppam Engineering College, Kuppam

Page 60: sonucgn.files.wordpress.com€¦  · Web view05/01/2018  · Objectives: Learn C Programming language. To make the student solve problems, implement algorithms using C language

Computer Programming Lab

case 2: rent=300;free_calls=225;call_charge=1.20;break;

case 3: rent=425;free_calls=400;call_charge=1.10;break;

case 4: rent=975;free_calls=1000;call_charge=1.00;break;

case 5: rent=1450;free_calls=1500;call_charge=0.90;break;

case 6: rent=2450;free_calls=3000;call_charge=0.80;break;

} flushall(); printf("\n Enter the customer name :"); gets(cname); printf("\n Enter the customer address :"); gets(cadd); printf("\n Enter billing month:"); scanf("%s",month); printf("\n Enter number of calls made during the month:"); scanf("%d",&ncalls); tcalls=ncalls-free_calls; if(tcalls<0)

tcalls=0; camt=tcalls*call_charge; amt=rent+camt; stax=(amt*12)/100; ecess=(amt*2)/100; hcess=(amt*1)/100; total=rent+camt+stax+ecess+hcess; clrscr(); printf("\n BHARAT SANCHAR NIGAM LTD."); printf("\n TELEPHONE BILL"); printf("\n Customer Name:"); puts(cname); printf("\n Customer Address:");

Kuppam Engineering College, Kuppam

Page 61: sonucgn.files.wordpress.com€¦  · Web view05/01/2018  · Objectives: Learn C Programming language. To make the student solve problems, implement algorithms using C language

Computer Programming Lab

puts(cadd); printf("\n Billing Month :"); puts(month); printf(" \n Summary of Charges \t Amount"); printf("\n Monthly Rent \t%6.2f",rent); printf("\n No. of free calls \t%6d",free_calls); printf("\n No.of Calls Made \t%6d",ncalls); printf("\n Usage Charges \t%6.2f",camt); printf("\n Service Tax \t%6.2f",stax); printf("\n Education CESS \t%6.2f",ecess); printf("\n Higher Edu. CESS \t%6.2f",hcess); printf("\n Total Charges \t%6.2f",total); getch();

}

Kuppam Engineering College, Kuppam

Page 62: sonucgn.files.wordpress.com€¦  · Web view05/01/2018  · Objectives: Learn C Programming language. To make the student solve problems, implement algorithms using C language

Computer Programming Lab

Input:- Subscribers Categories: 1. 0-999 2. 1000-2999 3. 30000-99999 4. above 100000 Select the category(1-4) :2 Plan Categories: 1. Basic 2. Economy 3. Special 4. Special Plus 5. Super 6. Premium 7. Sulab Select the plan category(1-7) :4 Enter the area type(r/u):u Enter the customer name :K.Subba Reddy Enter the customer address :3-25, Gandhi road , Madanapalle Enter billing month:January-2014 Enter number of calls made during the month:2258

Output:- BHARAT SANCHAR NIGAM LTD. TELEPHONE BILL Customer Name:K.Subba Reddy Customer Address:3-25,Gandhi Road, Madanapalle Billing Month :January-2014 Summary of Charges Amount Monthly Rent 975.00 . No. of free calls 1000 No.of Calls Made 2258 Usage Charges 1258.00 Service Tax 267.96 Education CESS 44.66 Higher Edu. CESS 22.33 Total Charges 2567.95

Viva Questions

1. C is structured programming language Justify?

2. What is the difference between top-down and bottom-up approaches?

3. Write the structure a c-program?

4. What is a macro substitution directive?

5. What is the use of #define. ?

Kuppam Engineering College, Kuppam

Page 63: sonucgn.files.wordpress.com€¦  · Web view05/01/2018  · Objectives: Learn C Programming language. To make the student solve problems, implement algorithms using C language

Computer Programming Lab

26. Write a program to find the execution time of a program.

Aim:- To find the execution time of a program

Program Description:- In this program we find the execution time by starting the clock at beginning of the task and ending the clock at end of task.

Source Code:-#include<stdio.h>#include<time.h>void main(){ int i;

double total_time; clock_t start, end; clrscr(); start = clock();//time count starts

srand(time(NULL)); for (i = 0; i < 25000; i++) {

printf("random_number[%d]= %d\n", i + 1, rand()); }

end = clock();//time count stops total_time = ((double) (end - start)) / CLK_TCK;//calulate total time printf("\nTime taken to print 25000 random numbers is: %6.4f seconds", total_time); return 0;

}

Kuppam Engineering College, Kuppam

Page 64: sonucgn.files.wordpress.com€¦  · Web view05/01/2018  · Objectives: Learn C Programming language. To make the student solve problems, implement algorithms using C language

Computer Programming Lab

Output:-random_number[1]= 26367random_number[2]= 22547random_number[3]= 26102random_number[4]= 8734random_number[5]= 18502

:::

random_number[24997]= 23216random_number[24998]= 29173random_number[24999]= 13056random_number[25000]= 7925

Time taken to print 25000 random numbers is: 17.5275 seconds

Viva Questions1. What are different functions available in time.h?2. What is an algorithm?3. What are the different categories of algorithms?4. What is a flow chart?5. What are the different steps involved in software development life cycle?

Kuppam Engineering College, Kuppam

Page 65: sonucgn.files.wordpress.com€¦  · Web view05/01/2018  · Objectives: Learn C Programming language. To make the student solve problems, implement algorithms using C language

Computer Programming Lab

27. Design a file format to store a person's name, address, and other information. Write a program to read this file and produce a set of mailing labels

Aim:- To write a c program which accepts person’s name, address ,mobile no., etc and store these details in a file. Read the contents of the file and print the details in a label format.

Program Description:-The program accept the details of a person and store the details in a file. Then the file is

opened in a read mode and print the contents in a label format.

Source Code#include<stdio.h>#include<string.h>struct person{ char name[15]; char dno[15];

char street[15]; char city[15]; long int pincode; double mobileno;}s[20];int main(){

int n,i,j;long int pin;double mob;char pname[15],d[15],strt[15],c[15];FILE *fp;fp=fopen("person.txt","w");printf("\n Enter no. of Persons :");scanf("%d",&n);printf("\n Enter Person details :");for(i=1;i<=n;i++){

printf("\n Enter %d person details :\n",i);printf("Name :");scanf("%s",s[i].name);printf("Door No :");scanf("%s",s[i].dno);printf("Street : ");scanf("%s",s[i].street);printf("City :");scanf("%s",s[i].city);printf("Pincode : ");scanf("%ld",&s[i].pincode);printf("Mobile No :");scanf("%lf",&s[i].mobileno);

Kuppam Engineering College, Kuppam

Page 66: sonucgn.files.wordpress.com€¦  · Web view05/01/2018  · Objectives: Learn C Programming language. To make the student solve problems, implement algorithms using C language

Computer Programming Lab

fprintf(fp,"%15s%15s%15s%15s%12ld%12.0lf\n",s[i].name,s[i].dno,s[i].street,s[i].city,s[i].pincode,s[i].mobileno); } fclose(fp); printf("Mailing Labels"); fp=fopen("person.txt","r"); for(i=1;i<=n;i++)

{printf("\n");for(j=1;j<=25;j++)

printf("_");printf("\n|");fscanf(fp,"%s",pname);printf("%20s|",pname);printf("\n|");fscanf(fp,"%s",d);printf("%20s|",d);printf("\n|");fscanf(fp,"%s",strt);printf("%20s|",strt);printf("\n|");fscanf(fp,"%s",c);printf("%20s|",c);printf("\n|");fscanf(fp,"%ld",&pin);printf("%-20ld|",pin);printf("\n|");fscanf(fp,"%lf",&mob);printf("%-20.0lf|",mob);printf("\n");for(j=1;j<=25;j++)

printf("_");printf("\n");

}return 1;

}

Kuppam Engineering College, Kuppam

Page 67: sonucgn.files.wordpress.com€¦  · Web view05/01/2018  · Objectives: Learn C Programming language. To make the student solve problems, implement algorithms using C language

Computer Programming Lab

Output:-Enter no. of Persons :2Enter Person details :

Enter 1 person details :Name :rajuDoor No :2-34Street : Nehru-streetCity :MadanapallePincode : 517325Mobile No :9876543210

Enter 2 person details :Name :KiranDoor No :34-56Street : Tagore-streetCity :MadanapallePincode : 517325Mobile No :9638527410

Mailing Labels_________________________| raju|| 2-34|| Nehru-street| | Madanapalle||517325 ||9876543210 |__________________________________________________| Kiran|| 34-56|| Tagore-street|| Madanapalle||517325 ||9638527410 |

Viva Questions

1. What are bit fields?

2. What is the use of type def?

3. What is the use of variable length parameter list?

4. C program execution starts from where?

5. Main is a keyword or not. Justify?

Kuppam Engineering College, Kuppam