C Programs


         C Programming Questions and Answers

Question 1 :

 
Write a program that asks user to input 2 integers and print the results of sum, difference, product, division (first by second number) and remainder operations. The output must look like below:
Enter first number: 7
Enter second number: 4
==========================
Result of summation is    : 11

Result of difference is    : 3

Result of product is        : 28

Result of division is        : 1.75

Result of remainder is    : 3
==========================
Note: There is an empty line after result of each operation. Also, the result of some of these operations may not be an integer. So use appropriate data types.
=====================================================


Answer(Code) :



#include <stdio.h>
#include <conio.h>


main ()
{
    
     int value1 , value2, total;
     float total1;
      printf("Enter First Number :");
     scanf("%d",&value1);
     printf("Enter Second Number :");
     scanf("%d",&value2);
     printf("======================\n");
     total= value1 + value2 ;
     printf("Result of summation is : %d\n\n",total);
     total= value1 - value2;
     printf("Result of  difference is  %d\n\n",total);
     total= value1 * value2;
     printf ("Result of Product is :%d\n\n",total);
      total1=(float)(value1)/value2;
     printf("Result of divison is :%0.2f\n\n",total1);
     total=value1%value2;
     printf("Result of divison is :%d\n\n",total);
     getch();
     }
    



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

QUESTION 2 :

Write a program that displays the following triangle. (Do NOT use looping mechanisms!)


Answer(Code) :



 #include <stdio.h>
#include <conio.h>


main ()
{
     
      printf("                              A \n");
      printf("\n                        B     B \n");
      printf("\n                      C    C    C  \n");
      printf("\n                    D             D   \n");
      printf("\n                  E        E        E   \n");
     getch();
     }
     



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

Question 3 :


Write a program that asks user to input his height in feet and inches. Convert the result into meters and display it on the screen.

Answer(Code) :

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

int height;
int inch;
float ans,total,ans2;
printf("RegID # 1266 \n\n");
printf("Enter Your Height in feet:");
scanf("%d",&height);
ans=(float)(height)/3.28084;
printf("\nYour Feet in meters is:%.2f\n",ans);
printf("\nEnter Your height in Inch:");
scanf("%d",&inch);
ans2=(float)(inch)/39.3701 ;
printf("\nYour Inch in meters is:%.2f\n",ans2);
total= (float)ans+ans2;
printf("\nThe total Height in meters is:%.2f",total);
getch();
}

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


Question 4 :


Write a program that asks user to input his/her GPA for each of the last 4 semesters. Then compute the average of the entered GPAs and display the result.

Answer(Code) :

#include <stdio.h>
#include <conio.h>

main ()
{
     float gpa_1 ,gpa_2 ,gpa_3 ,gpa_4 , total ;  
      printf("Enter Your Last 4 Semesters GPA");
     printf("\nEnter First GPA :");
     scanf("%f",&gpa_1);
     printf("\nEnter Second GPA :");
     scanf("%f",&gpa_2);
     printf("\nEnter Third GPA :");
     scanf("%f",&gpa_3);
     printf("\nEnter Fourth GPA :");
     scanf("%f",&gpa_4);

total= ( gpa_1 + gpa_2 + gpa_3 + gpa_4)/4 ;
printf("\n\nAverage : %.2f",total);
getch();
return 0;

} 
=========================================================
 

Question 5 :

Write a program that takes current temperature as input from the user in FAHRENHEIT. Then converts the temperature in CELSIUS scale and informs the user if the weather is Hot, Warm, Nice, Cold, Freezing. Use the following ranges for making decision about the warmness of the weather and print accordingly:
If the temperature is above or equal to 38oC, the weather is Hot. So print, “Isn’t it too HOT”
If the temperature is above or equal to 29oC but below 38oC, the weather is Warm. So print, “Hmm this is WARM”
If the temperature is above or equal to 22oC but below 29oC, the weather is Nice. So print, “It seems weather is really NICE.”
If the temperature is above or equal to 10oC but below 22oC, the weather is Cold. So print, “I feel this is COLD.”
If the temperature is below 10oC, the weather is Freezing. So print, “Wow, this is FREEZING.”
Your program should produce the following window. Note that the temperature only has one digit after decimal place. To achieve this effect, you may have to read more about format specifiers.

 




