Free Software Movement Karnataka www.fsmk.org } C PROGRAMMING LABORATORY (18CPL17/27) I\II Semester (common to all branches) LAB MANUAL } Prabodh C P Asst Professor Dept of CSE, SIT Volunteer, FSMK This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License. To veiw a copy of this license, visit https://creativecommons.org/licenses/by-nc-sa/4.0/
44
Embed
C PROGRAMMING LABORATORY (18CPL17/27)Finally you will be prompted to choose the compiler. Just choose the default options here (Dont change the options). You should be using GNU GCC
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Free Software Movement Karnatakawww.fsmk.org }
C PROGRAMMING LABORATORY (18CPL17/27)
I\II Semester(common to all branches)
LAB MANUAL}Prabodh C PAsst Professor
Dept of CSE, SIT
Volunteer, FSMK
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.To veiw a copy of this license, visit https://creativecommons.org/licenses/by-nc-sa/4.0/
0.1 Using Code::Blocks to compile and execute a C Program
To launch Code::Blocks IDE, Click onApplications → Programming → Code::Blocks IDEYou will get a window as shown below
5
0.1. USING CODE::BLOCKS TO COMPILE AND EXECUTE A C PROGRAM
Code::Blocks creates what is called a Workspace to keep track of the project you are working on. It is possible foryou to be working on multiple projects within your workspace. A project is a collection of one or more source (aswell as header) files. Source files are the files that contain the source code for your program. If you are developinga C program, you are writing C source code (.c files).
First start a new Project by clicking on Create a new projectOR To create a project, click on the File pull-down menu, open New and then Project.You get this pop-upwindow
Choose Console applicationThen in the next window select the programming language C (and not C++)
In the next step give the Project Title and specify the folder where you want to save your project.(Note : Dont use any special characters or whitespaces for project title and folder names)
Dept of CSE, SIT - CPP 6
0.1. USING CODE::BLOCKS TO COMPILE AND EXECUTE A C PROGRAM
Finally you will be prompted to choose the compiler. Just choose the default options here (Dont change theoptions). You should be using GNU GCC Compiler. Click Finish to create the new project.
The system will then return to the [MyProgram] window and you are ready to write your program.In theManagement area of the screen (Shift-F2 toggles the Management display), you will see the files that are part ofthe project in the Projects tab. To see the source files, click on the triangle symbol to expand the Workspace andits subdirectories.
Under Sources, there is a file called main.c, which is automatically created for you when you build a consoleapplication. Click on main.c.
Dept of CSE, SIT - CPP 7
0.1. USING CODE::BLOCKS TO COMPILE AND EXECUTE A C PROGRAM
main.c contains a simple Hello World program which you can edit later to solve a programming problem. Nowlet us see how to compile and execute this main.c program. Just to understand the process of debugging weknowingly introduce an error in the program by removing the semicolon after the printf statement. We will nowcompile the program (To compile a file means to take the instructions that you have written and translate it intomachine code for the computer to understand).Compile the project from the Build pull-down menu by clicking on Build option[Ctrl+F9].
The error messages are shown in the Build messages window at the bottom. Let us now try to understandthese error messages. === Build: Debug in MyProgram (compiler: GNU GCC Compiler) ===main.c In function main:main.c 7 error: expected ; before returnmain.c 8 warning: control reaches end of non-void function [-Wreturn-type]=== Build failed: 1 error(s), 1 warning(s) (0 minute(s), 1 second(s)) ===
The error messages show the errors in syntax (and not the logical errors). It also indicates the line number andthe type of error. Here in this example the error says that before the return statement in line no 7 a semicolon ismissing. The next message is a warning message which has resulted because of the previous error.Now go to line number 6 and add a semicolon at the end. Now build your project again.
Dept of CSE, SIT - CPP 8
0.1. USING CODE::BLOCKS TO COMPILE AND EXECUTE A C PROGRAM
Now the build message window shows the following message. 0 error(s), 0 warning(s) (0 minute(s), 0 second(s)This means that the errors and warnings have been successfully resolved. Now it is time to run the program. Youcan Execute the project from the Build pull-down menu by clicking on Run option[Ctrl+F10].
An output window pops displaying the output of the program. A greeting message Hello world! is printed onto the output console.
Dept of CSE, SIT - CPP 9
0.1. USING CODE::BLOCKS TO COMPILE AND EXECUTE A C PROGRAM
Installing Code::Blocks IDE
If you want to install Code::Blocks IDE on your system, you can download it from its official webpage.http://www.codeblocks.org/It is available for Linux, Mac, Windows platforms.
On Debian/Ubuntu systems Code::Blocks can be installed by using the apt package manner. You have to beconnected to the internet for necessary files to be downloaded. Run the following command.$sudo apt install codeblocks
For Windows download the binary whose name is like codeblocks-17.12mingw-setup.exe
Develop a program to solve simple computational problems using arithmetic expressions anduse of each operator leading to simulation of a commercial calculator. (No built-in math func-tion)
2.1 C Code
1 /***************************************************************************2 *File : A02Calculator.c3 *Description : Program to simulate a commercial calculator4 *Author : Prabodh C P5 *Compiler : gcc compiler, Ubuntu 18.046 *Date : 16 August 20187 ***************************************************************************/8
33 case ’-’: printf("\nResult = %d", iOperand1 - iOperand2);34 break;35
36 case ’*’: printf("\nResult = %d", iOperand1 * iOperand2);37 break;
11
2.1. C CODE CHAPTER 2. COMMERCIAL CALCULATOR
38
39 case ’/’: printf("\nResult = %g", (float)iOperand1 / iOperand2);40 break;41 case ’%’: printf("\nResult = %d", iOperand1 % iOperand2);42 break;43
44 }45 printf("\nPress 1 to continue and 0 to quit : ");46 scanf("%d", &iChoice);47 if(0==iChoice)48 {49 break;50 }51 }52 return 0;53 }
Listing 2.1: A02Calculator.c
Output
=================================
1 /***************************************2 Enter the arithmetic expression3 4+64
5 Result = 106 Press 1 to continue and 0 to quit : 17
8 Enter the arithmetic expression9 2-9
10
11 Result = -712 Press 1 to continue and 0 to quit : 113
14 Enter the arithmetic expression15 5*216
17 Result = 1018 Press 1 to continue and 0 to quit : 119
20 Enter the arithmetic expression21 4/522
23 Result = 0.824 Press 1 to continue and 0 to quit : 125
26 Enter the arithmetic expression27 8/428
29 Result = 230 Press 1 to continue and 0 to quit : 131
32 Enter the arithmetic expression33 15%434
35 Result = 336 Press 1 to continue and 0 to quit : 037 ***************************************/
Listing 2.2: out1.c
Dept of CSE, SIT - CPP 12
Chapter 3
Quadratic Equation
Question
Develop a program to compute the roots of a quadratic equation by accepting the coefficients.Print appropriate messages.
3.1 C Code
1 /***************************************************************************2 *File : A03Quadratic.c3 *Description : Program to find the roots of a Quadratic Equation4 *Author : Prabodh C P5 *Compiler : gcc compiler, Ubuntu 18.046 *Date : 16 August 20187 ***************************************************************************/8
9 #include<stdio.h>10 #include<stdlib.h>11 #include<math.h>12 /***************************************************************************13 *Function : main14 *Input parameters : no parameters15 *RETURNS : 0 on success16 ***************************************************************************/17 int main(void)18 {19 float fA,fB,fC,fDesc,fX1,fX2,fRealp,fImagp;20 int iState;21
22 printf("\n*************************************************************");23 printf("\n*\tPROGRAM TO FIND ROOTS OF A QUADRATIC EQUATION\t *\n");24 printf("*************************************************************");25
26 printf("\nEnter the coefficients of a,b,c \n");27 scanf("%f%f%f",&fA,&fB,&fC);28 if(0 == fA)29 {30 printf("\nInvalid input, not a quadratic equation - try again\n");31 exit(0);32 }33
39 case 1:40 fX1 = fX2 = -fB/(2*fA);41 printf("\nRoots are equal and the Roots are \n");42 printf("\nRoot1 = %g and Root2 = %g\n",fX1,fX2);43 break;44 case 2:45 fX1 = (-fB+sqrt(fDesc))/(2*fA);46 fX2 = (-fB-sqrt(fDesc))/(2*fA);47 printf("\nThe Roots are Real and distinct, they are \n");48 printf("\nRoot1 = %g and Root2 = %g\n",fX1,fX2);49 break;50 case 3:51 fRealp = -fB / (2*fA);52 fImagp = sqrt(fabs(fDesc))/(2*fA);53 printf("\nThe Roots are imaginary and they are\n");54 printf("\nRoot1 = %g+i%g\n",fRealp,fImagp);55 printf("\nRoot2 = %g-i%g\n",fRealp,fImagp);56 }57 return 0;58 }
Listing 3.1: A03Quadratic.c
Output
1 /***************************************2 *************************************************************3 * PROGRAM TO FIND ROOTS OF A QUADRATIC EQUATION *4 *************************************************************5 Enter the coefficients of a,b,c6 1 -5 67
8 The Roots are Real and distinct, they are9
10 Root1 = 3 and Root2 = 211 *************************************************************12 * PROGRAM TO FIND ROOTS OF A QUADRATIC EQUATION *13 *************************************************************14 Enter the coefficients of a,b,c15 1 4 416
17 Roots are equal and the Roots are18
19 Root1 = -2 and Root2 = -220 *************************************************************21 * PROGRAM TO FIND ROOTS OF A QUADRATIC EQUATION *22 *************************************************************23 Enter the coefficients of a,b,c24 1 3 325
26 The Roots are imaginary and they are27
28 Root1 = -1.5+i0.866025 Root2 = -1.5-i0.86602529 *************************************************************30 * PROGRAM TO FIND ROOTS OF A QUADRATIC EQUATION *31 *************************************************************32 Enter the coefficients of a,b,c33 0 1 234
35 Invalid input, not a quadratic equation - try again36 ***************************************/
Listing 3.2: out2.c
Dept of CSE, SIT - CPP 14
Chapter 4
Palindrome Check
Question
Develop a program to find the reverse of a positive integer and check for palindrome or not.Display appropriate messages.
C Code
1 /***************************************************************************2 *File : A04Palindrome.c3 *Description : Program to check whether the given integer is a Palindrome or
not4 *Author : Prabodh C P5 *Compiler : gcc compiler, Ubuntu 18.046 *Date : 16 August 20187 ***************************************************************************/8
9 #include<stdio.h>10 #include<stdlib.h>11
12 /***************************************************************************13 *Function : main14 *Input parameters : no parameters15 *RETURNS : 0 on success16 ***************************************************************************/17
18 int main(void)19 {20 int iNum,iRev = 0,iTemp,iRem;21
35 iNum = iNum/10;36 }37 printf("\nReverse is %d",iRev);38
39 if(iRev == iTemp)40 printf("\nNumber %d is a palindrome\n",iTemp);41 else42 printf("\nNumber %d is not a palindrome\n",iTemp);43
44 return 0;45 }
Listing 4.1: A04Palindrome.c
Output
1 /***************************************2 **************************************************************************3 * PROGRAM TO CHECK WHETHER AN INTEGER IS A PALINDROME OR NOT *4 **************************************************************************5 Enter a number6 4567
8 Reverse is 6549 Number 456 is not a palindrome
10
11 **************************************************************************12 * PROGRAM TO CHECK WHETHER AN INTEGER IS A PALINDROME OR NOT *13 **************************************************************************14 Enter a number15 4565416
17 Reverse is 4565418 Number 45654 is a palindrome19
20 **************************************************************************21 * PROGRAM TO CHECK WHETHER AN INTEGER IS A PALINDROME OR NOT *22 **************************************************************************23 Enter a number24 34325
26 Reverse is 34327 Number 343 is a palindrome28
29
30 Infix Expression is (a*(b-c)/(a+b*c))31
32 Postfix Expression is abc-*abc*+/33
34 ***************************************/
Listing 4.2: out3.c
Dept of CSE, SIT - CPP 16
Chapter 5
Electricity Bill
Question
An electricity board charges the following rates for the use of electricity: for the first 200 units80 paise per unit: for the next 100 units 90 paise per unit: beyond 300 units Rs 1 per unit.All users are charged a minimum of Rs. 100 as meter charge. If the total amount is more thanRs 400, then an additional surcharge of 15% of total amount is charged. Write a program toread the name of the user, number of units consumed and print out the charges.
C Code
1 /***************************************************************************2 *File : A05ElectricBill.c3 *Description : Program to perform a binary search on 1D Array4 *Author : Prabodh C P5 *Compiler : gcc compiler, Ubuntu 18.046 *Date : 16 August 20187 ***************************************************************************/8 #include<stdio.h>9 #include<stdlib.h>
53 if(iFound)54 printf("\nKey element %d found at position %d\n",iKey,iMid+1);55 else56 printf("\nKey element not found\n");57
58 return 0;59 }
Listing 6.1: A06BinarySearch.c
Output
=================================
1 /****************************2 Enter the number of elements3 54
5 Enter the elements in ascending order6 1 3 5 7 97
8 Enter the key element9 8
10
11 Key element not found12 ===============================================13 Enter the number of elements14 415
16 Enter the elements in ascending order17 1 4 5 718
19 Enter the key element20 521
22 Key element 5 found at position 323 ===============================================24 Enter the number of elements25 626 Enter the elements in ascending order27 2 4 6 8 9 1028
29 Enter the key element30 931
32 Key element 9 found at position 533 ***************************************/
Listing 6.2: out5.c
Dept of CSE, SIT - CPP 20
Chapter 7
Prime Number Check
Question
Implement using functions to check whether the given number is prime and display appropri-ate messages. (No built-in math function)
7.1 C Code
1 /***************************************************************************2 *File : A07isPrime.c3 *Description : Program to check whether the given integer is a Prime or not4 *Author : Prabodh C P5 *Compiler : gcc compiler, Ubuntu 18.046 *Date : 16 August 20187 ***************************************************************************/8 #include<stdio.h>9 #include<stdlib.h>
10 #include<stdbool.h>11
12 bool fnisPrime(int);13 /***************************************************************************14 *Function : main15 *Input parameters : no parameters16 *RETURNS : 0 on success17 ***************************************************************************/18 int main(void)19 {20 int iVal,iFlag;21 printf("\n******************************************************");22 printf("\n*\tPROGRAM TO IMPLEMENT TEST OF PRIMALITY\t *\n");23 printf("******************************************************");24
25 printf("\nEnter the value to be checked\n");26 scanf("%d",&iVal);27
28 iFlag = fnisPrime(iVal);29 if(iFlag)30 {31 printf("\nThe entered value %d is a prime number\n",iVal);32 }33 else34 {35 printf("\nThe entered value %d is not a prime number\n",iVal);36 }37 return 0;38 }
21
7.1. C CODE CHAPTER 7. PRIME NUMBER CHECK
39 /***************************************************************************40 *Function : fnisPrime41 *Description : Function to check whether a number is prime or not42 *Input parameters :43 * int iX - value to be checked whether prime or not44 *RETURNS :45 true if the number is prime and false otherwise46 ***************************************************************************/47 bool fnisPrime(int iX)48 {49 int i;50 if(1 == iX)51 {52 printf("\n1 is neither prime nor composite\n");53 exit(0);54 }55 for(i = 2; i*i <= iX ;i++)56 {57 if( 0 == iX % i )58 {59 return false;60 }61 }62 return true;63 }
Listing 7.1: A07isPrimefn.c
Output
1 /***************************************2 ******************************************************3 * PROGRAM TO IMPLEMENT TEST OF PRIMALITY *4 ******************************************************5 Enter the value to be checked6 457 The entered value 45 is not a prime number8
9 ******************************************************10 * PROGRAM TO IMPLEMENT TEST OF PRIMALITY *11 ******************************************************12 Enter the value to be checked13 4114 The entered value 41 is a prime number15
16 ******************************************************17 * PROGRAM TO IMPLEMENT TEST OF PRIMALITY *18 ******************************************************19 Enter the value to be checked20 1721 The entered value 17 is a prime number22
23 ******************************************************24 * PROGRAM TO IMPLEMENT TEST OF PRIMALITY *25 ******************************************************26 Enter the value to be checked27 1528 The entered value 15 is not a prime number29
30 ***************************************/
Listing 7.2: out6.c
Dept of CSE, SIT - CPP 22
Part II
PART B
23
Chapter 7
Matrix Multiplication
Question
Develop a program to introduce 2D Array manipulation and implement Matrix multiplicationand ensure the rules of multiplication are checked.
C Code
1 /***************************************************************************2 *File : B08MatrixMul.c3 *Description : Program to implement Matrix Multiplication4 *Author : Prabodh C P5 *Compiler : gcc compiler, Ubuntu 18.046 *Date : 16 August 20187 ***************************************************************************/8
9 #include<stdio.h>10 #include<stdlib.h>11
12 /***************************************************************************13 *Function : main14 *Input parameters : no parameters15 *RETURNS : 0 on success16 ***************************************************************************/17
18 int main(void)19 {20 int iM, iN, iP, iQ, i, j, k, iaMat1[10][10], iaMat2[10][10];21 int iaProd[10][10] = {0};22
23
24 printf("\n*********************************************************");25 printf("\n*\tPROGRAM TO IMPLEMENT MATRIX MULIPLICATION\t*\n");26 printf("*********************************************************");27
28 printf("\nEnter the order of Matrix1\n");29 scanf("%d%d",&iM,&iN);30
31 printf("\nEnter the order of Matrix2\n");32 scanf("%d%d",&iP,&iQ);33
34 if( iN != iP)35 {36 printf("\nMatrix Multiplication not possible\n");37 exit(0);38 }39
24
CHAPTER 7. MATRIX MULTIPLICATION
40
41 printf("\nEnter the elements of Matrix 1\n");42 for(i=0;i<iM;i++)43 for(j=0;j<iN;j++)44 scanf("%d",&iaMat1[i][j]);45
46 printf("\nEnter the elements of Matrix 2\n");47 for(i=0;i<iP;i++)48 for(j=0;j<iQ;j++)49 scanf("%d",&iaMat2[i][j]);50
3 *********************************************************4 * PROGRAM TO IMPLEMENT MATRIX MULIPLICATION *5 *********************************************************6 Enter the order of Matrix17 2 38
9 Enter the order of Matrix210 4 511
12 Matrix Multiplication not possible13
14 *********************************************************15 * PROGRAM TO IMPLEMENT MATRIX MULIPLICATION *16 *********************************************************17 Enter the order of Matrix118 2 319
20 Enter the order of Matrix221 3 222
23 Enter the elements of Matrix 124 1 2 325 4 5 626
27 Enter the elements of Matrix 228 1 229 3 430 5 631
32 Matrix 133 1 2 334 4 5 635
36 Matrix 237 1 238 3 439 5 640
Dept of CSE, SIT - CPP 26
CHAPTER 7. MATRIX MULTIPLICATION
41 The Product matrix is is42 22 2843 49 6444
45 *********************************************************46 * PROGRAM TO IMPLEMENT MATRIX MULIPLICATION *47 *********************************************************48 Enter the order of Matrix149 2 250
51 Enter the order of Matrix252 2 253
54 Enter the elements of Matrix 155 1 256 3 457
58 Enter the elements of Matrix 259 1 060 0 161
62 Matrix 163 1 264 3 465
66 Matrix 267 1 068 0 169
70 The Product matrix is is71 1 272 3 473 ***************************************/
Listing 7.2: out7.c
Dept of CSE, SIT - CPP 27
Chapter 8
Compute Sine of an Angle
Question
Develop a Program to compute Sin(x) using Taylor series approximation. Compare your resultwith the built- in Library function. Print both the results with appropriate messages.
C Code
1 /***************************************************************************2 *File : B09SineAngle.c3 *Description : Program to calculate Sin(x) using Taylor series4 *Author : Prabodh C P5 *Compiler : gcc compiler, Ubuntu 18.046 *Date : 16 August 20187 ***************************************************************************/8 #include<stdio.h>9 #include<stdlib.h>
10 #include <math.h>11 /***************************************************************************12 *Function : main13 *Input parameters : no parameters14 *RETURNS : 0 on success15 ***************************************************************************/16 int main()17 {18 float fAngD, fAngR;19 float fTerm, fNum, fDen, fVal;20 int i,iNum;21 printf("\nEnter the Angle : "); scanf("%f",&fAngD);22 printf("\nEnter the Number of terms : "); scanf("%d",&iNum);23 printf("\nInput Angle = %g\n",fAngD);24 printf("No of terms = %d\n",iNum);25
26 fAngR= (fAngD*M_PI)/180 ;27 fNum=fAngR;28 fDen=1.0;29 fVal =0.0;30 fTerm=fNum/fDen;31 for(i=1;i<=iNum;i++)32 {33 fVal = fVal + fTerm;34 fNum = -fNum * fAngR * fAngR ;35 fDen = fDen * (2*i) * (2*i+1);36 fTerm = fNum/fDen;37 }38 printf("\nCalculated value is :\nSin(%g) = %g\n",fAngD,fVal);39 printf("\nBuilt In function value is :\nSin(%g) = %g\n",fAngD, sin(fAngR));
28
CHAPTER 8. COMPUTE SINE OF AN ANGLE
40 return 0;41 }
Listing 8.1: B09SineAngle.c
Output
=================================
1 /***************************************2 Enter the Angle : 603 Enter the Number of terms : 34
5 Input Angle = 606 No of terms = 37
8 Calculated value is :9 Sin(60) = 0.866295
10
11 Built In function value is :12 Sin(60) = 0.86602513
14 =========================================15 Enter the Angle : 6016 Enter the Number of terms : 917
18 Input Angle = 6019 No of terms = 920
21 Calculated value is :22 Sin(60) = 0.86602523
24 Built In function value is :25 Sin(60) = 0.86602526
27 =========================================28 Enter the Angle : 3029 Enter the Number of terms : 230
31 Input Angle = 3032 No of terms = 233
34 Calculated value is :35 Sin(30) = 0.49967436
37 Built In function value is :38 Sin(30) = 0.539
40 =========================================41 Enter the Angle : 3042 Enter the Number of terms : 843
44 Input Angle = 3045 No of terms = 846
47 Calculated value is :48 Sin(30) = 0.549
50 Built In function value is :51 Sin(30) = 0.552 ***************************************/
Listing 8.2: out8.c
Dept of CSE, SIT - CPP 29
Chapter 9
String Operations
9.1 Question
=================================Write functions to implement string operations such as compare, concatenate, string length.
Convince the parameter passing techniques.
C Code
1 /***************************************************************************2 *File : B10StringFunctions.c3 *Description : Program to implement string operations as functions4 *Author : Prabodh C P5 *Compiler : gcc compiler, Ubuntu 18.046 *Date : 16 August 20187 ***************************************************************************/8
9 #include<stdio.h>10 #include<stdlib.h>11
12 int fnMyStrCmp(const char*, const char*);13 void fnMyStrCat(char*, const char*);14 int fnMyStrLen(const char*);15
16 /***************************************************************************17 *Function : main18 *Input parameters : no parameters19 *RETURNS : 0 on success20 ***************************************************************************/21
22 int main()23 {24 int iChoice;25 char acStr1[30], acStr2[30];26 int iLen;27 printf("\n=====================\n");28 printf("STRING OPERATIONS");29 printf("\n=====================\n");30 for(;;)31 {32 printf("\nEnter two strings\n");33 printf("\nString 1 : "); scanf("%s", acStr1);34 printf("\nString 2 : "); scanf("%s", acStr2);35 printf("\n1.String Compare\n2.String Concatenate\n3.String Length");36 printf("\nEnter your choice : "); scanf("%d", &iChoice);37 switch(iChoice)
30
9.1. QUESTION CHAPTER 9. STRING OPERATIONS
38 {39 case 1: if(fnMyStrCmp(acStr1, acStr2) == 0)40 printf("\nTwo strings are equal");41 else if(fnMyStrCmp(acStr1, acStr2) > 0)42 printf("\nString %s is greater than String %s", acStr1,
acStr2);43 else44 printf("\nString %s is greater than String %s", acStr2,
acStr1);45 break;46
47 case 2: fnMyStrCat(acStr1, acStr2);48 printf("\nConcatenated String is\n%s", acStr1);49 break;50
51 case 3: iLen = fnMyStrLen(acStr1);52 printf("\nLength of String %s is %d\n", acStr1, iLen);53 iLen = fnMyStrLen(acStr2);54 printf("\nLength of String %s is %d\n", acStr2, iLen);55 break;56
57 }58 printf("\nPress 1 to continue and 0 to quit : ");59 scanf("%d", &iChoice);60 if(0==iChoice)61 {62 break;63 }64 }65 return 0;66 }67
68 /***************************************************************************69 *Function : fnMyStrCmp70 *Description : Function that compares the two strings s1 and s2.71 *Input parameters :72 * const char *s1, const char *s2 - two strings to be compared73 *RETURNS :74 * 1 if s1 is greater than s2.75 * 0 if s1 matches s2.76 * -1 if s1 is less than s2.77 ***************************************************************************/78
79 int fnMyStrCmp(const char *s1, const char *s2)80 {81 int k;82 for(k=0; s1[k] == s2[k] && s1[k]!=’\0’&& s2[k]!=’\0’; k++);83
100 *Description : function that appends the src string to the dest string101 *Input parameters :102 * char *dest - first string103 * const char *src - second string104 *RETURNS : nothing105 ***************************************************************************/106
116 /***************************************************************************117 *Function : fnMyStrLen118 *Description : function that calculates the length of a string119 *Input parameters :120 * const char *str - string whose length needs to be found121 *RETURNS :122 * integer which is the length of the string123 ***************************************************************************/124
125 int fnMyStrLen(const char *str)126 {127 int iLen;128 for(iLen=0; str[iLen] != ’\0’; iLen++);129 return iLen;130 }
1 /***************************************2 *************************************************3 * PROGRAM TO IMPLEMENT BUBBLE SORT *4 *************************************************5 Enter no of elements6 57
8 Enter the elements9 2 1 6 5 7
10
11 The Sorted array is12 1 2 5 6 713
14 *************************************************15 * PROGRAM TO IMPLEMENT BUBBLE SORT *16 *************************************************17 Enter no of elements18 619
Develop a program to find the square root of a given number N and execute for all possibleinputs with appropriate messages. Note: Don’t use library function sqrt(n).
C Code
1 /***************************************************************************2 *File : B12SquareRoot.c3 *Description : Program to find the square root of a given number4 *Author : Prabodh C P5 *Compiler : gcc compiler, Ubuntu 18.046 *Date : 16 August 20187 ***************************************************************************/8
9 #include<stdio.h>10 #include<stdlib.h>11 #include <math.h>12 #include <float.h>13 /***************************************************************************14 *Function : main15 *Input parameters : no parameters16 *RETURNS : 0 on success17 ***************************************************************************/18 int main()19 {20 float fVal, fNextGuess, fLastGuess = 1.0f, fDiff ;21 printf("\nEnter a value whose square root has to be calculated\n");22 scanf("%f", &fVal);23 do24 {25 fNextGuess = 0.5 * (fLastGuess + (fVal/fLastGuess));26 fDiff = fabs(fNextGuess - fLastGuess);27 fLastGuess = fNextGuess;28 }while (fDiff > FLT_EPSILON);29 /* }while (fDiff > 0.0001);*/30
31 printf("\nSquare root of %g = %g\n", fVal, fNextGuess);32 //Comparison with built in function33 //printf("\nSquare root of %g = %g\n", fVal, sqrt(fVal));34 return 0;35 }
Listing 11.1: B12SquareRoot.c
36
CHAPTER 11. SQUARE ROOT OF A NUMBER
Output
=================================
1 /***************************************2 Enter a value whose square root has to be calculated3 454
5 Square root of 45 = 6.70826 =====================================================7 Enter a value whose square root has to be calculated8 499
10 Square root of 49 = 711 =====================================================12 Enter a value whose square root has to be calculated13 214
15 Square root of 2 = 1.4142116 =====================================================17 Enter a value whose square root has to be calculated18 5619
20 Square root of 56 = 7.4833121
22 ***************************************/
Listing 11.2: out11.c
Dept of CSE, SIT - CPP 37
Chapter 12
C Structures
Question
Implement structures to read, write and compute average- marks and the students scoringabove and below the average marks for a class of N students.
C Code
1 /***************************************************************************2 *File : B13StudentStructure.c3 *Description : Program to implement structure and compute average marks4 *Author : Prabodh C P5 *Compiler : gcc compiler, Ubuntu 18.046 *Date : 16 August 20187 ***************************************************************************/8
1 /***************************************2 Enter the number of students : 43
4 Enter the Student details5
6 ###############################7 Name : Raju8
9 USN : 1SI17CS03610
11 Marks : 6712
13 ###############################14 Name : Michael15
16 USN : 1SI17CS04517
18 Marks : 8719
20 ###############################21 Name : Sahana22
23 USN : 1SI17CS40524
25 Marks : 7726
27 ###############################28 Name : Jonathan29
30 USN : 1SI17CS02531
32 Marks : 8333
Dept of CSE, SIT - CPP 39
CHAPTER 12. C STRUCTURES
34 The average marks for the class is : 78.535
36 ###############################37 Name : Raju38 USN : 1SI17CS03639 Marks : 6740 The student has scored below average41
42 ###############################43 Name : Michael44 USN : 1SI17CS04545 Marks : 8746 The student has scored above average47
48 ###############################49 Name : Sahana50 USN : 1SI17CS40551 Marks : 7752 The student has scored below average53
54 ###############################55 Name : Jonathan56 USN : 1SI17CS02557 Marks : 8358 The student has scored above average59 ***************************************/
Listing 12.2: out12.c
Dept of CSE, SIT - CPP 40
Chapter 13
Pointers and Arrays
Question
Develop a program using pointers to compute the sum, mean and standard deviation of allelements stored in an array of n real numbers.
C Code
1 /***************************************************************************2 *File : B14MeanVarianceSD.c3 *Description : Program to compute Mean, Variance and Standard Deviation4 using pointer to an array5 *Author : Prabodh C P6 *Compiler : gcc compiler, Ubuntu 18.047 *Date : 16 August 20188 ***************************************************************************/9 #include<stdio.h>
10 #include<stdlib.h>11 #include<math.h>12 /***************************************************************************13 *Function : main14 *Input parameters : no parameters15 *RETURNS : 0 on success16 ***************************************************************************/17 int main(void)18 {19 int i,iNum;20 float fMean = 0.0f, fVariance = 0.0f, fSd = 0.0f,faArray[100],fSum=0.0f;21 float *fptr;22
23 fptr = faArray;24 printf("\nEnter the number of Values : ");25 scanf("%d",&iNum);26 printf("\nEnter %d values\n", iNum);27 for(i=0; i<iNum; i++)28 {29 scanf("%f",fptr+i);30 fSum += *(fptr+i); //fSum += fptr[i]; this is also valid31 }32 fMean = fSum/iNum;33
Implement Recursive functions for Binary to Decimal Conversion.
C Code
1 /***************************************************************************2 *File : B15BinarytoDecimal.c3 *Description : Program to compute Mean, Variance and Standard Deviation4 * using pointer to an array5 *Author : Prabodh C P6 *Compiler : gcc compiler, Ubuntu 18.047 *Date : 16 August 20188 ***************************************************************************/9
10 #include<stdio.h>11 #include<stdlib.h>12
13 unsigned long fnBin2Dec(unsigned long);14
15 /***************************************************************************16 *Function : main17 *Input parameters : no parameters18 *RETURNS : 0 on success19 ***************************************************************************/20 int main(void)21 {22 unsigned long iBinVal, iDecVal;23
24 printf("\nEnter the binary value : ");25 scanf("%lu", &iBinVal);26
27 iDecVal = fnBin2Dec(iBinVal);28
29 printf("\nDecimal equivalent of %lu is %lu\n", iBinVal, iDecVal);30 return 0;31 }32
33 /***************************************************************************34 *Function : fnBin2Dec35 *Description : Function to convert a binary value to its36 * equivalent decimal value37 *Input parameters : unsigned long iVal - binary value to be converted38 *RETURNS : equivalent decimal value39 ***************************************************************************/
1 /**************************************************2 Enter the binary value : 1100011000110013
4 Decimal equivalent of 110001100011001 is 253695 ===================================================6 Enter the binary value : 111111117
8 Decimal equivalent of 11111111 is 2559 ===================================================
10 Enter the binary value : 110111011101110111
12 Decimal equivalent of 1101110111011101 is 5679713 ===================================================14 Enter the binary value : 11100011100011100015
16 Decimal equivalent of 111000111000111000 is 23301617 **************************************************/