Program 27-40

 

PPS LAB RECORD PROGRAMS

 

1.     Write a C program that converts a string representing a number in Roman numeral form to decimal form.

[Follow regular convention for Roman numbers, Read string – parse it to convert in to decimal] Eg:

Input: XL output: 40

Ans:

Program: Program to convert Roman numeral to Decimal number.

// Program to convert Roman Numerals to Numbers

#include<stdio.h>

#include<string.h>

int value(char);

intromanToDecimal(char[]);

// Driver Program

int main(void)

{

charstr[10];

intnum;

printf("Enter Roman Number:");

scanf("%s",str);

num=romanToDecimal(str);

printf("Integer form of Roman Numeral is: %d",num);

return 0;

}

// This function returns value of a Roman symbol

int value(char r)

{

if (r == 'I')

return 1;

if (r == 'V')

return 5;

if (r == 'X')

return 10;

if (r == 'L')

return 50;

if (r == 'C')

return 100;

if (r == 'D')

return 500;

if (r == 'M')

return 1000;

return -1;

}

// Returns decimal value of roman numaral

intromanToDecimal(char str[])

{

// Initialize result

int i, res = 0;

// Traverse given input

for (i=0; i<strlen(str); i++)

{

// Getting value of symbol s[i]

int s1 = value(str[i]);

if (i+1 <strlen(str))

{

// Getting value of symbol s[i+1]

int s2 = value(str[i+1]);

// Comparing both values

if (s1 >= s2)

{

// Value of current symbol is greater

// or equal to the next symbol

res = res + s1;

}

else

{

res = res + s2 - s1;

i++; // Value of current symbol is

// less than the next symbol

}

}

else

{

res = res + s1;

}

}

return res;

}

Output:

Enter Roman Number: XI

Integer form of Roman Numeral is: 11

2.     WriteaCProgramto count number of vowels, words, blanks in a given string.

3.  #include <stdio.h>

4.  intmain() {

5.   

6.  char line[150];

7.  int vowels, consonant, digit, space;

8.   

9.  // initialize all variables to 0

10.  vowels = consonant = digit = space = 0;

11. 

12.// get full line of string input

13.printf("Enter a line of string: ");

14.fgets(line, sizeof(line), stdin);

15. 

16.// loop through each character of the string

17.for (int i = 0; line[i] != '\0'; ++i) {

18. 

19.// convert character to lowercase

20.    line[i] = tolower(line[i]);

21. 

22.// check if the character is a vowel

23.if (line[i] == 'a' || line[i] == 'e' || line[i] == 'i' ||

24.        line[i] == 'o' || line[i] == 'u') {

25. 

26.// increment value of vowels by 1

27.      ++vowels;

28.    }

29. 

30.// if it is not a vowel and if it is an alphabet, it is a consonant

31.elseif ((line[i] >= 'a'&& line[i] <= 'z')) {

32.      ++consonant;

33.    }

34. 

35.// check if the character is a digit

36.elseif (line[i] >= '0'&& line[i] <= '9') {

37.      ++digit;

38.    }

39. 

40.// check if the character is an empty space

41.elseif (line[i] == ' ') {

42.      ++space;

43.    }

44.  }

45. 

46.printf("Vowels: %d", vowels);

47.printf("\nConsonants: %d", consonant);

48.printf("\nDigits: %d", digit);

49.printf("\nWhite spaces: %d", space);

50. 

51.return0;

52.}

 

3.     WriteaCProgramto check whether a given string is a palindrome or not.

4.     #include<stdio.h>
5.     #include<string.h>
6.      
7.     intmain(){
8.     char string1[20];
9.     int i, length;
10.  int flag =0;
11.   
12.  printf("Enter a string:");
13.  scanf("%s", string1);
14.   
15.      length =strlen(string1);
16.   
17.  for(i=0;i < length ;i++){
18.  if(string1[i]!= string1[length-i-1]){
19.              flag =1;
20.  break;
21.  }
22.  }
23.   
24.  if(flag){
25.  printf("%s is not a palindrome", string1);
26.  }
27.  else{
28.  printf("%s is a palindrome", string1);
29.  }
30.  return0;
31.  }

 

 

 