Answer(Code) :


#include <stdio.h>
#include <conio.h>

main ()
{
float c,temp ;
printf("Enter the temperature:");
scanf("%f",&temp);
printf("\n\n======================================");

c = (((temp-32)*5)/9);

if( temp >=38)
{
 printf("\nThe temperature you entered is equal to %.1fC.",c);
printf("Isn't it too HOT");
}
else if(temp>=29 && temp<38)
{
 printf("\nThe temperature you entered is equal to %.1fC.",c);
printf("Hmm this is WARM");
}
else if (temp>=22 && temp <29)
{
 printf("\nThe temperature you entered is equal to %.1fC.",c);
printf("It seems wearther is really NICE.");
}
else if (temp>=10 && temp <22)
{
 printf("\nThe temperature you entered is equal to %.1fC.",c);
printf("I feel this is COLD.");
}
else if (temp <10)
{

 printf("\nThe temperature you entered is equal to %.1fC.",c);
printf("Wow, this is FREEZING");
}
getch();
}
=========================================================

QUESTION 6 :

Write a program that asks user to input a character. Then inform the user if the entered character is a number, a capital letter, a small letter or a symbol. The input and output messages should look like the following:

Answer(Code) :

#include<stdio.h>
#include<conio.h>
main()
{
      char a;
    
      printf("Enter a Charatcter:");
     
       scanf("%c",&a);
      
      printf("\n******************************");
    
    
    
      if(a>='0'&&a<='9')
     
      printf("\n%c is Number",a);
     
      else if(a>='a' && a<='z')
     
      printf("\n%c is small letter ",a);
    
      else if(a>='A' && a<='Z')
     
      printf("\n%c is Capital letter",a);
  
       else
      
       printf("\n %c is a symbol",a);
  
      getch();
      }

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

QUESTION 7 :
 
Write a program that asks user to input his marks (percentage). Then display the corresponding letter grade he/she may have got. Use the following ranges for computation of letter grade from the percentage.
A+ if the percentage is above 95
A if the percentage is above 90
A- if the percentage is above 85
B+ if the percentage is above 80
B if the percentage is above 75
B- if the percentage is above 70
C+ if the percentage is above 65
C if the percentage is above 60
D if the percentage is below 60
NOTE: Above here means greater than or equal to.


Answer(Code) :

#include <stdio.h>
#include <conio.h>
main ()
{
int a ;
printf("Enter Your Marks:");
scanf("%d",&a);
if(a>95 )
{
printf("A+");
}
else if(a<=95 && a>90)
{
printf("A");
}
else if(a>85 && a<=90)
{
printf("A- (A Minus) ");
}
else if(a>80 && a<=85)
{
printf("B+");
}
else if(a>75 && a<=80)
{
printf("B");
}
else if(a>70 && a<=75)
{
printf("B-");
}
else if(a>65 && a<=70)
{
printf("C+");
}
else if(a>60 && a<=65)
{
printf("C");
}
else if(a<60)
{
printf("D");
}
getch();
}

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



QUESTION 8 :

Write a program to compute the tax due on the annual income. Your program should ask the user to input his/her monthly income. Make sure that the user did not make any error while entering the income (for e.g. the income of the person cannot be less than zero). Then compute the income tax that he/she owes to the government based on his annual income. Report both the total amount of tax that he owes in a year and how much it amounts to per month. Use the following tax brackets for your calculation (these brackets will be used for calculation of tax by the government of Pakistan for fiscal year 2013-2014). 



Answer(Code) :

