Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

C Manual

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 53

Department of Computer Science and Engineering CS8261-C PROGRAMMING

LAB

Exp No: 1 Date of Exp:


Programs using I/O statements and expressions

Aim:
Write C programs using I/O statements and expressions.

Algorithm:
1.Start the program
2.Enter into C editor
3.declare the variable needed for each program
4.get string using gets() and print using puts().
5.perform addition operation using expression
6.Run the program and get output.
7.stop the program.

Programs:

1)a.program using gets,puts:

#include<stdio.h>
#include<conio.h>
#include <string.h>
void main()
{
char name[50];
clrscr();
printf("Enter your name: ");
gets(name); //reads string from user
printf("Your name is: ");
puts(name); //displays string
getch(); }
Output :
Department of Computer Science and Engineering CS8261-C PROGRAMMING
LAB

b)programs using expressions

#include<stdio.h>
#include<conio.h>
Void main()
{
int a, b, c;
clrscr();

printf("Enter two numbers to add\n");


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

c = a + b;

printf("Sum of the numbers = %d\n", c);

getch();
}
Output:
Department of Computer Science and Engineering CS8261-C PROGRAMMING
LAB

Result:

Thus the above programs for using I/O statements and expressions were executed successfully.

Questions for Viva – Voce


Sl. No. Questions Marks Awarded
1 What is scanf() function
2 What is printf() function
3 What is get() method in c
4 What is get() method in c
5 .List a few conditional statements in C

Date of Submission:

Marks awarded: / 15

Sign. of Faculty
Department of Computer Science and Engineering CS8261-C PROGRAMMING
LAB

Exp No: 2 Date of Exp:


Programs using decision-making constructs

Aim:
Write C programs using decision making constructs.

Algorithm:

1.Start the program.


2.Enter into C editor.
3.Declare the variables.
4.Perform the operations using decision making constructs(if, if…else, conditional operator,
switch, goto).
5.Run the program and get the result.
6.Stop the program.

1)if:

#include <stdio.h>

#include<conio.h>

void main( )

int x, y;

x = 15;

y = 13;

clrscr();

if (x > y )

printf("x is greater than y");

getch();

}
Department of Computer Science and Engineering CS8261-C PROGRAMMING
LAB

Output:

2)if..else:

#include <stdio.h>

#include<conio.h>

void main( )

int x, y;

x = 15;

y = 18;

clrscr();

if (x > y )

printf("x is greater than y");

else

printf("y is greater than x");

getch();

}
Department of Computer Science and Engineering CS8261-C PROGRAMMING
LAB

Output:

3)conditional operator:

#include <stdio.h>
#include<conio.h>
void main()
{
int x=1,y;
clrscr();
y=(x==1?2:0);
printf("x value is %d\n",x);
printf("y value is %d",y);
getch();
}

Output:

4)switch statement:

#include<stdio.h>

void main( )

int a, b, c, choice;

while(choice != 3)

{
Department of Computer Science and Engineering CS8261-C PROGRAMMING
LAB

/* Printing the available options */

printf("\n 1. Press 1 for addition");

printf("\n 2. Press 2 for subtraction");

printf("\n Enter your choice");

/* Taking users input */

scanf("%d", &choice);

switch(choice)

case 1:

printf("Enter 2 numbers");

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

c = a + b;

printf("%d", c);

break;

case 2:

printf("Enter 2 numbers");

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

c = a - b;

printf("%d", c);

break;

default:

printf("you have passed a wrong key");

printf("\n press any key to continue");

}
Department of Computer Science and Engineering CS8261-C PROGRAMMING
LAB

Output:

5)goto:

#include<stdio.h>

#include<conio.h>

void main()

int age;

clrscr();

g: //label name

printf("you are Eligible\n");

s: //label name printf("you are not Eligible");

printf("Enter your age:");

scanf("%d",&age);

if(age>=18)

goto g;//goto label g

else
Department of Computer Science and Engineering CS8261-C PROGRAMMING
LAB

goto s; //goto label s

getch();

Output:

Result:

Thus the above programs for using decision making constructs were executed successfully.

Questions for Viva – Voce


Sl. No. Questions Marks Awarded
1 What is decision making statements
2 What are the basic data types associated with C
3 What is a keyword
4 What is a variable
5 Explain the working of break and continue

Date of Submission:

Marks awarded: / 15