4.     WriteaCProgramto read a string and converts alphabets from lower case letters to capital letters.

#include<stdio.h>
#include<string.h>
 
int main(){
   char s[100];
   int i;
   printf("\nEnter a string : ");
   gets(s);
 
   for(i =0; s[i]!='\0'; i++){
      if(s[i]>='a'&& s[i]<='z'){
         s[i]= s[i]-32;
      }
   }
   printf("\nString in Upper Case = %s", s);
   return0;
}

 

5.     A.WriteaCprogram to find second maximum in an array using functions.

 

#include<stdio.h>
void main(){
   inti,j,a,n,counter,ave,number[30];
   printf("Enter the value of N
");
   scanf("%d",&n);
   printf("Enter the numbers 
");
   for(i=0; i<n;++i)
      scanf("%d",&number[i]);
   for(i=0; i<n;++i){
      for(j=i+1; j<n;++j){
         if(number[i]< number[j]){
            a = number[i];
            number[i]= number[j];
            number[j]= a;
         }
      }
   }
   printf("The numbers arranged in descending order are given below
");
   for(i=0; i<n;++i)
      printf("%10d
",number[i]);
   printf("The 2nd largest number is = %d
", number[1]);
   printf("The 2nd smallest number is = %d
", number[n-2]);
   ave=(number[1]+number[n-2])/2;
   counter=0;
   for(i=0; i<n;++i){
      if(ave==number[i])
         ++counter;
   }
   if(counter==0)
      printf("The average of 2nd largest & 2nd smallest is not in the array
");
   else
      printf("The average of 2nd largest & 2nd smallest in array is %d in numbers
", counter);
}

 

B.    Write a C program to check whether a given matrix is identity matrix or not.

 

/*

* C Program to check if a given matrix is an identity matrix

*/

#include <stdio.h>

 

int main (void)

{

  int a[10][10];

  int i =0, j =0, row =0, col =0;

 

  printf("Enter the order of the matrix (mxn):\n");

  printf("where m = number of rows; and\n");

  printf("      n = number of columns\n");

  scanf("%d %d",&row,&col);

 

  int flag =0;

 

  printf("Enter the elements of the matrix\n");

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

  {

         for(j =0; j < col; j++)

         {

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

         }

  }

 

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

  {

         for(j =0; j < col; j++)

         {

                 if(i == j && a[i][j]!=1)

                 {

                         flag=-1;

                         break;

                 }

                 elseif(i != j && a[i][j]!=0)

                 {

                         flag=-1;

                         break;

                 }

         }

  }

 

  if(flag ==0)

  {

         printf("It is a IDENTITY MATRIX\n");

  }

  else

  {

         printf("It is NOT an identity matrix\n");

  }

 

  return0;

}

 

6.     Write a C program for linear search & binary search usingrecursive& non-recursiveprocedures.

A)LinearSearch:

 

#include <stdio.h>#defineMAX_LEN10

 

voidl_search_nonrecursive(intl[],intnum,intele);voidl_search_recursive(intl[],intnum,intele);

 

voidread_list(int l[],intnum);void print_list(int l[],intnum);voidmain()

{

int l[MAX_LEN], num, ele;intch;

clrscr();printf("======================================================");

printf("\n\t\t\tMENU");printf("\n====================================================");

printf("\n[1] Linear Search using Recursion method");printf("\n[2] Linear Search using Non-Recursion method");printf("\n\nEnteryour Choice:");

scanf("%d",&ch);if(ch<=2&ch>0)

{

printf("Enterthenumberofelements:");scanf("%d",&num);

read_list(l,num);

printf("\nElements present in the list are:\n\n");print_list(l,num);

printf("\n\nElement you want to search:\n\n");scanf("%d",&ele);

switch(ch)

{

case1:printf("\n**Recursionmethod**\n");

 

l_search_recursive(l,num,ele);getch();

break;

case 2:printf("\n**Non-Recursion method**\n");l_search_nonrecursive(l,num,ele);

getch();break;

}

}

getch();

 

}

 

/*endmain*/

 

/*Non-Recursivemethod*/

 

voidl_search_nonrecursive(intl[],intnum,intele)

{

int j, f=0;for(j=0;j<num;j++)if(l[j] ==ele)

{

printf("\nThe element %d is present at position %d in list\n",ele,j);f=1;

break;

}

if(f==0)

printf("\nTheelementis%dis notpresentin thelist\n",ele);

}

/*Recursivemethod*/

voidl_search_recursive(intl[],intnum,intele)


 

 

{

int f =0;

if(l[num]== ele)

{

printf("\nThe element %d is present at position %d in list\n",ele,num);f=1;

}

else

{

if((num==0)&&(f==0))

 

{

printf("Theelement%d isnotfound.",ele);

}

else

{

l_search(l,num-1,ele);

}

}

getch();

}

voidread_list(intl[],intnum)

{

int j;

printf("\nEnter the elements:\n");for(j=0;j<num;j++)scanf("%d",&l[j]);

}

voidprint_list(int l[],intnum)

{

int j;for(j=0;j<num;j++)printf("%d\t",l[j]);

}

 

Output:

Enter the number of elements:6Enter6 integer(s)

12 45 78 89 34 56

Enterthenumbertosearch78

78ispresentatlocation3.


 

 

A)   BinarySearch:

 

#include <stdio.h>#defineMAX_LEN10

/*Non-Recursivefunction*/

voidb_search_nonrecursive(intl[],intnum,intele)

{

int l1,i,j, flag = 0;l1 = 0;

i = num-1;while(l1<=i)

{

j = (l1+i)/2;if(l[j]==ele)

{

printf("\nTheelement%dispresentatposition%d inlist\n",ele,j);flag=1;break;

}

else

if(l[j]<ele)l1= j+1;

else

i= j-1;

}

if(flag ==0)

printf("\nTheelement %dis notpresent inthe list\n",ele);

}

/*Recursivefunction*/

intb_search_recursive(intl[],intarrayStart,intarrayEnd,inta)

{

 

intm,pos;

if(arrayStart<=arrayEnd)

{

m=(arrayStart+arrayEnd)/2;if(l[m]==a)

returnm;

elseif(a<l[m])

returnb_search_recursive(l,arrayStart,m-1,a);else

returnb_search_recursive(l,m+1,arrayEnd,a);

}

return-1;

 

}

voidread_list(intl[],intn)


 

 

{

int i;

 

printf("\nEnter theelements:\n");

 

for(i=0;i<n;i++)scanf("%d",&l[i]);

}

voidprint_list(int l[],intn)

{

int i;for(i=0;i<n;i++)printf("%d\t",l[i]);

 

}

/*mainfunction*/main()

{

int l[MAX_LEN], num, ele,f,l1,a;intch,pos;

//clrscr();printf("======================================================");

printf("\n\t\t\tMENU");

printf("\n====================================================");

printf("\n[1]BinarySearch usingRecursionmethod");

printf("\n[2] Binary Search using Non-Recursion method"); printf("\n\nEnter yourChoice:");scanf("%d",&ch);

if(ch<=2&ch>0)

{

printf("\nEnter the number of elements : ");scanf("%d",&num);

read_list(l,num);

printf("\nElements present in the list are:\n\n");print_list(l,num);

printf("\n\nEnter the element you want to search:\n\n");scanf("%d",&ele);

 

switch(ch)

 

{

case 1:printf("\nRecursive method:\n");pos=b_search_recursive(l,0,num,ele);


 

 

if(pos==-1)

{

printf("Elementisnotfound");

 

}

else

 

{

 

printf("Elementisfoundat%dposition",pos);

 

}

 

//getch();break;

case 2:printf("\nNon-Recursive method:\n");b_search_nonrecursive(l,num,ele);

//getch();break;

}

 

}

 

//getch();

}

 

Output:

======================================================MENU

=====================================================

[1]    BinarySearchusingRecursionmethod

[2]    Binary Search using Non-Recursion methodEnteryour Choice:1

Enter the number of elements : 5Enter the elements: 1 3 5 6 2Elementspresentinthelistare:

1          3          5          6          2

Entertheelementyouwanttosearch:4Recursivemethod:

Elementis not found

 

======================================================MENU

=====================================================


 

 

[1]    BinarySearchusingRecursionmethod

[2]    Binary Search using Non-Recursion methodEnteryour Choice:2

Enter the number of elements : 4Enter the elements: 1 2 3 4Elementspresentinthelistare:

1          2          3          4

Entertheelementyouwanttosearch:3Non-Recursivemethod:

TheElement 3 is found at position 2 in list

 

7.     WriteaCProgramtoimplementBubbleSort&Selection Sort.

 

A)      BubbleSort:

 

#include<stdio.h>main()

{

inta[50],n,i,j,temp;

 

printf("Enterthesizeofarray:");scanf("%d",&n);

printf("Enter %darray elements: ",n);for(i=0;i<n;++i)

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

 

printf("\nArray elements before sorting: ");for(i=0;i<n;i++)

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

 

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

{

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

{

if(a[j]>a[j+1])

{

temp=a[j];a[j]=a[j+1];a[j+1]=temp;

}

}

}

 

printf("\nArrayelements aftersorting:");


 

 

for(i=0;i<n;i++)printf("%d",a[i]);

 

printf("\n");

}

 

Output:

Enterthesizeofarray: 5

Enter5array elements: 1267 3489 245

Arrayelements beforesorting:12 6734 89 245

Arrayelementsafter sorting:1234 6789245

 

B)      SelectionSort:

 

#include<stdio.h>main()

{

inta[50],n,i,j,temp;

 

printf("Enterthesizeofarray:");scanf("%d",&n);

printf("Enter %darray elements: ",n);for(i=0;i<n;++i)

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

 

printf("\nArray elements before sorting: ");for(i=0;i<n;i++)

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

 

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

{

for(j=i+1;j<n;j++)

{

if(a[i]>a[j])

{

temp=a[i];a[i]=a[j];a[j]=temp;

}

}

}

printf("\nArrayelementsaftersorting:");for(i=0;i<n;i++)

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


 

 

printf("\n");

}

Output:

Enterthesizeofarray: 6

Enter6array elements: 3478 12 9045 87

 

Arrayelements beforesorting:34 78 1290 45 87

Arrayelements aftersorting: 12 3445 7887 90

 

8.     Write a C program to write a sum function.

Text Box: #include<conio.h>

#include<stdio.h>

voidmain(){

Text Box: int num1, num2, res;

Text Box: printf("\nEnterthetwonumbers:");

scanf("%d%d",&num1,&num2);

 


//CallFunctionSumWithTwoParameters

getch();

Text Box: }

Text Box: int sum(intnum1,intnum2){

intnum3;

Text Box: num3 =num1 +num2;

return(num3);

}

 

9.     WriteaCprogramtointerchange(swap)twonumbers with andwithoutusingthird variables.

#include<stdio.h>  

 int main()    

{    

int a=10, b=20;      

printf("Before swap a=%d b=%d",a,b);      

a=a+b;//a=30 (10+20)    

b=a-b;//b=10 (30-20)    

a=a-b;//a=20 (30-10)    

printf("\nAfter swap a=%d b=%d",a,b);    

return 0;  

}   

Using third variable---

#include <stdio.h>

int main()

{

int var1, var2, temp;

printf("Enter two integersn");

scanf("%d%d", &var1, &var2);

printf("Before SwappingnFirst variable = %dnSecond variable = %dn", var1, var2);

temp = var1;

var1 = var2;

var2 = temp;

printf("After SwappingnFirst variable = %dnSecond variable = %dn", var1, var2);

return 0;

}

10.  WriteaCprogram to calculate volume of the following shapes ----- Cube, Cuboid, and Cone. Take appropriate input and calculate any one of them a t a time.

Input should be taken in main () and calculation of each volume should be done in separate function by passing arguments.

11.  Write a C program that uses recursion to find: Factorial, Fibonacci, and GCD.

A)      ComputeFibonacciseriesusingrecursion.

 

#include<stdio.h>intfib(int x);main()

{

inti,r,n;

printf("Enter number of terms to print \n");scanf("%d",&n);

printf("Fibonacci series is :\n");for(i=0;i<n;i++)

{


 

 

r=fib(i);printf("%5d",r);

}

printf("\n");

}

intfib(int x)

{

int f;

if(x==0)return(0);

elseif(x==1)return(1);

else

f= fib(x-1)+fib(x-2);return(f);

}

 

Output:

Enter number of terms to print10Fibonacciseries is :

0    1    1    2    3    5    813   21   34

 

Enternumberoftermstoprint15

Fibonacciseriesis:

0    1    1    2    3    5    813   21   34   55   89144233377

 

B)   ComputeGCDusingRecursion.

 

#include<stdio.h>

intfindgcd(int x,int y);

 

main()

{

intn1,n2,gcd;

printf("\nEntertwonumbers:");scanf("%d %d",&n1,&n2);gcd=findgcd(n1,n2);

printf("\nGCDof%dand%dis:%d\n\n",n1,n2,gcd);

}

 

intfindgcd(intx,inty)

{

while(x!=y)

{

if(x>y)


 

 

return(findgcd(x-y,y));else

return(findgcd(x,y-x) );

}

returnx;

}

 

Output:

Entertwonumbers:

366

60

GCDof366 and 60 is: 6

 

Entertwonumbers:

24

64

GCDof24 and 64 is: 8

 

 

C)ComputeFactorialusingRecursion.

 

#include <stdio.h>longintfact(intn);

 

main()

{

int n;

printf("\nEnterapositiveinteger:");scanf("%d",&n);

printf("\nFactorialof%d=%ld\n",n,fact(n));

}

 

longintfact(intn)

{

if (n >=1)

return ( n*fact(n-1) );else

return1;

}

 

Output:

Enterapositiveinteger:5Factorialof 5 =120

 

Enterapositiveinteger: 10


 

 

Factorialof 10 =3628800

 

12.  WriteaCProgramto implementStructures&Unions.

 

a)Structures:

 