#include<stdio.h>
#include<conio.h>
main()
{
      printf("=============A PROGRAM FOR TAXATION=======\n");
      float income,tax,abc,abc1,abc2,abc3,abc4,abc5,abc6,abc7,abc8;
      float abc9,abc10,total1,total2,total3,total4,total5,total6,total7,total8,total9,total10;
     
    
      printf("Enter your monthly income:");
      scanf("\n%f",&income);
      if(income>0)
      {
      abc=(income*12);  
      printf("\nYour annual income is %3.3f",abc);
      printf("\n\n===================Tax Computation=====================\n\n");
      if(abc<=400000.000)
      {
       printf("\nThere are no tax on your annual income:");
      }
       else if(abc>400000.000 && abc<=750000.000)
       {
       abc1=(((abc-400000.000)*5)/100); 
       printf("\nThe total amount of tax you owe in a year is %3.3f",abc1);
        total1=abc1/12;
       printf("\nThe total tax that you owe per month is %3.3f",total1);
       }
       else if(abc>750000.000 && abc<=1400000.000)
       {
       abc2=((((abc-750000.000)*10)/100)+17500.000);
       printf("\nThe total amount of tax you owe in a year is %3.3f",abc2);               
        total2=abc2/12;
       printf("\nThe total tax that you owe per month is %3.3f",total2);
       }
       else if(abc>1400000.000 && abc<=1500000.000)
       {
       abc3= ((((abc-1400000.000)*12.500)/100)+82500.000);
       printf("\nThe total amount of tax you owe in a year is %3.3f",abc3);
        total3=abc3/12;
       printf("\nThe total tax that you owe per month is %3.3f",total3);
       }
       else if(abc>1500000.000 && abc<=1800000.000)
       {
       abc4=((((abc-1500000.000)*15)/100)+140000.000);
       printf("\nThe total amount of tax you owe in a year is %3.3f",abc4);
        total4=abc4/12;
       printf("\nThe total tax that you owe per month is %3.3f",total4);
       }
       else if(abc>1800000.000 && abc<=2500000.000)
       {
       abc5=((((abc-1800000.000)*17.5)/100)+1800000);
       printf("\nThe total amount of tax you owe in a year is %3.3f",abc5);
        total6=abc5/12;
       printf("\nThe total tax that you owe per month is %3.3f",total6);
       }
       else if(abc>2500000.000 && abc<=3000000.000)
       {
       abc6=((((abc-2500000.000)*20)/100)+262500.000);
       printf("\nThe total amount of tax you owe in a year is %3.3f",abc6);
        total6=abc6/12;
       printf("\nThe total tax that you owe per month is %3.3f",total6);
       }
       else if(abc>3000000.000 && abc<=3500000.000)
       {
       abc7=((((abc-3000000.000)*22.5)/100)+362500.000);
       printf("\nThe total amount of tax you owe in a year is %3.3f",abc7);
        total7=abc7/12;
       printf("\nThe total tax that you owe per month is %3.3f",total7);
       }
       else if(abc>3500000.000 && abc<=4000000.000)
       {
       abc8=((((abc-3500000.000)*25)/100)+475000.000);
       printf("\nThe total amount of tax you owe in a year is %3.3f",abc8);
        total8=abc8/12;
       printf("\nThe total tax that you owe per month is %3.3f",total8);
       }
       else if(abc>4000000.000 && abc<= 7000000.000)
       {
       abc9=((((abc-4000000.000)*27.5)/100)+600000);   
       printf("\nThe total amount of tax you owe in a year is %3.3f",abc9);
       total9=abc9/12;
       printf("\nThe total tax that you owe per month is %3.3f",total9);
       }
       else if(abc>7000000.000)
       {
       abc10=((((abc-7000000.000)*30)/100)+1425000.000);
       printf("\nThe total amount of tax you owe in a year is %3.3f",abc10);
       total10=abc10/12;
       printf("\nThe total tax that you owe per month is %3.3f",total10);
       }
       else
       {
       printf("\nError Error Error !!");
       }
       }
      else
      {
      printf("\nError! Your income cannot be less than zero:\n");
      main();
      }
      getch();
      }
=========================================================  




QUESTION 9 :