Sign. of Faculty
Department of Computer Science and Engineering CS8261-C PROGRAMMING
LAB

Exp No: 3 Date of Exp:


To find whether the given year is leap year or Not

Aim:
Write a C program to find whether the given year is leap year or Not

Algorithm:
1.Start a program
2.Enter into C editor
3.Declare the variable year
4.Get entered year
5. check the condition year%4==0 and year%100!=0 or year%400=0
6. if the condition is true,print the given year is a leap year
7. Otherwise the given year is not a leap year.
8. Run the program
9. Stop

Program:

#include <stdio.h>
#include <conio.h>
void main()
{
  int year;
  clrscr();
  printf("Enter the Year (YYYY) : ");
  scanf("%d",&year);
  if(year%4==0 && year%100!=0 || year%400==0)
    printf("\nThe Given year %d is a Leap Year");
  else
    printf("\nThe Given year %d is Not a Leap Year");
  getch();
}
Department of Computer Science and Engineering CS8261-C PROGRAMMING
LAB

Output:

Result:

Thus the above program for finding the given year is leap year or not was executed
successfully

Questions for Viva - Voce


Sl. No. Questions Marks Awarded
1 What is preprocessor?
2 What is the purpose of type declaration in c?
3 Define and Explain about ! operator
4 What are library functions
5 What is operator and operand

Date of Submission:

Marks awarded: / 15

Sign. of Faculty
Department of Computer Science and Engineering CS8261-C PROGRAMMING
LAB

Exp No: 4 Date of Exp:


Arithmetic operations

Aim:
Write a C program to design a calculator to perform the operation namely addition,
subtraction, multiplication, division and square of a number.

Algorithm:
1. Start the program.
2. Enter into C editor.
3. Declare the needed variables fn, sn, c.
4. Get first number and second number.
5. Perform addition, subtraction, multiplication and division using switch case.
6. Perform the operation based on entered options.
7. Run the program and get result.
8. Stop the program.

Program:
#include <stdio.h>
#include <conio.h>
void main()
{
  int fn,sn,c;
  float r;
  char c1;
  clrscr();
  printf("Enter the First Number : ");
  scanf("%d",&fn);
  printf("\nEnter the Second Number : ");
  scanf("%d",&sn);
  do{
    printf("\nWhich operations you want to perform (+,-,*,/,s)\n");
    c=getch();
    switch(c)
    {
Department of Computer Science and Engineering CS8261-C PROGRAMMING
LAB

      case '+':


        r = fn+sn;
        break;
      case '-':
        r = fn-sn;
        break;
      case '*':
        r = fn*sn;
        break;
      case '/':
        r = fn/(float)sn;
        break;
      case 's':
        r = fn*fn;
        break;
    } // switch
    if(c=='/')
      printf("\nResult = %f\n",r);
    else
      printf("\nResult = %.f\n",r);
    printf("\ndo you want continue (y/n) :");
    c1 = getch();
  }  while (c1=='y' || c1=='Y');
}
Department of Computer Science and Engineering CS8261-C PROGRAMMING
LAB

Output:
Department of Computer Science and Engineering CS8261-C PROGRAMMING
LAB

Result:
Thus the above program for designing calculator to perform basic operations was executed
successfully.

Questions for Viva - Voce


Sl. No. Questions Marks Awarded
1 What is switch statement
2 What is the use of a \n character?
3 What is nested loop?
4 What is compiler?
5 What is identifier?

Date of Submission:

Marks awarded: / 15

Sign. of Faculty
Department of Computer Science and Engineering CS8261-C PROGRAMMING
LAB

Exp No: 5 Date of Exp:


Armstrong number

Aim:

Write a C program to check whether a given number is Armstrong number or not.

Algorithm:
1
2 1. Start
3 2. Declare variables
4 3. Read the Input number.
5 4. Calculate sum of cubic of individual digits of the input.
6 5. Match the result with input number.
7 6. If match, Display the given number is Armstrong otherwise not.
8 7. Stop
Program:

#include <stdio.h>
#include <conio.h>
#include <math.h>
void main()
{
 long int num,result;
 long int armstrong(long);
 int base;
 clrscr();
 printf("Enter the given number : ");
 scanf("%ld",&num);
 result = armstrong(num);
 if(result==num)
   printf("\nThe given number %ld is an Armstrong number",num);
 else
   printf("\nThe given number %ld is not an Armstrong number",num);
 getch();
}  // main
long int armstrong(long int num)
{
 long int num1=num, res;
Department of Computer Science and Engineering CS8261-C PROGRAMMING
LAB

 double r,count=0;
 double sum=0.0;
 for(;num1!=0;count++,num1/=10);
 num1=num;
 while(num1!=0)
 {
   r = num1%10;
   sum = sum+pow(r,count);
   num1 = num1/10;
 }
 res = sum;
 return res;
}
Output:

Result:

Thus the above program for finding Armstrong number was executed successfully.

Questions for Viva - Voce


Sl. No. Questions Marks Awarded
1 What is syntax error?
2 What is identifier?
3 Can I use “int” data type to store the value 32768?Why?
4 When is the “void” keyword used in a function
5 What is comments

Date of Submission:

Marks awarded: / 15

Sign. of Faculty
Department of Computer Science and Engineering CS8261-C PROGRAMMING
LAB

Exp No: 6 Date of Exp:


Sort the numbers based on the weight

Aim:
Write a C program to find the sum of weights based on the following conditions:
5 if it is a perfect cube.
             4 if it is a multiple of 4 and divisible by 6.
             3 if it is a prime number.
Algorithm:
1 1. Start
2 2. Declare variables
3 3. Read the number of elements in an array .
4 4. Get the individual elements.
5 5. Calculate the weight for each element by the conditions
6  5 if it is a perfect cube (pow)
7  4 if it is a multiple of 4 and divisible by 6 (modulus operator)
8  3 if it is a prime number(modulus operator)
9 6. Display the output of the weight calculations after sorting .
10 7. Stop
Program:

#include <stdio.h>
#include <math.h>
void main()
{
int nArray[50],wArray[50],nelem,sq,i,j,t;
clrscr();
printf("\nEnter the number of elements in an array : ");
scanf("%d",&nelem);
printf("\nEnter %d elements\n",nelem);
for(i=0;i<nelem;i++)
  scanf("%d",&nArray[i]);
// Sorting an array
for(i=0;i<nelem;i++)
  for(j=i+1;j<nelem;j++)
     if(nArray[i] > nArray[j])
     {
Department of Computer Science and Engineering CS8261-C PROGRAMMING
LAB

t = nArray[i];
nArray[i] = nArray[j];
nArray[j] = t;
     }
//Calculate the weight
    for(i=0; i<nelem; i++)
{
    wArray[i] = 0;
   // sq =(int) sqrt(nArray[i]);
    if(percube(nArray[i]))
wArray[i] = wArray[i] + 5;

    if(nArray[i]%4==0 && nArray[i]%6==0)


wArray[i] = wArray[i] + 4;

    if(prime(nArray[i]))
wArray[i] = wArray[i] + 3;

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


   printf("<%d,%d>", nArray[i],wArray[i]);
     getch();

int prime(int num)


{
 int flag=1,i;
 for(i=2;i<=num/2;i++)
   if(num%i==0)
   {
     flag=0;
     break;
   }
  return flag;
}
int percube(int num)
{
   int i,flag=0;
   for(i=2;i<=num/2;i++)
     if((i*i*i)==num)
     {
 flag=1;
 break;
     }
Department of Computer Science and Engineering CS8261-C PROGRAMMING
LAB

 return flag;
}

Output:

Result:

Thus the above program for finding the sum of weights based on the conditions was
executed successfully.

Questions for Viva - Voce


Sl. No. Questions Marks Awarded
1 What is debugging?
2 What is sorting
3 What does the && operator do in a program code
4 What is logical error
5 What are preprocessor directives?

Date of Submission:

Marks awarded: / 15

Sign. of Faculty
Department of Computer Science and Engineering CS8261-C PROGRAMMING
LAB

Exp No: 7 Date of Exp:


Average height of persons

Aim:

Write a C program to populate an array with height of persons and find how many persons
are above the average height.

Algorithm:

1. Start the program


2. Enter into c editor
3. Declare variables
4. Read the total number of persons and their height.
5. Calculate avg=(float)sum/n and find number of persons their height>avg.
6. Display the output of the calculations .
7. Stop the program

Program:
#include <stdio.h>
#include <conio.h>
void main()
{
 int i,n,sum=0,count=0,height[100];
 float avg;
 clrscr();
 //Read Number of persons
 printf("Enter the Number of Persons : ");
 scanf("%d",&n);
 //Read the height of n persons
 printf("\nEnter the Height of each person in centimeter\n");
 for(i=0;i<n;i++)
 {
   scanf("%d",&height[i]);
   sum  = sum + height[i];
 }
 avg = (float)sum/n;
Department of Computer Science and Engineering CS8261-C PROGRAMMING
LAB

 //Counting
 for(i=0;i<n;i++)
  if(height[i]>avg)
     count++;
 //display
 printf("\nAverage Height of %d persons is : %.2f\n",n,avg);
 printf("\nThe number of persons above average : %d ",count);
 getch();
}

Output:

Result:

Thus the above program to populate an array with height of persons and find how many
persons are above the average height was executed successfully.

Questions for Viva - Voce


Sl. No. Questions Marks Awarded
1 What is format operator give example?
2 What is runtime error?
3 What is local variable?
4 What is global variable
When is a ‘switch’ statement preferable over an ‘if’
5 statement

Date of Submission:

Marks awarded: / 15

Sign. of Faculty
Department of Computer Science and Engineering CS8261-C PROGRAMMING
LAB

Exp No: 8 Date of Exp:


Body Mass Index of the individuals

Aim:
Write a C program to Populate a two dimensional array with height and weight of persons
and compute the Body Mass Index of the individuals.

Algorithm:
1 1. Start the program
2 2. Declare variables
3 3. Read the number of persons and their height and weight.
4 4. Calculate BMI=W/H2for each person
5 5. Display the output of the BMI for each person.
6 6. Stop

Program:

#include <stdio.h>
#include <conio.h>
void main()
{
  int stu[100][2];
  int index[100];
  int i,n;
  float h;
  clrscr();
  printf("Enter the number of students : ");
  scanf("%d",&n);
  for(i=0;i<n;i++)
  {  printf("Enter the Height(cm) and Weight(kg) of student %d :",i+1);
     scanf("%d%d",&stu[i][0],&stu[i][1]);
     h = (float)(stu[i][0]/100.0);
     index[i] = (float)stu[i][1]/(float)(h*h);
 }
  printf("\nStu.No.\tHeight\tWeight\tBMI\tResult\n");
  for(i=0;i<n;i++)
 {
    printf("\n%d\t%d\t%d\t%d\t",i+1,stu[i][0],stu[i][1],index[i]);
Department of Computer Science and Engineering CS8261-C PROGRAMMING
LAB

    if(index[i]<15)
      printf("Starvation\n");
    else if(index[i]>14 && index[i] < 18)
      printf("Underweight\n");
    else if(index[i] > 17 && index[i] < 26)
      printf("Healthy\n");
    else if(index[i] > 25 && index[i] < 31)
      printf("Over weight\n");
    else if(index[i] > 30 && index[i] < 36)
      printf("Obese\n");
    else
      printf("Severe Obese\n");
  } // for loop
  getch();
}

Output:
Department of Computer Science and Engineering CS8261-C PROGRAMMING
LAB

Result:
Thus the above program to Populate a two dimensional array with height and weight of
persons and compute the Body Mass Index of the individuals was executed successfully.

Questions for Viva - Voce


Sl. No. Questions Marks Awarded
1 What are enumerated types
2 What is an array
3 What is the use of getch() function
4 Is it possible to create your own header files?
5 What is pointer?

Date of Submission:

Marks awarded: / 15

Sign. of Faculty
Department of Computer Science and Engineering CS8261-C PROGRAMMING
LAB

Exp No: 9 Date of Exp:


Reverse of a given string

Aim:
Write a C program to find its reverse without changing the position of special characters.

Algorithm:
1 1. Start the program
2 2. Declare variables .
3 3. Read a String.
4 4. Check each character of string for alphabets or a special character by using isAlpha()
5 5. Change the position of a character vice versa if it is alphabet otherwise remains same.
6 6. Repeat step 4 until reach to the mid of the position of a string.
7 7. Display the output of the reverse string without changing the position of special
characters .
8 8. Stop

Program:
#include <stdio.h>
#include <string.h>
#include <conio.h>
void swap(char *a, char *b)
{
  char t;
  t = *a;
  *a = *b;
  *b = t;
}

// Main program
void main()
{
    char str[100];
    // Function Prototype
    void reverse(char *);
    int isAlpha(char);
    void swap(char *a ,char *b);
    clrscr();
    printf("Enter the Given  String : ");
   // scanf("%[^\n]s",str);
Department of Computer Science and Engineering CS8261-C PROGRAMMING
LAB

    gets(str);
    reverse(str);
    printf("Reverse String : %s",str);
    getch();
}

void reverse(char str[100])


{
    // Initialize left and right pointers
    int r = strlen(str) - 1, l = 0;

    // Traverse string from both ends until


    // 'l' and 'r'
    while (l < r)
  {
// Ignore special characters
if (!isAlpha(str[l]))
    l++;
else if(!isAlpha(str[r]))
    r--;

else
{
    swap(&str[l], &str[r]);
    l++;
    r--;
}
  }
}

// To check x is alphabet or not if it an alphabet then return 0 else 1

int isAlpha(char x)
{
    return ( (x >= 'A' &&  x <= 'Z') ||
     (x >= 'a' &&  x <= 'z') );
}
Department of Computer Science and Engineering CS8261-C PROGRAMMING
LAB

Output:

Result:
Thus the above program for finding its reverse without changing the position of special
characters.

Sl. No. Questions Marks Awarded


1 What is string?
2 What is purpose of using strcpy() and strcmp() functions
3 What is the use of (;) at the end of every program
4 Differentiate struct and union
5 What is variable

Date of Submission:

Marks awarded: / 15

Sign. of Faculty
Department of Computer Science and Engineering CS8261-C PROGRAMMING
LAB

Exp No: 10 Date of Exp:


Conversion of Decimal number into other bases

Aim:
Write a C program to Convert the given decimal number into binary, octal and
hexadecimal numbers using user defined functions.

Algorithm:
1 1. Start the program
2 2. Declare variables.
3 3. Read a decimal number.
4 4. Develop the procedure for conversion of different base(binary, octal, hexa) by modulus
and divide operator.
5 5. Display the output of the conversion value.
6 6. Stop
Program:
#include <stdio.h>
#include <conio.h>
void swap(char *s1, char *s2)
{
 char temp;
 temp = *s1;
 *s1  = *s2;
 *s2  = temp;
}
void reverse(char *str, int length)
{
int start = 0;
int end = length -1;
while (start < end)
{
swap(&str[start], &str[end]);
start++;
end--;
}
}
char* convert(int num, char str[100], int base)
{
  int i = 0;
Department of Computer Science and Engineering CS8261-C PROGRAMMING
LAB

  if (num == 0)
 {
   str[i++] = '0';
   str[i] = '\0';
   return str;
 }
while (num != 0)
{
int rem = num % base;
str[i++] = (rem > 9)? (rem-10) + 'a' : rem + '0';
num = num/base;
}
str[i] = '\0'; // Append string terminator
// Reverse the string
reverse(str, i);
return str;
}
void main()
{
 char str[100];
 int n;
 clrscr();
 printf("Enter the given decimal number : ");
 scanf("%d",&n);
 printf("The Binary value : %s\n",convert(n,str,2));
 printf("The Octal value  : %s\n",convert(n,str,8));
 printf("The Hexa value   : %s\n",convert(n,str,16));
 getch();
}

Output:
Department of Computer Science and Engineering CS8261-C PROGRAMMING
LAB

Result:

Thus the above program to Convert the given decimal number into binary, octal and
hexadecimal numbers using user defined functions.

Sl. No. Questions Marks Awarded


1 How to define pointer?
2 How to define function?
3 What is file?
4 What is malloc()?
Date of Submission:
5 What is the mean of #include and why we use it?

Marks awarded: / 15

Sign. of Faculty
Department of Computer Science and Engineering CS8261-C PROGRAMMING
LAB

Exp No: 11 Date of Exp:


String operations

Aim:

Write C programs to find the total number of words, To capitalize the first word of each
sentence and To replace a given word with another word from a given paragraph.

Algorithm:

1. Start the program


2. Enter into c editor
3. Declare the variable needed for each condition
4 Perform the condition for finding the total number of words, capitalize the first word of
each sentence and replace a given word with another word from a given paragraph.
5 Run the program and get result for each program
6 Stop the program

a)Find the total number of words

program:

#include<stdio.h>

#include<string.h>

void main()

char s[200];

int count=0,i;
Department of Computer Science and Engineering CS8261-C PROGRAMMING
LAB

printf("Enter the string:");

scanf("%[^\n]s",&s);

for(i=0;s[i]!='\0';i++)

if(s[i]=='')

count++;

printf("Number of words in given String are:%d\n", count+1);

Output:

b.To capitalize the first word of each sentence

Program:

#include <stdio.h>

#define MAX 100

int main()

char str[MAX]={0};

int i;
Department of Computer Science and Engineering CS8261-C PROGRAMMING
LAB

//input string

printf("Enter a string: ");

scanf("%[^\n]s",str); //read string with spaces

//capitalize first character of words

for(i=0; str[i]!='\0'; i++)

//check first character is lowercase alphabet

if(i==0)

if((str[i]>='a' && str[i]<='z'))

str[i]=str[i]-32; //subtract 32 to make it capital

continue; //continue to the loop

if(str[i]==' ')//check space

//if space is found, check next character

++i;

//check next character is lowercase alphabet

if(str[i]>='a' && str[i]<='z')

str[i]=str[i]-32; //subtract 32 to make it capital

continue; //continue to the loop

}
Department of Computer Science and Engineering CS8261-C PROGRAMMING
LAB

