Welcome to the World of Modelling and Simulation

What is Modelling?

This blog is all about system dynamics modelling and simulation applied in the engineering field, especially mechanical, electrical, and ...

C Programming and Applications: Questions and Solutions for Practice - I

1. Write an appropriate function call (function access) for each of the following functions.


(a)
float  formula(float x)
{
      float y;
      y=(3*x-1);
      return (y);
      }

Answer: y=formula(x)

(b)
void  display(int a,int b)
{
     int c;
     c=sqrt(a*a+b*b);
     printf("c=%d\n",c);
     }

Answer: display(a,b)



2. Write down the output generated by each of the following programs.



(a)
#include  <stdio.h>
int funct(int count);
main ( )
{
     int a,count;
     for(count=1; count<=5; ++count)
     {
                  a=funct1(count);
                  printf("%d",a);
                  }
                  }
int funct1(int x)
{
    int y;
    y=x*x;
    return(y);
}

Answer: 1   4   9   16   25

(b)
#include <stdio.h>
int funct1(int n);
main ( )
{
     int n=10;
     printf("%d",funct1(n));
     }
int funct1(int n)
{
    if(n>0) return(n+funct1(n-1));
}

Answer: 55

(c)
#include <stdio.h>
int  funct1(int n);
main ( )
{
     int n=10;
     printf("%d",funct1(n));
     }
int funct1(int n)
{
    if(n>0) return(n+funct1(n-2));
}

Answer: 30

(d)
#include <stdio.h>
main  ( )
{    int i=0,x=0;
     for(i=1; i<10; i*=2)
     {x++;
     printf("%d",x);}
     printf("\nx=%d",x);}

Answer: 1   2   3   4;    x=4

(e)
#include <stdio.h>
main  ( )
{    int i,j,x=0;
     for(i=0; i<5; ++i)
     for(j=0; j<i; ++j)
     {x+=(i+j-1);
     printf("%d",x);
     break;}
     printf("\nx=%d",x);}

Answer: 0;   x=0


3. Write a complete program to calculate the average of n numbers and then compute the deviation of each number about the average.     


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

main ()
{
     int n,count;
     float avg,d,sum=0;
     float list[100];
    
     printf("\nHow many numbers will be averaged?");
     scanf("%d",&n);
     printf("\n");
    
     for(count=0; count<n; ++count)
     {printf("i=%d x=",count);
     scanf("%f",&list[count]);
     sum+=list[count];
     }
     avg=sum/n;
     printf("\nThe average is %f\n\n",avg);
    
     for(count=0; count<n; ++count)
     {
                  d=list[count]-avg;
                  printf("i=%d x=%f d=%f\n", count,list[count],d);
                  }
                  getch ();
                  } 

4. Why getch() is used as the last statement of many programs?



getch function prompts the user to press a character and that character is not printed on screen, getch header file is conio.h. Common use of getch is that you can view the output (if any) of your program without having to open the output window if you are using turbo c compiler or if you are not running your program from command prompt.

No comments:

Post a Comment