#include<stdio.h>voidmain()

{

struct

{

int htno,m1,m2,m3;charsname[20];

}

stud;clrscr();

printf("Enter the hallticketno,name of the student and three subject marks\n");scanf("%d%s%d%d%d",&stud.htno,stud.sname,&stud.m1,&stud.m2,&stud.m3);printf("hallticketno of thestudent is %d\n",stud.htno);

printf("name of the student is %s\n",stud.sname);printf("marks in maths is %d\n",stud.m1);printf("marks in physics is %d\n",stud.m2);printf("marks in computer science is %d\n",stud.m3);getch();

}

 

Output:

Enterthehallticketno,name ofthe studentand threesubject marks36

Ali60

40

50

hallticket no of the student is 36nameofthe student isali

marks in maths is 60marksinphysicsis40

marksincomputerscienceis50

 

(a)     Unions:#include <stdio.h>#include<string.h>

 

unionstudent

{

charname[20];


 

 

charsubject[20];floatpercentage;

};

 

intmain()

{

unionstudentrecord1;unionstudentrecord2;

 

//assigningvaluestorecord1unionvariablestrcpy(record1.name, "Raju");strcpy(record1.subject, "Maths");record1.percentage=86.50;

 

printf("Union record1 values example\n");printf(" Name: %s \n", record1.name);printf("Subject:%s\n",record1.subject);

printf("Percentage: %f\n\n",record1.percentage);

 

// assigning values to record2 union variableprintf("Union record2 values example\n");strcpy(record2.name,"Mani");

printf("Name    :%s \n", record2.name);

 

strcpy(record2.subject,"Physics");

printf("Subject:%s \n",record2.subject);

 

record2.percentage= 99.50;

printf(" Percentage : %f \n", record2.percentage);return0;

}

 