else

//all other uppercase characters should be in lowercase

if(str[i]>='A' && str[i]<='Z')

str[i]=str[i]+32; }

printf("Capitalize string is: %s\n",str);

return 0;

Output:

c. To replace a given word with another word.

Program:

#include <stdio.h>

#include<conio.h>

#include <string.h>

#include <stdlib.h>

// Function to replace a string with another

// string

char *replaceWord(const char *s, const char *oldW,

const char *newW)


Department of Computer Science and Engineering CS8261-C PROGRAMMING
LAB

char *result;

int i, cnt = 0;

int newWlen = strlen(newW);

int oldWlen = strlen(oldW);

// clrscr();

// Counting the number of times old word

// occur in the string

for (i = 0; s[i] != '\0'; i++)

if (strstr(&s[i], oldW) == &s[i])

cnt++;

// Jumping to index after the old word.

i += oldWlen - 1;

// Making new string of enough length

result = (char *)malloc(i + cnt * (newWlen - oldWlen) + 1);

i = 0;

while (*s)

// compare the substring with the result

if (strstr(s, oldW) == s)

{
Department of Computer Science and Engineering CS8261-C PROGRAMMING
LAB

strcpy(&result[i], newW);

i += newWlen;

s += oldWlen;

else

result[i++] = *s++;

result[i] = '\0';

return result;

return 0;

// Driver Program

int main()

char str[] = "xxforxx";

char c[] = "xx";

char d[] = "Geeks";

char *result = NULL;

clrscr();

printf("");

// oldW string

printf("\nOld string: %sn", str);

result = replaceWord(str, c, d);

printf("\nNew String: %sn", result);

free(result);
Department of Computer Science and Engineering CS8261-C PROGRAMMING
LAB

getch();

return 0;

Output:

Result:

Thus the above programs are executed and output was verified successfully.

Sl. No. Questions Marks Awarded


1 Give any three different format specifiers
2 What is header file?
3 What do you mean by hardware and software?
4 What is the use of main() function?
5 What is statement in c?

Date of Submission:

Marks awarded: / 15

Sign. of Faculty
Department of Computer Science and Engineering CS8261-C PROGRAMMING
LAB

Exp No: 12 Date of Exp:


Towers of Hanoi using Recursion

Aim:

Write a program to Solve towers of Hanoi using recursion.

Algorithm:

1 1. Start
2 2. Declare variables
3 3. Read the Input for number of discs.
4 4. Check the condition for each transfer of discs using recursion.
5 5.Only a single disc is allowed to be transferred at a time.
6 6. Each transfer or move should consist of taking the upper disk from one of the stacks
and then placing it on the top of another stack i.e. only a topmost disk on the stack can be moved.
7 7.Larger disk cannot be placed over smaller disk; placing of disk should be in increasing
order.

8 8. Display the output of the each move .


9 9. Stop
Program:
#include <stdio.h>
#include <conio.h>
void towerofhanoi(int n, char from, char to, char aux)
{
if (n == 1)
{
printf("\n Move disk 1 from Peg %c to Peg %c", from, to);
return;
}
towerofhanoi(n-1, from, aux, to);
printf("\n Move disk %d from Peg %c to Peg %c", n, from, to);
Department of Computer Science and Engineering CS8261-C PROGRAMMING
LAB

towerofhanoi(n-1, aux, to, from);


}

int main()
{
    int n;
    clrscr();
    printf("Enter the number of disks : ");
    scanf("%d",&n); // Number of disks
    towerofhanoi(n, 'A', 'C', 'B'); // A, B and C are names of peg
    getch();
    return 0;
}

Output:
Department of Computer Science and Engineering CS8261-C PROGRAMMING
LAB

Result:

Thus the above program for solving tower of Hanoi using recursion was executed
successfully.

Sl. No. Questions Marks Awarded


1 What is tower of Hanoi?
2 Give the syntax for if statement
3 Define goto and labeled statement
4 What is the different between #include<> and #include “”?
5 What are different storage classes in c

Date of Submission:

Marks awarded: / 15

Sign. of Faculty
Department of Computer Science and Engineering CS8261-C PROGRAMMING
LAB

Exp No: 13 Date of Exp:


Sorting using pass by reference

Aim:
Write a C program to sort the list of numbers using pass by reference.

Algorithm:

1 1. Start
2 2. Declare variables and create an array
3 3. Read the Input for number of elements and each element.
4 4. Develop a function to sort the array by passing reference
5 5. Compare the elements in each pass till all the elements are sorted.
6 6. Display the output of the sorted elements .
7 7. Stop
Program:
#include <stdio.h>
#include <conio.h>
void main()
{
  int n,a[100],i;
  void sortarray(int*,int);
  clrscr();
  printf("\nEnter the Number of Elements in an array : ");
  scanf("%d",&n);
  printf("\nEnter the Array elements\n");
  for(i=0;i<n;i++)
   scanf("%d",&a[i]);
  sortarray(a,n);
  printf("\nAfter Sorting....\n");
  for(i=0;i<n;i++)
   printf("%d\n",a[i]);
  getch();
}
void sortarray(int* arr,int num)
Department of Computer Science and Engineering CS8261-C PROGRAMMING
LAB

{
 int i,j,temp;
 for(i=0;i<num-1;i++)
  for(j=0;j<num-i-1;j++)
    if(arr[j] > arr[j+1])
  {
      temp=arr[j];
      arr[j] = arr[j+1];
      arr[j+1] = temp;
  }
}

Output:
Department of Computer Science and Engineering CS8261-C PROGRAMMING
LAB

Result:

Thus the above program for sorting the list of numbers using pass by reference.

Sl. No. Questions Marks Awarded


1 What is recursion?
2 What is the purpose of realloc()?
3 What is an argument?
4 What are the uses of function?
5 Define call by value

Date of Submission:

Marks awarded: / 15

Sign. of Faculty
Department of Computer Science and Engineering CS8261-C PROGRAMMING
LAB

Exp No: 14 Date of Exp:


Salary slip of employees

Aim:

Write a C program to Generate salary slip of employees using structures and pointers.

Algorithm:

1. Start

2.ReadEmployeesdetailse1,empid,name,basic,hra,da,ma,pf,insurance,gross,

Net

3. e1=(struct employee *)malloc(sizeof(struct employee) * num);

4. print input for every employee

5. For(i=0;i<num;i++)

6.Calculate gross amount

7. Calculate net amount

8. ENDFOR

9.Stop

Program:

  #include <stdio.h>
  #include <stdlib.h>
  #include <string.h>

  /* structure to store employee salary details */


  struct employee {
        int empId;
        char name[32];
Department of Computer Science and Engineering CS8261-C PROGRAMMING
LAB

        int basic, hra, da, ma;


        int pf, insurance;
        float gross, net;
  };

  /* prints payslip for the requested employee */


  void printSalary(struct employee e1) {
        printf("Salary Slip of %s:\n", e1.name);
        printf("Employee ID: %d\n", e1.empId);
        printf("Basic Salary: %d\n", e1.basic);
        printf("House Rent Allowance: %d\n", e1.hra);
        printf("Dearness Allowance: %d\n", e1.da);
        printf("Medical Allowance: %d\n", e1.ma);
        printf("Gross Salary: %.2f Rupees\n", e1.gross);

        printf("\nDeductions: \n");
        printf("Provident fund: %d\n", e1.pf);
        printf("Insurance: %d\n", e1.insurance);
        printf("\nNet Salary: %.2f Rupees\n\n", e1.net);
        return;
 }

  int main() {
        int i, ch, num, flag, empID;
        struct employee *e1;

        /* get the number of employees from the user  */


        printf("Enter the number of employees:");
        scanf("%d", &num);

        /* dynamically allocate memory to store employee salary details */


        e1 = (struct employee *)malloc(sizeof(struct employee) * num);

        /* get the employee salary details from the customer */


        printf("Enter your input for every employee:\n");
        for (i = 0; i < num; i++) {
                printf("Employee ID:");
                scanf("%d", &(e1[i].empId));
                getchar();
                printf("Employee Name:");
Department of Computer Science and Engineering CS8261-C PROGRAMMING
LAB

                fgets(e1[i].name, 32, stdin);


                e1[i].name[strlen(e1[i].name) - 1] = '\0';
                printf("Basic Salary, HRA:");
                scanf("%d%d", &(e1[i].basic), &(e1[i].hra));
                printf("DA, Medical Allowance:");
                scanf("%d%d", &(e1[i].da), &(e1[i].ma));
                printf("PF and Insurance:");
                scanf("%d%d", &(e1[i].pf), &(e1[i].insurance));
                printf("\n");

    }

        /* gross and net salary calculation */


        for (i = 0; i < num; i++) {
                e1[i].gross = e1[i].basic +
                        (e1[i].hra * e1[i].basic) / 100 +
                                (e1[i].da * e1[i].basic) / 100 +
                                        (e1[i].ma * e1[i].basic) / 100;
                e1[i].net = e1[i].gross - (e1[i].pf + e1[i].insurance);
    }

        /* printing payslip for the given employee ID */


        while (1) {
                printf("Enter employee ID to get payslip:");
                scanf("%d", &empID);
                flag = 0;
                for (i = 0; i < num; i++) {
                        if (empID == e1[i].empId) {
                                printSalary(e1[i]);
                                flag = 1;
            }
        }

                if (!flag) {
                        printf("No Record Found!!\n");
        }

                printf("Do You Want To Continue(1/0):");


                scanf("%d", &ch);
Department of Computer Science and Engineering CS8261-C PROGRAMMING
LAB

                if (!ch) {
                        break;
        }
    }
        return 0;
 }

Output:
Department of Computer Science and Engineering CS8261-C PROGRAMMING
LAB

Result:

Thus the above program for Generating salary slip of employees using structures and
pointers

Sl. No. Questions Marks Awarded


1 What is structure?
2 What is union?
3 What is looping?
4 What is n array?
5 What are character array?

Date of Submission:

Marks awarded: / 15

Sign. of Faculty
Department of Computer Science and Engineering CS8261-C PROGRAMMING
LAB

Exp No: 15 Date of Exp:


Internal marks of students

Aim:

Write a C program to Compute internal marks of students for five different subjects using
structures and functions.

Algorithm;

1. Start the program.

2. Enter into c editor.

3. Declare the variables for five subjects in structure. int sub1,int sub2,int sub3,int sub4,int
sub5.

4.calculate sum for five subjects total=s[i].sub1+s[i].sub2+s[i].sub3+s[i].sub4+s[i].sub5.

5. Run the program

6.Get result.

7.Stop the program

Program:

#include<stdio.h>

#include<conio.h>

struct student

int sub1;

int sub2;
Department of Computer Science and Engineering CS8261-C PROGRAMMING
LAB

int sub3;

int sub4;

int sub5;

};

int main()

struct student s[10];

int i,total=0;

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

printf("\n Enter marks in five subjects=");

scanf("%d%d%d%d%d",&s[i].sub1,&s[i].sub2,&s[i].sub3,&s[i].sub4,&s[i].sub5);

total=s[i].sub1+s[i].sub2+s[i].sub3+s[i].sub4+s[i].sub5;

printf("\n total marks of s[%d] Student=%d",i,total);

getch();

return 0;

Output:
Department of Computer Science and Engineering CS8261-C PROGRAMMING
LAB

Result:

Thus the above program for computing internal marks of students for five different subjects
using structures and functions was executed successfully.

Sl. No. Questions Marks Awarded


1 What is function?
Department of Computer Science and Engineering CS8261-C PROGRAMMING
LAB

2 Differentiate break and continue


3 Differentiate parameters and argument
4 How do you access the member of the structure
5 When do you prefer for loop statement?

Date of Submission:

Marks awarded: / 15

Sign. of Faculty

You might also like