SlideShare une entreprise Scribd logo
1  sur  33
Exercises on Structures and Strings




Spring      Programming and   1
Q. 1
  Define a structure data-type named
  _PLAYER which has the following
   members:

  Name: A string of 30 characters.
  DOB: A string of 10 characters.
  Height: A floating point number.
  Weight: A floating point number.


Spring      Programming and   2
Structure Definition
typedef struct{
     char Name[31];
      char DOB[11];
      float Height;
      float Weight;
      } _PLAYER;

Spring       Programming and   3
Q. 2
  Write a main program which
  reads records of N players
  (N to be read from the
  keyboard) in an array of
  _PLAYER and prints their
  names and dates of birth.


Spring   Programming and   4
Structure Definition

   #include <stdio.h>
   #define MAX_NO 100

   typedef struct {
                   char Name[31];
                   char DOB[11];
                   float Height;
                   float Weight;
                    } _PLAYER;



Spring        Programming and       5
Reading and Printing
main()         printf("DOB as dd/mm/yyyy? n");
{ _PLAYER pl[MAX_NO]; %[^n]",pl[i].DOB);
               scanf(“
 int N,i;
                   printf("Height (cm.) and Weight (kg) ? n");
 printf("Give the number of players n");
 scanf("%d",&N); scanf("%f%f",&pl[i].Height,&pl[i].Weight);
                  }
 for(i=0;i<N;i++) printf("Data read n");
 { printf("Input the %d th player n",i+1);

    printf("Name? n ");
printf("Printing Name and Dates of Births n");
    scanf(“ %[^n]",pl[i].Name);
for(i=0;i<N;i++)
 {
   printf("Player[%d]--> %s %s n",i,pl[i].Name,pl[i].DOB);
  } Spring            Programming and         6
Q. 3
 Write a function which takes
 an array of _PLAYER as a
 parameter and returns the
 tallest player by deleting the
 player from the list and
 adjusting the array by moving
 the elements upward.

Spring    Programming and   7
Function Implementation
_PLAYER tallest_player(_PLAYER p[ ], int N)
 {          Computing the array index for the tallest player
   int i;
   float maxHeight=-1;
   int maxPos;
 _PLAYER tmp;

 for(i=0;i<N;i++)                    tmp=p[maxPos];
 {                                     for(i=maxPos+1;i<N;i++)
    if (p[i].Height > maxHeight)
    {     Return Tallest Player             p[i-1]=p[i];
      maxPos=i;                          return(tmp);
      maxHeight=p[i].Height;            }
     }
   } Spring            Deleting a player and readjusting array
                        Programming and           8
Q. 4
   Use this function to print the
   Names of players in the
   descending order of their
   heights.




Spring     Programming and   9
Printing in ascending order of heights
main()            printf("DOB as dd/mm/yyyy? n");
{ _PLAYER pl[MAX_NO]; %[^n]",pl[i].DOB);
                  scanf("
 int N,i;
 _PLAYER tallest; printf("Height (cm.) and Weight (kg) ? n");

 printf("Give the number of players n");
                   scanf("%f%f",&pl[i].Height,&pl[i].Weight);
 scanf("%d",&N); }
                    printf("Data read n");
   for(i=N;i>1;i--)
 for(i=0;i<N;i++)
 { { printf("Input the %d th player n",i+1);
      tallest=tallest_player(pl,i);
       printf("%s Height=%f n",tallest.Name,tallest.Height);
     printf("Name? n ");
     }
     scanf("%[^n]",pl[i].Name);
     printf("%s Height=%f n",pl[0].Name,pl[0].Height);
   }
      Spring            Programming and        10
Q. 5
(a)Write a function isLC( )
  which takes a character as
  an input and returns 1 if it is
  a lower case alphabet else 0.
(b)Write the corresponding
  function isUC( ) for checking
  an upper case alphabet.

Spring    Programming and   11
Functions for checking alphabet cases


int isLC(char c)          int isUC(char c)
{                         {
  if((c>='a') && (c<='z')) if((c>='A') &&
    return 1;                (c<='Z'))
  else                        return 1;
    return 0;               else
}                             return 0;
                          }


   Spring        Programming and    12
Q. 6

  Write a function toLC( ) which
  takes a string as an input and
  replaces all the Upper Case
  alphabets to lower cases
  within it. The function also
  returns the number of
  changes it made.

Spring    Programming and   13
int toLC(char s[ ])
{
  int i, nChange=0;

  for(i=0; s[i]!=0; i++)
  {
    if ((s[i]>='A') && (s[i]<='Z'))
     {
      s[i]=s[i]-('A'-'a');
      nChange++;
     }
   }
    return nChange;
}
Spring         Programming and        14
Q. 6-a

• Write the recursive
  implementation of toLC( )
  for converting Upper
  Cases to Lower Case.



Spring   Programming and   15
int toLC(char s[ ],int pos)
  {
    if(s[pos]==0)
       return 0;

   else

    if((s[pos]>='A') && (s[pos]<='Z'))
     {
      s[pos]=s[pos]-('A'-'a');
      return 1+toLC(s,pos+1);
     }

    else
     return toLC(s,pos+1);
  }
Spring         Programming and      16
Q. 7

• Write a function
  complementString( ) which
  complements an input
  string by changing the
  cases of its alphabets. The
  function also returns the
  number of changes.
Spring   Programming and   17
nt complementString(char s[ ])

int i,nChange=0;              If (isLC(s[i]))
                                   {
i=0;                                s[i]=s[i]+('A'-'a');
while(s[i]!=0)                      nChange++;
{                                  };
if (isUC(s[i]))                  i++;
 {                              }
    s[i]=s[i]-('A'-'a');          return nChange;
    nChange++;                }
 }
 else
     Spring           Programming and        18
Q. 8
• (a) Write a function absd( ) which
  takes a value in double data-type and
  returns its absolute value in double.
• (b) Write a function expd( ) which
  computes ex for an input variable x
  (of double data type) by computing
  the following series summation with
  an accuracy of .0001.
 ex= 1 + x/1! + x2/2!+ x3/3!+…………..

Spring      Programming and   19
double expd(double x)
                          {
                           double sum,term;
                           double error_bound=.0001;
ouble absd(double x)       int i;

 f(x<0) return -x;        term=1;
else return x;            sum=1;
                          i=0;

                          while(absd(term)>error_bound)
actorial is not           {
omputed directly.          i++;
                           term=term*x/(double) i;
     Xn/n!                 sum=sum+term;
                          }

                           return(sum);
       Spring          Programming and       20
Q 8 (contd.)
• Write a program which
  computes exponential of
  values (to be read from the
  keyboard) in an infinite loop.




Spring    Programming and   21
nclude <stdio.h>           main()
                           {
ouble absd (double x)        double y,val;

                           while(1)
                           {
                            printf("Give y: ");
                            scanf("%lf",&y);
ouble expd (double x)
                            val=expd(y);
ive y: 1                   printf("y= %lf exp(y)=%lf n",y,val);
= 1.000000 exp(y)=2.718279}
ive y: -1                }
= -1.000000 exp(y)=0.367882
ive y: 23
= 23.000000 exp(y)=9744803446.248880
ive y: ^C
      Spring          Programming and          22
Q. 9
• Write a function which returns square root
  of a floating point value with an accuracy
  of .00001, following the Newton-Raphson
  method.
• Newton-Raphson method:
     Solve: f(x)=0
     Iteration: xn+1= xn- f(xn)/f’(xn)
• Newton-Raphson method for square root:
     f(x)=x2-a
  Iteration: xn+1= xn- (xn2 –a)/2xn

Spring        Programming and     23
oat newton_sqrt (float x)

loat error,xinit,xold,xnew;
                                         main()
nt iter_no=0;
                                         {
                                         float a,root;
f(x<=0) return (-1);
                                         printf(“Input a? n");
init=x;
                                         scanf("%f",&a);
old=xinit;
                                         printf(“a= %f n",a);
do {
    xnew=xold- (xold*xold-x)/(2*xold);
                                         root=newton_sqrt(a);
    error= xnew-xold;
                                         if(root>0)
    if(error<0) error=-error;
                                         printf("%f n",root);
    xold=xnew;
                                         }
    iter_no++;
  } while(error>.00001);
 return(xold);
      Spring           Programming and          24
Q.10
• (a) Define a structure _PNT
  which has x-coordinate and y-
  coordinate (both of float data-
  type) as its members for
  representing a point in a 2-D
  space.
• (b) Write a function dist() which
  takes two points and returns the
  distance between them.
Spring     Programming and   25
typedef struct{
    float x,y;
    } _PNT;
float dist(_PNT a, _PNT b)
{
  float d;
  d=(a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y);
  if(d>0)
   return((float)sqrt((double)d));
  else
   return(0);
} Spring         Programming and 26
Q. 10
• (c) Define a function checkCircle( ) which
  takes center and radius of a circle and a
  point p as inputs and returns -1, 0 or 1 if p
  is outside, or, on its perimeter or inside
  the circle respectively. Use the function
  dist( ).
• (d) Write a main( ) function to read center
  and radius of a circle and a query point q.
  The program should print whether the
  point is outside or inside or on the circle.

Spring         Programming and       27
int checkCircle(_PNT c, float R, _PNT p)
{
  float d;

    d=dist(c,p);

    if(d>R) return (-1);
    else if (d<R) return(1);
        else return(0);
}

     Spring        Programming and   28
Read the center of circle
  40 50
main( )
{ Read the radius of circle switch(flag)
  10
 _PNT oc,p;                   {
 float R; point
  Read a
                               case 1: printf("Inside n");
  35 25
 int flag;                         break;
  Outside
                               case -1: printf("Outside n");
 printf("Read the center            break;
  n");                        case 0: printf("On circle n");
 scanf("%f%f",&oc.x,&oc.y);        break;
 printf("Read the radius       default:
  n");
                                   printf("?? n");
 scanf("%f",&R);
                              }
 printf("Read a point n");
                            }
 scanf("%f%f",&p.x,&p.y);

 flag=checkCircle(oc,R,p);

    Spring            Programming and         29
Q. 11
• (a) Write a function mean( )
  which takes an array of N
  floating point numbers and
  computes their mean.
• (b) Write another function
  named sd( ) for same input
  for computing standard
  deviation. Use mean( ).
Spring    Programming and   30
oat mean(float x[ ],int N)     float sd(float x[ ],int N)
                               {
 nt i;                           int i;
float sum=0;                     float sum=0, sqrsum=0;
                                 float mu, var, sigma;
for(i=0;i<N;i++)
 sum+=x[i];                     for(i=0;i<N;i++)
                                 sqrsum+=x[i]*x[i];
eturn(sum/(float)N);
                                 mu=mean(x,N);
                                 var=sqrsum/(float) N-mu*mu;

                                 if(var>0)

                                  sigma=(float)sqrt((float)var);
                                 else
                                   sigma=0;

      Spring            Programming and
                                return(sigma); 31
Q. 11 (contd.)
• Write a main program to read
  N values in an array and
  compute their mean and
  standard deviation.




Spring    Programming and   32
main()
#include <stdio.h>    {
#include <math.h>      int i,N;
                       float height[MAX_NO];
#define MAX_NO 100
                          printf("Input N? n");
float mean(float x [ ],int N)
                          scanf("%d",&N);
{
:                         printf("Give %d values n",N);
}                         for(i=0;i<N;i++)
                           scanf("%f",&height[i]);
   Input N?
float sd(float x[ ],int N)
{ 5                       printf("Mean= %f n",mean(height,N));
: Give 5 values           printf("S.D.= %f n",sd(height,N));
} 5 10 20 30 40          }
   Mean= 21.000000
   S.D.= 12.806249

     Spring           Programming and          33

Contenu connexe

Tendances

SupportVectorRegression
SupportVectorRegressionSupportVectorRegression
SupportVectorRegression
Daniel K
 
C Prog. - Strings (Updated)
C Prog. - Strings (Updated)C Prog. - Strings (Updated)
C Prog. - Strings (Updated)
vinay arora
 

Tendances (20)

SE Computer, Programming Laboratory(210251) University of Pune
SE Computer, Programming Laboratory(210251) University of PuneSE Computer, Programming Laboratory(210251) University of Pune
SE Computer, Programming Laboratory(210251) University of Pune
 
Atomically { Delete Your Actors }
Atomically { Delete Your Actors }Atomically { Delete Your Actors }
Atomically { Delete Your Actors }
 
Computer Graphics Lab
Computer Graphics LabComputer Graphics Lab
Computer Graphics Lab
 
Computer graphics lab manual
Computer graphics lab manualComputer graphics lab manual
Computer graphics lab manual
 
Practical Class 12th (c++programs+sql queries and output)
Practical Class 12th (c++programs+sql queries and output) Practical Class 12th (c++programs+sql queries and output)
Practical Class 12th (c++programs+sql queries and output)
 
Monadologie
MonadologieMonadologie
Monadologie
 
COMPUTER GRAPHICS LAB MANUAL
COMPUTER GRAPHICS LAB MANUALCOMPUTER GRAPHICS LAB MANUAL
COMPUTER GRAPHICS LAB MANUAL
 
C program
C programC program
C program
 
C programs
C programsC programs
C programs
 
Graphics practical lab manual
Graphics practical lab manualGraphics practical lab manual
Graphics practical lab manual
 
COMPUTER SCIENCE CLASS 12 PRACTICAL FILE
COMPUTER SCIENCE CLASS 12 PRACTICAL FILECOMPUTER SCIENCE CLASS 12 PRACTICAL FILE
COMPUTER SCIENCE CLASS 12 PRACTICAL FILE
 
SupportVectorRegression
SupportVectorRegressionSupportVectorRegression
SupportVectorRegression
 
C Prog. - Strings (Updated)
C Prog. - Strings (Updated)C Prog. - Strings (Updated)
C Prog. - Strings (Updated)
 
VTU Data Structures Lab Manual
VTU Data Structures Lab ManualVTU Data Structures Lab Manual
VTU Data Structures Lab Manual
 
ADA FILE
ADA FILEADA FILE
ADA FILE
 
Cs practical file
Cs practical fileCs practical file
Cs practical file
 
Chapter 7 functions (c)
Chapter 7 functions (c)Chapter 7 functions (c)
Chapter 7 functions (c)
 
Pnno
PnnoPnno
Pnno
 
Futures e abstração - QCon São Paulo 2015
Futures e abstração - QCon São Paulo 2015Futures e abstração - QCon São Paulo 2015
Futures e abstração - QCon São Paulo 2015
 
Data Structure Project File
Data Structure Project FileData Structure Project File
Data Structure Project File
 

En vedette (9)

L11 tree
L11 treeL11 tree
L11 tree
 
L2 number
L2 numberL2 number
L2 number
 
L3 control
L3 controlL3 control
L3 control
 
L4 functions
L4 functionsL4 functions
L4 functions
 
Snns
SnnsSnns
Snns
 
Extra problem for 1st yr
Extra problem for 1st yrExtra problem for 1st yr
Extra problem for 1st yr
 
Elimination
EliminationElimination
Elimination
 
19 - Amines - Wade 7th
19 - Amines - Wade 7th19 - Amines - Wade 7th
19 - Amines - Wade 7th
 
Aminas
AminasAminas
Aminas
 

Similaire à Struct examples

Numerical analysis
Numerical analysisNumerical analysis
Numerical analysis
Vishal Singh
 
C interview question answer 2
C interview question answer 2C interview question answer 2
C interview question answer 2
Amit Kapoor
 
C aptitude.2doc
C aptitude.2docC aptitude.2doc
C aptitude.2doc
Srikanth
 
1sequences and sampling. Suppose we went to sample the x-axis from X.pdf
1sequences and sampling. Suppose we went to sample the x-axis from X.pdf1sequences and sampling. Suppose we went to sample the x-axis from X.pdf
1sequences and sampling. Suppose we went to sample the x-axis from X.pdf
rushabhshah600
 

Similaire à Struct examples (20)

L25-L26-Parameter passing techniques.pptx
L25-L26-Parameter passing techniques.pptxL25-L26-Parameter passing techniques.pptx
L25-L26-Parameter passing techniques.pptx
 
C lab manaual
C lab manaualC lab manaual
C lab manaual
 
C programming
C programmingC programming
C programming
 
Basic c programs updated on 31.8.2020
Basic c programs updated on 31.8.2020Basic c programs updated on 31.8.2020
Basic c programs updated on 31.8.2020
 
Cpds lab
Cpds labCpds lab
Cpds lab
 
LET US C (5th EDITION) CHAPTER 2 ANSWERS
LET US C (5th EDITION) CHAPTER 2 ANSWERSLET US C (5th EDITION) CHAPTER 2 ANSWERS
LET US C (5th EDITION) CHAPTER 2 ANSWERS
 
data structure and algorithm.pdf
data structure and algorithm.pdfdata structure and algorithm.pdf
data structure and algorithm.pdf
 
DataStructures notes
DataStructures notesDataStructures notes
DataStructures notes
 
7 functions
7  functions7  functions
7 functions
 
Solutionsfor co2 C Programs for data structures
Solutionsfor co2 C Programs for data structuresSolutionsfor co2 C Programs for data structures
Solutionsfor co2 C Programs for data structures
 
Numerical analysis
Numerical analysisNumerical analysis
Numerical analysis
 
C interview question answer 2
C interview question answer 2C interview question answer 2
C interview question answer 2
 
Functions
FunctionsFunctions
Functions
 
Data Structure in C Programming Language
Data Structure in C Programming LanguageData Structure in C Programming Language
Data Structure in C Programming Language
 
Introduction to Basic C programming 02
Introduction to Basic C programming 02Introduction to Basic C programming 02
Introduction to Basic C programming 02
 
Let us C (by yashvant Kanetkar) chapter 3 Solution
Let us C   (by yashvant Kanetkar) chapter 3 SolutionLet us C   (by yashvant Kanetkar) chapter 3 Solution
Let us C (by yashvant Kanetkar) chapter 3 Solution
 
C aptitude.2doc
C aptitude.2docC aptitude.2doc
C aptitude.2doc
 
Captitude 2doc-100627004318-phpapp01
Captitude 2doc-100627004318-phpapp01Captitude 2doc-100627004318-phpapp01
Captitude 2doc-100627004318-phpapp01
 
All important c programby makhan kumbhkar
All important c programby makhan kumbhkarAll important c programby makhan kumbhkar
All important c programby makhan kumbhkar
 
1sequences and sampling. Suppose we went to sample the x-axis from X.pdf
1sequences and sampling. Suppose we went to sample the x-axis from X.pdf1sequences and sampling. Suppose we went to sample the x-axis from X.pdf
1sequences and sampling. Suppose we went to sample the x-axis from X.pdf
 

Plus de mondalakash2012 (6)

Sn reaction
Sn reactionSn reaction
Sn reaction
 
Part i
Part iPart i
Part i
 
L12 complexity
L12 complexityL12 complexity
L12 complexity
 
L10 sorting-searching
L10 sorting-searchingL10 sorting-searching
L10 sorting-searching
 
L8 file
L8 fileL8 file
L8 file
 
L6 structure
L6 structureL6 structure
L6 structure
 

Struct examples

  • 1. Exercises on Structures and Strings Spring Programming and 1
  • 2. Q. 1 Define a structure data-type named _PLAYER which has the following members: Name: A string of 30 characters. DOB: A string of 10 characters. Height: A floating point number. Weight: A floating point number. Spring Programming and 2
  • 3. Structure Definition typedef struct{ char Name[31]; char DOB[11]; float Height; float Weight; } _PLAYER; Spring Programming and 3
  • 4. Q. 2 Write a main program which reads records of N players (N to be read from the keyboard) in an array of _PLAYER and prints their names and dates of birth. Spring Programming and 4
  • 5. Structure Definition #include <stdio.h> #define MAX_NO 100 typedef struct { char Name[31]; char DOB[11]; float Height; float Weight; } _PLAYER; Spring Programming and 5
  • 6. Reading and Printing main() printf("DOB as dd/mm/yyyy? n"); { _PLAYER pl[MAX_NO]; %[^n]",pl[i].DOB); scanf(“ int N,i; printf("Height (cm.) and Weight (kg) ? n"); printf("Give the number of players n"); scanf("%d",&N); scanf("%f%f",&pl[i].Height,&pl[i].Weight); } for(i=0;i<N;i++) printf("Data read n"); { printf("Input the %d th player n",i+1); printf("Name? n "); printf("Printing Name and Dates of Births n"); scanf(“ %[^n]",pl[i].Name); for(i=0;i<N;i++) { printf("Player[%d]--> %s %s n",i,pl[i].Name,pl[i].DOB); } Spring Programming and 6
  • 7. Q. 3 Write a function which takes an array of _PLAYER as a parameter and returns the tallest player by deleting the player from the list and adjusting the array by moving the elements upward. Spring Programming and 7
  • 8. Function Implementation _PLAYER tallest_player(_PLAYER p[ ], int N) { Computing the array index for the tallest player int i; float maxHeight=-1; int maxPos; _PLAYER tmp; for(i=0;i<N;i++) tmp=p[maxPos]; { for(i=maxPos+1;i<N;i++) if (p[i].Height > maxHeight) { Return Tallest Player p[i-1]=p[i]; maxPos=i; return(tmp); maxHeight=p[i].Height; } } } Spring Deleting a player and readjusting array Programming and 8
  • 9. Q. 4 Use this function to print the Names of players in the descending order of their heights. Spring Programming and 9
  • 10. Printing in ascending order of heights main() printf("DOB as dd/mm/yyyy? n"); { _PLAYER pl[MAX_NO]; %[^n]",pl[i].DOB); scanf(" int N,i; _PLAYER tallest; printf("Height (cm.) and Weight (kg) ? n"); printf("Give the number of players n"); scanf("%f%f",&pl[i].Height,&pl[i].Weight); scanf("%d",&N); } printf("Data read n"); for(i=N;i>1;i--) for(i=0;i<N;i++) { { printf("Input the %d th player n",i+1); tallest=tallest_player(pl,i); printf("%s Height=%f n",tallest.Name,tallest.Height); printf("Name? n "); } scanf("%[^n]",pl[i].Name); printf("%s Height=%f n",pl[0].Name,pl[0].Height); } Spring Programming and 10
  • 11. Q. 5 (a)Write a function isLC( ) which takes a character as an input and returns 1 if it is a lower case alphabet else 0. (b)Write the corresponding function isUC( ) for checking an upper case alphabet. Spring Programming and 11
  • 12. Functions for checking alphabet cases int isLC(char c) int isUC(char c) { { if((c>='a') && (c<='z')) if((c>='A') && return 1; (c<='Z')) else return 1; return 0; else } return 0; } Spring Programming and 12
  • 13. Q. 6 Write a function toLC( ) which takes a string as an input and replaces all the Upper Case alphabets to lower cases within it. The function also returns the number of changes it made. Spring Programming and 13
  • 14. int toLC(char s[ ]) { int i, nChange=0; for(i=0; s[i]!=0; i++) { if ((s[i]>='A') && (s[i]<='Z')) { s[i]=s[i]-('A'-'a'); nChange++; } } return nChange; } Spring Programming and 14
  • 15. Q. 6-a • Write the recursive implementation of toLC( ) for converting Upper Cases to Lower Case. Spring Programming and 15
  • 16. int toLC(char s[ ],int pos) { if(s[pos]==0) return 0; else if((s[pos]>='A') && (s[pos]<='Z')) { s[pos]=s[pos]-('A'-'a'); return 1+toLC(s,pos+1); } else return toLC(s,pos+1); } Spring Programming and 16
  • 17. Q. 7 • Write a function complementString( ) which complements an input string by changing the cases of its alphabets. The function also returns the number of changes. Spring Programming and 17
  • 18. nt complementString(char s[ ]) int i,nChange=0; If (isLC(s[i])) { i=0; s[i]=s[i]+('A'-'a'); while(s[i]!=0) nChange++; { }; if (isUC(s[i])) i++; { } s[i]=s[i]-('A'-'a'); return nChange; nChange++; } } else Spring Programming and 18
  • 19. Q. 8 • (a) Write a function absd( ) which takes a value in double data-type and returns its absolute value in double. • (b) Write a function expd( ) which computes ex for an input variable x (of double data type) by computing the following series summation with an accuracy of .0001. ex= 1 + x/1! + x2/2!+ x3/3!+………….. Spring Programming and 19
  • 20. double expd(double x) { double sum,term; double error_bound=.0001; ouble absd(double x) int i; f(x<0) return -x; term=1; else return x; sum=1; i=0; while(absd(term)>error_bound) actorial is not { omputed directly. i++; term=term*x/(double) i; Xn/n! sum=sum+term; } return(sum); Spring Programming and 20
  • 21. Q 8 (contd.) • Write a program which computes exponential of values (to be read from the keyboard) in an infinite loop. Spring Programming and 21
  • 22. nclude <stdio.h> main() { ouble absd (double x) double y,val; while(1) { printf("Give y: "); scanf("%lf",&y); ouble expd (double x) val=expd(y); ive y: 1 printf("y= %lf exp(y)=%lf n",y,val); = 1.000000 exp(y)=2.718279} ive y: -1 } = -1.000000 exp(y)=0.367882 ive y: 23 = 23.000000 exp(y)=9744803446.248880 ive y: ^C Spring Programming and 22
  • 23. Q. 9 • Write a function which returns square root of a floating point value with an accuracy of .00001, following the Newton-Raphson method. • Newton-Raphson method: Solve: f(x)=0 Iteration: xn+1= xn- f(xn)/f’(xn) • Newton-Raphson method for square root: f(x)=x2-a Iteration: xn+1= xn- (xn2 –a)/2xn Spring Programming and 23
  • 24. oat newton_sqrt (float x) loat error,xinit,xold,xnew; main() nt iter_no=0; { float a,root; f(x<=0) return (-1); printf(“Input a? n"); init=x; scanf("%f",&a); old=xinit; printf(“a= %f n",a); do { xnew=xold- (xold*xold-x)/(2*xold); root=newton_sqrt(a); error= xnew-xold; if(root>0) if(error<0) error=-error; printf("%f n",root); xold=xnew; } iter_no++; } while(error>.00001); return(xold); Spring Programming and 24
  • 25. Q.10 • (a) Define a structure _PNT which has x-coordinate and y- coordinate (both of float data- type) as its members for representing a point in a 2-D space. • (b) Write a function dist() which takes two points and returns the distance between them. Spring Programming and 25
  • 26. typedef struct{ float x,y; } _PNT; float dist(_PNT a, _PNT b) { float d; d=(a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y); if(d>0) return((float)sqrt((double)d)); else return(0); } Spring Programming and 26
  • 27. Q. 10 • (c) Define a function checkCircle( ) which takes center and radius of a circle and a point p as inputs and returns -1, 0 or 1 if p is outside, or, on its perimeter or inside the circle respectively. Use the function dist( ). • (d) Write a main( ) function to read center and radius of a circle and a query point q. The program should print whether the point is outside or inside or on the circle. Spring Programming and 27
  • 28. int checkCircle(_PNT c, float R, _PNT p) { float d; d=dist(c,p); if(d>R) return (-1); else if (d<R) return(1); else return(0); } Spring Programming and 28
  • 29. Read the center of circle 40 50 main( ) { Read the radius of circle switch(flag) 10 _PNT oc,p; { float R; point Read a case 1: printf("Inside n"); 35 25 int flag; break; Outside case -1: printf("Outside n"); printf("Read the center break; n"); case 0: printf("On circle n"); scanf("%f%f",&oc.x,&oc.y); break; printf("Read the radius default: n"); printf("?? n"); scanf("%f",&R); } printf("Read a point n"); } scanf("%f%f",&p.x,&p.y); flag=checkCircle(oc,R,p); Spring Programming and 29
  • 30. Q. 11 • (a) Write a function mean( ) which takes an array of N floating point numbers and computes their mean. • (b) Write another function named sd( ) for same input for computing standard deviation. Use mean( ). Spring Programming and 30
  • 31. oat mean(float x[ ],int N) float sd(float x[ ],int N) { nt i; int i; float sum=0; float sum=0, sqrsum=0; float mu, var, sigma; for(i=0;i<N;i++) sum+=x[i]; for(i=0;i<N;i++) sqrsum+=x[i]*x[i]; eturn(sum/(float)N); mu=mean(x,N); var=sqrsum/(float) N-mu*mu; if(var>0) sigma=(float)sqrt((float)var); else sigma=0; Spring Programming and return(sigma); 31
  • 32. Q. 11 (contd.) • Write a main program to read N values in an array and compute their mean and standard deviation. Spring Programming and 32
  • 33. main() #include <stdio.h> { #include <math.h> int i,N; float height[MAX_NO]; #define MAX_NO 100 printf("Input N? n"); float mean(float x [ ],int N) scanf("%d",&N); { : printf("Give %d values n",N); } for(i=0;i<N;i++) scanf("%f",&height[i]); Input N? float sd(float x[ ],int N) { 5 printf("Mean= %f n",mean(height,N)); : Give 5 values printf("S.D.= %f n",sd(height,N)); } 5 10 20 30 40 } Mean= 21.000000 S.D.= 12.806249 Spring Programming and 33