Write a program to take input from the user in an array of size 10. You should ask user 10 times to enter a number and store each of his responses at a different index. After you have taken input, display the numbers, their sum and their average. A sample run of the program is shown below. Make sure the output of your program is correctly formatted otherwise your marks will be deducted.                                    
Input a number: 5
Input a number: 6
Input a number: 10
Input a number: 1
Input a number: -1
Input a number: 15
Input a number: -10
Input a number: 3
Input a number: 11
Input a number: 7
=====================================
Element    Value
  5
  6
 10
  1
 -1
 15
-10
  3
 11
  7
Sum           47
Average      4.7
Note: There are 2 empty spaces before each of the element (i.e. 0, 1, 2,…,9) and all the values (5, 6, 10,…,7) are right aligned with and a possibility of up to 3 places to the left of the value (a total of 4 places).


Answer(Code) :

#include<conio.h>
#include<stdio.h>
#define Arrsize 10
main ()   //body
{
    int Element[Arrsize],i,sum=0;   // declare
    float avg;                    // declare
   
for(i=0;i<Arrsize;i++)
    {
       
    printf("Input a number: ");
    
    scanf("%d",&Element[i]);
    
    sum=sum+Element[i];
    
    avg=(float)(sum)/10;
       
     }

        printf("=====================================\n");
    printf("Element\t  Value");
    printf("\n");   // for line
 for(i=0;i<Arrsize;i++)
    {
       
     printf("%3d\t    %3d\n",i,Element[i]);              
    }
   printf("Sum\t    %3d\n",sum);
   printf("Average\t    %0.1f\n",avg);
                                      
 getch();

}
 Output :

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



QUESTION 10 :


Now write another program just like above, but change it so that it now only computes the sum and average of the non-negative numbers (i.e numbers ≥ 0). A sample run of the program is given below. Make sure the output of your program is correctly formatted otherwise your marks will be deducted.                              
Input a number: 5
Input a number: 6
Input a number: 10
Input a number: 1
Input a number: -1
Input a number: 15
Input a number: -10
Input a number: 3
Input a number: 11
Input a number: 7
=====================================
Element    Value
  5
  6
 10
  1
 15
  3
 11
  7
Sum           58
Average     7.25
Note: Only those elements are displayed by the program for which the number ≥ 0 i.e. after element 3, element 5 is displayed by the program. Also, there are 2 empty spaces before each of the element (i.e. 0, 1, 2,…,9) and all the values (5, 6, 10,…,7) are right aligned with and a possibility of up to 3 places to the left of the value (a total of 4 places)


Answer(Code) :

#include<conio.h>
#include<stdio.h>
#define Arrsize 10
main()
{
    int value[Arrsize],i,increment=0,sum=0;    // declare
   
    float average;    //declare
   
for(i=0;i<Arrsize;i++)
    {
printf("Input a number: ");
scanf("%d",&value[i]);
if(value[i]>=0)
{
increment++;
sum=sum+value[i];
average=(float)sum/increment;
  
   }
    }
    printf("=====================================");
    printf("\n");
    printf("Element\t   Value");
    printf("\n");
   
 for(i=0;i<Arrsize;i=i+1)
  
    {
       
        if (value[i]>0)
     {
    
     printf("%3d\t     %3d\n",i,value[i]);              
    }
}
   printf("Sum \t     %3d",sum);
  
   printf("\n");
  
   printf("Average\t    %.2f\n",average);
                                      
                                      
getch();
}
  
Output :


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

QUESTION 11 :