Output:

Union record1 values exampleName:

Subject:

Percentage:86.500000;Union record2 values exampleName: Mani


 

 

Subject : PhysicsPercentage:99.500000

 

 

 

 

13.  Writeaprogramtofindthestudentwhogets themaximummarksinclassusingastructuredefinitionforstudents.

Program to print the details of students who got highest marks in the class.

//Array of Structures Without Functions

#include<stdio.h>

typedefstruct

{

int S_ID;

char name[20];

intmid_marks[3];

int sum;

}STUDENT;

int main(void)

{

STUDENT std[60];

int i, max=0;

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

{

std[i].S_ID=19001+i;

printf("\nEnter %d Student Details...",std[i].S_ID);

printf("\nEnter Student Name:");

scanf("%s",std[i].name);

printf("\nEnter 3-subjects marks:");

scanf("%d %d %d",&std[i].mid_marks[0], &std[i].mid_marks[1], &std[i].mid_marks[2]);

std[i].sum=(std[i].mid_marks[0]+std[i].mid_marks[1]+std[i].mid_marks[2])/3;

}

printf("\n***Student who got highest marks***\n");

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

if(std[i].sum>max)

max=std[i].sum;

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

{

if(std[i].sum == max)

{

printf("\n%d Student Details...",std[i].S_ID);

printf("\nStudent Name: %s",std[i].name);

printf("\n3-Subjects Marks: %d %d %d", std[i].mid_marks[0], std[i].mid_marks[1], std[i].mid_marks[2]);

printf("\nSum of Marks: %d", std[i].sum);

}

}

getch();

return 0;

}