Now, write another program which is a modification of the program in Q10. This program should ask user to input a number until the user enters a negative number. Once a negative number is entered, your program should stop asking for input and display the numbers, their sum and their mean and their standard deviation. In case, if a user never enters a negative number, you should stop asking for input after you have reached the size limit of your array (which is set to 10 in Q9. A sample run of the program is given below. Make sure the output of your program is correctly formatted otherwise your marks will be deducted.             10 marks
Input a number: 5
Input a number: 6
Input a number: 10
Input a number: 1
Input a number: 13
Input a number: 7
Input a number: -1
=====================================
Element    Value
  5
  6
 10
  1
 13
  7
Sum           42
Mean            7
Std.Dev.     3.79
Note: The formula for standard deviation is: , where  represents the number of non-negative numbers the user entered, represents the  th number the user entered and  is the mean of the numbers entered.
Also, there are 2 empty spaces before each of the element (i.e. 0, 1, 2,…,9) and all the values (5, 6, 10,…,7) are right aligned with and a possibility of up to 3 places to the left of the value (a total of 4 places)
Hint: To compute standard deviation, you will first need to compute mean of the numbers. Then loop over the elements of the array again and compute the sum of squared differences .


Answer(Code) :

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

#define size 10

main()

{
    int array[size],mean=0,i,dincrement=0,sum=0;    // mean given  in int because of h.w output
    float StdDev1=0,StdDev=0;
   
    for(i=0;i<size;i++)    // 1st loop for  input
    {
        printf("Input Your Number: ");
        scanf("%d",&array[i]);
             
            if(array[i]<0)            // we can use if(num[i]>=0) on other way
            {
                break;
            }
    }
   
    printf("=====================================");
               
    printf("\n");
               
    printf("Elements    Values\n");
       
    for(i=0;i<size;i++)    // 2nd loop for sum
    {
       
    if (array[i]<0)
    {
    break;
    }
    printf("%3d\t      %3d\n",i,array[i]);
                   
    sum=sum+array[i];
    dincrement++;
    }           
                   
    printf("Sum   \t      %3d",sum);
                       
    mean=sum/dincrement;

    printf("\n");           
    printf("Mean          %3d",mean);
                       
    for(i=0;i<size;++i)   // 3rd loop for std.dev
    {   
    if(array[i]<0)
    break;
                                                       
    StdDev1+=(array[i]-mean)*(array[i]-mean);
    }
                       
    StdDev=sqrt(StdDev1/dincrement);          // stddev formula
                           
               
    printf("\nStd.Dev      %3.2f",StdDev);

    getch();
    return 0 ;
   
}
Output :



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


QUESTION 12 :

Write a program to draw a hollow square of width w. The width w is entered by the user. A sample output run is shown below:                        
Input width of square: 6
############
#                    #
#                    #
#                    #
#                    #
############
Note: Even though the width is 6, a total of 12 (double of 6) # symbols are displayed in the first and the sixth line. However, the number of lines is still 6.
Hint: You will need nested for loops as discussed in class. For all the lines except first and the last one, you can use if condition that the symbol # should only be printed if the inner loop is running for the first time or the last time. You can determine if the loop is running for the first or the last time by comparing the counter of inner loop with 1 (for first time) or width (for the last time). Also remember that this if condition should only execute for the lines which are not the first or the last. So basically you need a nested if and possibly a nested if.


Answer(Code) :

 #include<stdio.h>
#include<conio.h>


int main()
{
    int width,square,i,count;   //declare
  
    printf("Input width of square: ");
    scanf("%d",&width);
  
    square=width*2;
  
    for(i=1;i<=width;i++)
    {
    for(count=1;count<=square;count++)
    {
              
   if(i==1)
    printf("#");
    else if(i==width)
    printf("#");
    else if(count==1)
    printf("#");
    else if (count==square)
    printf("#");
    else
    printf(" ");
    }
    printf("\n");
    }
  
getch();
return 0 ;
}
Output :


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

QUESTION 13 :

 Write a program that asks user to input a character and displays it in the opposite case. That is if a user entered ‘a’, you should display ‘A’, but if user entered ‘A’, you should display ‘a’.  However, if the user entered a number like ‘0’ or ‘2’, or enters any other symbol, you should display as it is.                                  
Hint: Do NOT use scanf() or getche() for input, because these methods do not give you the ability to not show characters on the screen as user enters them. Instead use getch(). You can use printf(“%c”,val) or putchar(val) to display a character on the screen, where val is a variable of type char. We made a program in assignment 2, which checked if the input character was an UPPERCASE or lowercase letter.


Answer(Code) :

#include <stdio.h>
#include <conio.h>

main()
  
   {
  
   char  c;
  
    printf("\t Program: input a character and displays it in the opposite case\n\n\n");
   
   
    printf("Input a character: ");
   
    c = getch();
   
    printf("\n\n\n\n======================================\n\n");

   
     if(c >= 'a')
   
   

     {
        if( c <= 'z')
   
    c=c-32;
    printf("Result:\n");
     printf("\n\nUppercase Equivalent : %c", c);
   
      }
   
      else if(c >='A')
      {
      if(c <='Z')
     
      c=c+32;
    printf("Result:\n");
      printf("\n\nThe Lowercase Equivalent Is: %c", c);
     
      }
      else
     
      printf("\n\nYou enter this %c",c);
   
  getch();
         }

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


QUESTION 14 :

Modify the program in Q1 so that a user can enter as many characters or numbers or symbols he wants but all the characters in small letters are displayed in capital letters. Stop asking for input once the user presses “Enter” key. For example, if a user wants to input, “How many days are there in a Week? There are 7 dAYs.” Your program should display, “HOW MANY DAYS ARE THERE IN A WEEK? THERE ARE 7 DAYS.”             Hint: You DO NOT need to use an array at this point. Just use a loop which terminates when the user presses the “Enter” key. Again, do NOT use gets() or scanf() or getche() for input, because these methods do not give you the ability to not show characters on the screen as user enters them. Instead use getch(). Each character you take as input is displayed (after conversion to capital letter, if required) on the screen before you take another input.

Answer(Code) :

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

 int main()
 {
     char d;
  do 

{
    
         d=getch();
        
             if(d>='a')
             {
                 if(d<='z')
            
                 d=d-32;
            
                 printf("%c",d);
             }
                 else
            
                     printf("%c",d);
    
 }
    

     while(d!='\r');
    
     getch();
 }

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

QUESTION 15 :

Now modify the program in Q14 so that a user can enter as many characters or numbers or symbols he wants but all the characters in small letters are displayed in capital letters. Stop asking for input once the user presses “Enter” key. For example, if a user wants to input, “How many days are there in a Week? There are 7 dAYs.” Your program should display, “HOW MANY DAYS ARE THERE IN A WEEK? THERE ARE 7 DAYS.”               
Hint: You DO NOT need to use an array at this point. Just use a loop which terminates when the user presses the “Enter” key. Again, do NOT use gets() or scanf() or getche() for input, because these methods do not give you the ability to not show characters on the screen as user enters them. Instead use getch(). Each character you take as input is displayed (after conversion to capital letter, if required) on the screen before you take another input.


Answer(Code) :

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

main()
 {
     char str[80] ,str1[80];

     int i, j=0;

         while(j<=80 )

         {
         str[j]=getch();
         str1[j]=str[j];
            
             if(str[j]=='\r')
                 {
                    
             break;
                    
                   }
        
                     if(str[j]>='a' )
                    
                   
                             {
                             if(str[j]<='z')
                            
                              str[j]=str[j]-32;
                               
                                 putchar(str[j]);
                               }
             else
            
             
              printf("%c",str[j]);
            
                 j++;
          }
           
            printf("\n");
            
                                                         for(i=0;i<j ;i++)
            
                                                                {
            
                                                                  if(str[i]=='\0')
            
           
           
                                                             {
            
                                                                    break;
            
           
                                                                }
            
           
                    
                                                                  else if(str1[i]>='A' && str1[i]<='Z')
            
                                                                      {
            
                                                                             str1[i]=str1[i]+32;
             
                                                                                  printf("%c",str1[i]);   
            
                                                                      }           
            
               else
               printf("%c",str1[i]);
                                    
              }
             getch();
               }

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

QUESTION 16 :

Modify the program in Q15 so that you first take input in a char array. Assume the array size to be 80. Your program should ask the user to input a sentence or his favorite quote and press “Enter” when done. Note that you should also make sure that the user does not enter more than 80 characters (i.e. the size of the array) including null terminator (‘\0’). When taking input you should display whatever the user is entering in UPPERCASE letters. After the user is done giving input, you should now display whatever he entered in lowercase letters. A sample output is shown below:

Answer(Code) :

#include<stdio.h>

#include<conio.h>

#include<string.h>

int main()

{

    char string1[80],string2[80];

   int n,i=0;

    printf("\t\t\tTwo Input Program \n\n");
    printf("\nEnter First String: ");

    gets(string1);
   
    printf("\n\nEnter Second String: ");

    gets(string2);
  
   
   
              if(strlen(string1) != strlen(string2))
              {
                  n=1;
               }
                 else
       
             
                 while (i<=n)
                                  
                      {
                       
                        if(string1[i]>='A' && string1[i]<='Z')
                    {
                    string1[i]=string1[i]+32;
                        i++;                        
                    }
                      else if(string2[i]>='A' && string2[i]<='Z')
                   {
                                                     
                   string2[i]=string2[i]+32;
                    }
                    n=string1[i]-string2[i];
                    i++;
              }
              
               printf("\n\n\nRESULT:\n");
                 if(n==0 )
{

              printf("\nBoth Strings are Similar");
}
                else
                {
               
             printf("\nBoth Strings are Different");

}

getch();
return 0;
}
=========================================================  


QUESTION 17 : 

Write a program that compares two strings after ignoring case. That is you want to mimic the functionality of strcmpi() function. For a complete program you should, declare two char arrays s1 and s2. Take input from user in s1 and s2. Then make an element by element comparison of the two strings. Two strings are similar if they satisfy the following two conditions:                                   
⦁    They both have same number of characters.
⦁    The order of characters in both the strings is same.
For example, “ABCD”, “Abcd”, “aBCd”, “abcd”, etc. are same, but “ABCD”, “ABC”, “ACBD”, “adbc”, “ab”, etc. are not.
Hint: I am providing code for string comparison which is case sensitive. You can modify this to make it case insensitive.


Answer(Code) :

#include<stdio.h>

#include<conio.h>

#include<string.h>

int main()

{

    char string1[80],string2[80];

   int n,i=0;

    printf("\t\t\tTwo Input Program \n\n");
    printf("\nEnter First String: ");

    gets(string1);
  
    printf("\n\nEnter Second String: ");

    gets(string2);
 
  
  
              if(strlen(string1) != strlen(string2))
              {
                  n=1;
               }
                 else
      
             
                 while (i<=n)
                                
                      {
                       
                        if(string1[i]>='A' && string1[i]<='Z')
                    {
                    string1[i]=string1[i]+32;
                        i++;                       
                    }
                      else if(string2[i]>='A' && string2[i]<='Z')
                   {
                                                    
                   string2[i]=string2[i]+32;
                    }
                    n=string1[i]-string2[i];
                    i++;
              }
              
               printf("\n\n\nRESULT:\n");
                 if(n==0 )
{

              printf("\nBoth Strings are Similar");
}
                else
                {
              
             printf("\nBoth Strings are Different");

}

getch();
return 0;
}


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

QUESTION 18 :

Now modify the program of Q17 so that your program compares only first n characters in the two strings after ignoring case. That is you want to mimic the functionality of strncmpi() function. For a complete program you should, declare two char arrays s1 and s2. Take input from user in s1 and s2. Then ask user to input n, which indicates the number of characters to be considered in comparison. Then make an element by element comparison of first n characters in the two strings. The criteria for similarity is as follows:        
⦁    If the lengths of both strings are greater than n, then the two strings are considered same if the characters and their order are same in both the strings for only the first n characters.
⦁    If the length of any one of the strings is less than n, then:
⦁    If there lengths are different then they are NOT the same.
⦁    If there lengths are same then they ARE same ONLY if ALL of the characters and their order is same.
For example, if we want to compare only the first 4 characters then “STRING”, “String”, “string”, “strings123”, “stri”, “StRiNgS”, etc. are all the same, but “STRING”, “str”, “S1tring”, “STR1NG”, “GNIRTS”, etc. are NOT.
Hint: I am providing code for string comparison which is case sensitive. You can modify this to make it case insensitive and take care of n.


Answer(Code) :

#include<stdio.h>

#include<conio.h>

#include<string.h>

int main()

{

    char string1[80],string2[80];

   int n,i=0,d;

    printf("\t\t\tTwo Input Program \n\n");
    printf("\nEnter First String: ");

    gets(string1);
  
    printf("\n\nEnter Second String: ");

    gets(string2);
 
    printf("\nWhat you Want To Search In array:");
  
    scanf("%d",&d);
  
  
    if((strlen(string1) != strlen(string2)) || d>=strlen(string2) || d>=strlen(string1) )
              {
                  n=1;
               }
                 else
      
             
                 while (i<=n)
                                
                      {
                       
                        if(string1[i]>='A' && string1[i]<='Z')
                    {
                    string1[i]=string1[i]+32;
                        i++;                       
                    }
                      else if(string2[i]>='A' && string2[i]<='Z')
                   {
                                                    
                   string2[i]=string2[i]+32;
                    }
                    n=string1[i]-string2[i];
                    i++;
              }
              
               printf("\n\n\nRESULT:\n");
                 if(n==0 )
{

              printf("\nBoth Strings are Similar");
}
                else
                {
              
             printf("\nBoth Strings are Different");

}

getch();

return 0;
}

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

QUESTION 19 :

Write a program that copies first n characters of a string (char array) into another string (char array). That is you have to write a program that mimics strncpy(dest, src, n) function. For a complete program, you should take input from the user using gets() in a char array of size 80, call it src. Then ask the user to enter the number of characters (n) the user wants to copy into another char array of size 50, call it dest. Make sure you take care of array bounds. That is: your program should be robust to following situations:            20 marks
⦁    n may be larger than valid number of characters (string length) in src. You can use strlen() function to find the length of a string
⦁    The user may have entered more than 50 characters as input in src, but dest array is of size 50.
 

Answer(Code) :

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

main()
 {

     char src[80],dest[50];
     int i=0, n,d;
    
     d=strlen(dest);
          printf("\t\t\tProgram : Number of Character Counter\n\n");
     printf("Enter Your Characters:");
     
      gets(src);
     
     
      while (i<=50)
     
      {
     
          dest[i]=src[i];
      i++;
      }
     
     
    
     printf("\nEnter the Number Of Characters Which You Want to Copy:");
    
   
     scanf("%d",&n);
    
 if( n>strlen(src) )

     {
      if( n>50 )
   
         printf("\n================================\n");


         printf("\nWrong Input !!");

    
    }
   
    else
    {
   
         printf("\n================================\n");

    printf("\nCopied first %d Characters\n\n",n);
   
for(i=0;i<n;i++)
     {
        
        
         putchar(dest[i]);

     }
 }

     getch();
 return 0;
 }
 


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

QUESTION 20 :

 Write a program that asks user to input his favorite quote. Then construct a histogram (frequency table) of alphabets. Your program should be insensitive to case of alphabets, i.e. UPPERCASE and lowercase letters are considered to be the same.      
Hint: We did a histogram program in the class. Use similar logic. Your histogram now has 26 bins, which is equal to number of alphabets in English language. 


Answer(Code) :
 #include <stdio.h>
#include<conio.h>
#include<string.h>


main()
{
  
    int c, i, x;
  
  
    int length[200];


        for(x = 0; x < 200 ;x++)
      
        length[x] = 0;
      
        printf("Enter characters:\n");
      
                  while( (c = getchar() ) != '\n')
                  { 
                  if(c>='A')
                    {
                        if( c<='Z')
                      
                      c=c+32;
                     }
                  
                         length[c]++;
                            if (c == '\n')
                               getch();   // we can use break command as well.
                          }


                                for(x = 0; x < 200; x++)
                               {
                                    if( length[x] > 0)
                                   {
                                        printf("%c: ", x);
                                            for(i = 0; i < length[x]; i++)
                                            {
                                                printf("*");
                                      }
                                                 printf("\n");
                                   }
                              
                                }
                              
    getch();
}











































0 comments:

Post a Comment

 

Copyright @ 2013 Haqk Articles.