Output:

Enter 19001 Student Details...

Enter Student Name: Sam

Enter 3-subjects marks:20 11 12

Enter 19002 Student Details...

Enter Student Name: John

Enter 3-subjects marks:20 20 20

Enter 19003 Student Details...

Enter Student Name:Paul

Enter 3-subjects marks:18 17 16

***Student who got highest marks***

19002 Student Details...

Student Name: John

3-Subjects Marks: 20 20 20

Sum of Marks: 60

 

14.  Createastructuretospecifydataofcustomersinabank.Thedatatobestored is:Accountnumber, Name, Balance in Account. Assume maximum of 50 customers in the bank. Write afunctiontoprintaccountnumberandnameofeachcustomerwithbalancebelowRs. 1000.

#include<stdio.h>

typedefstruct

{

intacc_no;

char name[20];

floatacc_bal;

}CUSTOMER;

voidreadCustomer(CUSTOMER*);

voidprintCustomer(CUSTOMER*);

int main(void)

{

CUSTOMER cst[50];

int i;

system("cls"); //clrscr();

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

{

cst[i].acc_no=19001+i;

readCustomer(&cst[i]);

}

printf("***Customers with account balance less than 1000 are***\n");

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

printCustomer(&cst[i]);

getch();

return 0;

}

voidreadCustomer(CUSTOMER* tcst)

{

printf("\nEnter %d Customer Details...",tcst->acc_no);

printf("\nEnter Student Name:");

scanf("%s",tcst->name);

printf("\nEnter Account Balance:");

scanf("%f",&tcst->acc_bal);

}

voidprintCustomer(CUSTOMER* tcst)

{

if(tcst->acc_bal<1000)

{

printf("\n%d Customer Details...",tcst->acc_no);

printf("\nCustomer Name: %s",tcst->name);

printf("\nAccount Balance: %f", tcst->acc_bal);

}

}

Output:

Enter 19001 Customer Details...

Enter Student Name: John

Enter Account Balance:1200

Enter 19002 Customer Details...

Enter Student Name: Sam

Enter Account Balance:900

.

.

***Customers with account balance less than 1000 are***

19002 Customer Details...

Customer Name: Sam

Account Balance: 900.000000

 

 

Comments

Popular posts from this blog