You are on page 1of 42

Free Software Movement Karnataka

www.fsmk.org

}
Principles of Programming using C Lab (22POP13/23)
} I\II Semester
(common to all branches)
LAB MANUAL

Prabodh C P
Asst Professor
Dept of CSE, SIT
Volunteer, FSMK

The versioned repository of all the programs can be found here as a GitLab Repository
https://gitlab.com/lab_manuals/pop_manual_vtu_2022_23

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/
Contents

Code::Blocks Usage iii

1 Simple Calculator 1

2 Quadratic Equation 3

3 Electricity Bill 5

4 Printing Pattern 10

5 Binary Search 12

6 Matrix Multiplication 14

7 Compute Sine and Cosine of an Angle 18

8 Bubble Sort 20

9 String Operations 22

10 C Structures 26

11 Pointers and Arrays 29

12 File Copy 31

i
Listings

1.1 A01Calculator.c . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.2 OUTPUT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
2.1 A02Quadratic.c . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
2.2 OUTPUT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
3.1 A03ElectricBill.c . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
3.2 OUTPUT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
3.3 A03ElectricBill 02.c . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
3.4 OUTPUT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
4.1 A04Pattern.c . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
4.2 out4.c . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
5.1 A05BinarySearchIntegers.c . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
5.2 OUTPUT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
6.1 A06MatrixMul.c . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
6.2 OUTPUT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
7.1 A07SineCosAngle.c . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
7.2 OUTPUT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
8.1 A08BubbleSort.c . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
8.2 OUTPUT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
9.1 A09StringFunctions.c . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
9.2 OUTPUT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
10.1 A10StudentStructure.c . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
10.2 OUTPUT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
11.1 A11MeanVarianceSD.c . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
11.2 out11.c . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
12.1 A12FileCopy.c . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
12.2 out12.c . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32

ii
Preface

Usage of Free and Open Source Software


This manual has been developed for the lab component of the newly introduced subject Principles of Programming
using C (22POP13/23) for the first year students of VTU. This manual has been prepared entirely using Free
Software. The following Free Software has been used in preparation of this manual.
Operating System Ubuntu 22.04.1 LTS (Jammy Jellyfish)

Linux Kernel 5.15.0-56-generic


Compiler gcc 11.3.0
IDE Code::Blocks 20.03

Version Control git 2.34.1


Typesetting Texmaker 5.0.3 with LaTeX
Image Editing GIMP 2.10.30
I am sharing this manual 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/.
You are free to share modify this manual with attribution for academic purposes. A repository of all the programs
can be found as GitLab repository in the following link https://gitlab.com/lab_manuals/pop_manual_
vtu_2022_23. Looking for your feedback. If you want to contribute let me know by sending a PR on the git repo
mentioned earlier.

Use and spread the word of Free Software. Free Software leads to a Free Society!

Prabodh C P

iii
CODE::BLOCKS

CODE::BLOCKS TUTORIAL
Using Code::Blocks to compile and execute a C Program
To launch Code::Blocks IDE, Click on
Applications → Programming → Code::Blocks IDE
You will get a window as shown below

iv
LISTINGS LISTINGS

Code::Blocks creates what is called a Workspace to keep track of the project you are working on. It is possible for
you to be working on multiple projects within your workspace. A project is a collection of one or more source (as
well as header) files. Source files are the files that contain the source code for your program. If you are developing a
C program, you are writing C source code (.c files).

First start a new Project by clicking on Create a new project


OR To create a project, click on the File pull-down menu, open New and then Project.You get this pop-up window

Choose Console application


Then 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)

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 Compiler. Click Finish to create the new project.

Dept of CSE, SIT - CPP v


LISTINGS LISTINGS

The system will then return to the [MyProgram] window and you are ready to write your program.In the Man-
agement area of the screen (Shift-F2 toggles the Management display), you will see the files that are part of the
project in the Projects tab. To see the source files, click on the triangle symbol to expand the Workspace and its
subdirectories.

Under Sources, there is a file called main.c, which is automatically created for you when you build a console
application. Click on main.c.

main.c contains a simple Hello World program which you can edit later to solve a programming problem. Now let
us see how to compile and execute this main.c program. Just to understand the process of debugging we knowingly
introduce an error in the program by removing the semicolon after the printf statement. We will now compile the
program (To compile a file means to take the instructions that you have written and translate it into machine code

Dept of CSE, SIT - CPP vi


LISTINGS LISTINGS

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 understand these
error messages. === Build: Debug in MyProgram (compiler: GNU GCC Compiler) ===
main.c In function main:
main.c 7 error: expected ; before return
main.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 and
the type of error. Here in this example the error says that before the return statement in line no 7 a semicolon is
missing. 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 vii


LISTINGS LISTINGS

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. You
can 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 on
to the output console.

Dept of CSE, SIT - CPP viii


LISTINGS LISTINGS

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 be
connected 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

Dept of CSE, SIT - CPP ix


Chapter 1

Simple Calculator

Question
Simulation of a Simple Calculator.

C Code
1 /***************************************************************************
2 *File : A01Calculator.c
3 *Description : Program to simulate a commercial calculator
4 *Author : Prabodh C P
5 *Compiler : gcc compiler, Ubuntu 22.04
6 *Date : 10 August 2022
7 ***************************************************************************/
8

9 #include<stdio.h>
10 #include<stdlib.h>
11 #include<math.h>
12

13 /***************************************************************************
14 *Function : main
15 *Input parameters : no parameters
16 *RETURNS : 0 on success
17 ***************************************************************************/
18

19 int main()
20 {
21 int iChoice, iOperand1, iOperand2;
22 char cOperator;
23

24 for(;;)
25 {
26 printf("\nEnter the arithmetic expression(Do not add spaces in the
expression)\n");
27 scanf("%d%c%d", &iOperand1, &cOperator, &iOperand2);
28 switch(cOperator)
29 {
30 case ’+’: printf("\nResult = %d", iOperand1 + iOperand2);
31 break;
32

33 case ’-’: printf("\nResult = %d", iOperand1 - iOperand2);


34 break;
35

36 case ’*’: printf("\nResult = %d", iOperand1 * iOperand2);


37 break;
38

39 case ’/’: printf("\nResult = %g", (float)iOperand1 / iOperand2);

1
CHAPTER 1. SIMPLE CALCULATOR

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 1.1: A01Calculator.c

Output
=================================
1 /***************************************
2 Enter the arithmetic expression
3 4+6
4

5 Result = 10
6 Press 1 to continue and 0 to quit : 1
7

8 Enter the arithmetic expression


9 2-9
10

11 Result = -7
12 Press 1 to continue and 0 to quit : 1
13

14 Enter the arithmetic expression


15 5*2
16

17 Result = 10
18 Press 1 to continue and 0 to quit : 1
19

20 Enter the arithmetic expression


21 4/5
22

23 Result = 0.8
24 Press 1 to continue and 0 to quit : 1
25

26 Enter the arithmetic expression


27 8/4
28

29 Result = 2
30 Press 1 to continue and 0 to quit : 1
31

32 Enter the arithmetic expression


33 15%4
34

35 Result = 3
36 Press 1 to continue and 0 to quit : 0
37 ***************************************/
Listing 1.2: OUTPUT

Dept of CSE, SIT - CPP 2


Chapter 2

Quadratic Equation

Question
Compute the roots of a quadratic equation by accepting the coefficients. Print appropriate mes-
sages.

C Code
1 /***************************************************************************
2 *File : A02Quadratic.c
3 *Description : Program to find the roots of a Quadratic Equation
4 *Author : Prabodh C P
5 *Compiler : gcc compiler, Ubuntu 22.04
6 *Date : 10 August 2022
7 ***************************************************************************/
8

9 #include<stdio.h>
10 #include<stdlib.h>
11 #include<math.h>
12 /***************************************************************************
13 *Function : main
14 *Input parameters : no parameters
15 *RETURNS : 0 on success
16 ***************************************************************************/
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

34 /*COMPUTE THE DESCRIMINANT*/


35 fDesc = fB * fB - 4 * fA * fC;
36 ((0 == fDesc) ? (iState = 1):((fDesc > 0) ? (iState = 2) : (iState = 3)));
37 switch(iState)
38 {
39 case 1:

3
CHAPTER 2. QUADRATIC EQUATION

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 2.1: A02Quadratic.c

Output
1 /***************************************
2 *************************************************************
3 * PROGRAM TO FIND ROOTS OF A QUADRATIC EQUATION *
4 *************************************************************
5 Enter the coefficients of a,b,c
6 1 -5 6
7

8 The Roots are Real and distinct, they are


9

10 Root1 = 3 and Root2 = 2


11 *************************************************************
12 * PROGRAM TO FIND ROOTS OF A QUADRATIC EQUATION *
13 *************************************************************
14 Enter the coefficients of a,b,c
15 1 4 4
16

17 Roots are equal and the Roots are


18

19 Root1 = -2 and Root2 = -2


20 *************************************************************
21 * PROGRAM TO FIND ROOTS OF A QUADRATIC EQUATION *
22 *************************************************************
23 Enter the coefficients of a,b,c
24 1 3 3
25

26 The Roots are imaginary and they are


27

28 Root1 = -1.5+i0.866025 Root2 = -1.5-i0.866025


29 *************************************************************
30 * PROGRAM TO FIND ROOTS OF A QUADRATIC EQUATION *
31 *************************************************************
32 Enter the coefficients of a,b,c
33 0 1 2
34

35 Invalid input, not a quadratic equation - try again


36 ***************************************/
Listing 2.2: OUTPUT

Dept of CSE, SIT - CPP 4


Chapter 3

Electricity Bill

Question
An electricity board charges the following rates for the use of electricity: for the first 200 units
80 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 than Rs
400, then an additional surcharge of 15% of total amount is charged. Write a program to read
the name of the user, number of units consumed and print out the charges.

C Code
Implementation 1

1 /***************************************************************************
2 *File : A03ElectricBill.c
3 *Description : Program to perform a binary search on 1D Array
4 *Author : Prabodh C P
5 *Compiler : gcc compiler, Ubuntu 22.04
6 *Date : 10 August 2022
7 ***************************************************************************/
8 #include<stdio.h>
9 #include<stdlib.h>
10 /***************************************************************************
11 *Function : main
12 *Input parameters : no parameters
13 *RETURNS : 0 on success
14 ***************************************************************************/
15 int main(void)
16 {
17 char cName[30];
18 int iUnits;
19 const int iMinCharge = 100;
20 const double dSlab1 = 0.8;
21 const double dSlab2 = 0.9;
22 const double dSlab3 = 1.0;
23 const double dSurcharge = 0.15;
24 double dBillAmount = 0.0;
25

26 printf("\nEnter the name of the customer : "); scanf("%s", cName);


27 printf("\nEnter the number of units consumed : "); scanf("%d", &iUnits);
28 dBillAmount += iMinCharge;
29 if(iUnits <= 200)
30 {
31 dBillAmount += iUnits*dSlab1;
32 }
33 else if(iUnits > 200 && iUnits <= 300)
34 {

5
CHAPTER 3. ELECTRICITY BILL

35 dBillAmount += (200*dSlab1)+((iUnits-200)*dSlab2);
36 }
37 else
38 {
39 dBillAmount += (200*dSlab1)+(100*dSlab2)+((iUnits-300)*dSlab3);
40 }
41 if(dBillAmount > 400)
42 {
43 dBillAmount += dBillAmount * dSurcharge;
44 }
45 printf("\nElectricity Bill\n===================================");
46 printf("\nCustomer Name\t: %s", cName);
47 printf("\nUnits Consumed\t: %d", iUnits);
48 printf("\nBill Amount\t: %0.2lf Rupees\n\n", dBillAmount);
49 return 0;
50 }
Listing 3.1: A03ElectricBill.c

Output 1

1 /***************************************
2 Enter the name of the customer : Ramesh
3 Enter the number of units consumed : 457
4

5 Electricity Bill
6 ===================================
7 Customer Name : Ramesh
8 Units Consumed : 457
9 Bill Amount : 583.05 Rupees
10

11 Enter the name of the customer : Sayeed


12 Enter the number of units consumed : 150
13

14 Electricity Bill
15 ===================================
16 Customer Name : Sayeed
17 Units Consumed : 150
18 Bill Amount : 220.00 Rupees
19

20 Enter the name of the customer : Jaswinder


21 Enter the number of units consumed : 300
22

23 Electricity Bill
24 ===================================
25 Customer Name : Jaswinder
26 Units Consumed : 300
27 Bill Amount : 350.00 Rupees
28

29 Enter the name of the customer : Shyam


30 Enter the number of units consumed : 182
31

32 Electricity Bill
33 ===================================
34 Customer Name : Shyam
35 Units Consumed : 182
36 Bill Amount : 245.60 Rupees
37 ***************************************/
Listing 3.2: OUTPUT

Dept of CSE, SIT - CPP 6


CHAPTER 3. ELECTRICITY BILL

Implementation 2
1 /***************************************************************************
2 *File : A03ElectricBill_02.c
3 *Description : Program to perform a binary search on 1D Array
4 *Author : Prabodh C P
5 *Compiler : gcc compiler, Ubuntu 22.04
6 *Date : 10 August 2022
7 ***************************************************************************/
8 #include<stdio.h>
9 #include<stdlib.h>
10 /***************************************************************************
11 *Function : main
12 *Input parameters : no parameters
13 *RETURNS : 0 on success
14 ***************************************************************************/
15 #define SLAB1 0.8
16 #define SLAB2 0.9
17 #define BILL_MIN 100
18 #define SURCHARGE_RATE 0.15
19 int main()
20 {
21 char stName[40];
22 int iNumUnits;
23 float fAmount;
24

25 printf("\nEnter Customer name:");


26 gets(stName);
27 printf("\nEnter number of units consumed: ");
28 scanf("%d", &iNumUnits);
29

30 printf("ELECTRIC BILL\n");
31 printf("%-25s%s\n", "Name : ",stName);
32 printf("%-25s%d units\n", "Units Consumed : ", iNumUnits);
33

34 if(iNumUnits < 200)


35 {
36 fAmount = BILL_MIN + iNumUnits * SLAB1;
37 printf("%-24s= %7.2f Rs\n","Bill Minimum ",100.0);
38 printf("\t%3d * 80 paise = %7.2f\n", iNumUnits,iNumUnits * SLAB1);
39 }
40 else if(iNumUnits < 300)
41 {
42 fAmount = BILL_MIN + (200 * SLAB1) + (iNumUnits-200) * SLAB2;
43 printf("%-24s= %7.2f Rs\n","Bill Minimum ",100.0);
44 printf("\t%3d * 80 paise = %7.2f\n", 200, 200 * SLAB1);
45 printf("\t%3d * 90 paise = %7.2f\n", (iNumUnits-200),(iNumUnits-200) *
SLAB2);
46 }
47 else
48 {
49 fAmount = BILL_MIN + (200 * SLAB1) + (100 * SLAB2) + (iNumUnits-300);
50 printf("%-24s= %7.2f Rs\n","Bill Minimum ",100.0);
51 printf("\t%3d * 80 paise = %7.2f Rs\n", 200, 200 * SLAB1);
52 printf("\t%3d * 90 paise = %7.2f Rs\n", 100, 100 * SLAB2);
53 printf("\t%3d * 100 paise = %7.2f Rs\n", (iNumUnits-300),(float)(iNumUnits
-300));
54 }
55 if(fAmount > 400) //Add surcharge at the rate of 15% if any
56 {
57 fAmount = 1.15 * fAmount;
58 printf("%-23s = %7.2f Rs\n","Surcharge Amount", fAmount *0.15);
59 }

Dept of CSE, SIT - CPP 7


CHAPTER 3. ELECTRICITY BILL

60

61 printf("%-23s = %7.2f Rs\n", "Total Bill Charges ", fAmount);


62 return 0;
63 }
Listing 3.3: A03ElectricBill 02.c

Dept of CSE, SIT - CPP 8


CHAPTER 3. ELECTRICITY BILL

Output 2

1 /***************************************
2 Enter Customer name:SHAM
3

4 Enter number of units consumed: 150


5 ELECTRIC BILL
6 Name : SHAM
7 Units Consumed : 150 units
8 Bill Minimum = 100.00 Rs
9 150 * 80 paise = 120.00
10 Total Bill Charges = 220.00 Rs
11 ===================================
12

13 Enter Customer name:BABU


14

15 Enter number of units consumed: 260


16 ELECTRIC BILL
17 Name : BABU
18 Units Consumed : 260 units
19 Bill Minimum = 100.00 Rs
20 200 * 80 paise = 160.00
21 60 * 90 paise = 54.00
22 Total Bill Charges = 314.00 Rs
23 ===================================
24

25 Enter Customer name:RAMU


26

27 Enter number of units consumed: 555


28 ELECTRIC BILL
29 Name : RAMU
30 Units Consumed : 555 units
31 Bill Minimum = 100.00 Rs
32 200 * 80 paise = 160.00 Rs
33 100 * 90 paise = 90.00 Rs
34 255 * 100 paise = 255.00 Rs
35 Surcharge Amount = 104.36 Rs
36 Total Bill Charges = 695.75 Rs
37 ===================================
38

39 ***************************************/
Listing 3.4: OUTPUT

Dept of CSE, SIT - CPP 9


Chapter 4

Printing Pattern

Question
Write a C Program to display the following by reading the number of rows as input

1
1 2 1
1 2 3 2 1
1 2 3 4 3 2 1

C Code
Implementation
1 /***************************************************************************
2 *File : A04Pattern.c
3 *Description : Program to print a Pattern
4 *Author : Prabodh C P
5 *Compiler : gcc compiler, Ubuntu 22.04
6 *Date : 26 December 2022
7 ***************************************************************************/
8 #include<stdio.h>
9 #include<stdlib.h>
10 /***************************************************************************
11 *Function : main
12 *Input parameters : no parameters
13 *RETURNS : 0 on success
14 ***************************************************************************/
15

16 int main()
17 {
18 int iNum, iSp_cnt, iNum_cnt, iVal, i, j, k;
19 printf("Enter the number of rows : ");
20 scanf("%d", &iNum);
21 iSp_cnt = iNum - 1;
22 iNum_cnt = 1;
23

24 for(i=0;i<iNum;i++)
25 {
26 iVal = 1;
27 for(j=0;j<iSp_cnt;j++)
28 {
29 printf(" ");
30 }
31 for(k=0;k<iNum_cnt;k++)

10
CHAPTER 4. PRINTING PATTERN

32 {
33 if(k <= iNum_cnt/2)
34 {
35 printf("%d ", iVal);
36 iVal++;
37 }
38 else
39 {
40 iVal--;
41 printf("%d ", iVal-1);
42 }
43 }
44 printf("\n");
45 iSp_cnt--;
46 iNum_cnt += 2;
47 }
48 return 0;
49 }
Listing 4.1: A04Pattern.c

Output
=================================
1 /****************************
2

3 Enter the number of rows : 3


4 1
5 1 2 1
6 1 2 3 2 1
7

8 Enter the number of rows : 4


9 1
10 1 2 1
11 1 2 3 2 1
12 1 2 3 4 3 2 1
13

14 Enter the number of rows : 5


15 1
16 1 2 1
17 1 2 3 2 1
18 1 2 3 4 3 2 1
19 1 2 3 4 5 4 3 2 1
20 ***************************************/
Listing 4.2: out4.c

Dept of CSE, SIT - CPP 11


Chapter 5

Binary Search

Question
Implement Binary Search on Integers.

C Code
1 /***************************************************************************
2 *File : A05BinarySearchIntegers.c
3 *Description : Program to perform a binary search on 1D Array of Integers
4 *Author : Prabodh C P
5 *Compiler : gcc compiler, Ubuntu 22.04
6 *Date : 10 August 2022
7 ***************************************************************************/
8

9 #include<stdio.h>
10 #include<stdlib.h>
11

12 /***************************************************************************
13 *Function : main
14 *Input parameters : no parameters
15 *RETURNS : 0 on success
16 ***************************************************************************/
17

18 int main(void)
19 {
20 int iaArr[100],iNum,i,iMid,iLow,iHigh,iFound,iKey;
21

22 printf("\nEnter the number of elements\n");


23 scanf("%d",&iNum);
24

25 printf("\nEnter the elements in ascending order\n");


26 for(i=0;i<iNum;i++)
27 scanf("%d",&iaArr[i]);
28

29 printf("\nEnter the key element\n");


30 scanf("%d",&iKey);
31

32 iFound = 0;
33 iLow = 0;
34 iHigh = iNum-1;
35 while(iLow <= iHigh)
36 {
37 iMid = (iLow+iHigh)/2;
38 if(iKey == iaArr[iMid])
39 {
40 iFound = 1;
41 break;

12
CHAPTER 5. BINARY SEARCH

42 }
43 else if(iKey < iaArr[iMid])
44 {
45 iHigh = iMid-1;
46 }
47 else
48 {
49 iLow = iMid+1;
50 }
51 }
52

53 if(iFound)
54 printf("\nKey element %d found at position %d\n",iKey,iMid+1);
55 else
56 printf("\nKey element not found\n");
57

58 return 0;
59 }
Listing 5.1: A05BinarySearchIntegers.c

Output
=================================
1 /****************************
2 Enter the number of elements
3 5
4

5 Enter the elements in ascending order


6 1 3 5 7 9
7

8 Enter the key element


9 8
10

11 Key element not found


12 ===============================================
13 Enter the number of elements
14 4
15

16 Enter the elements in ascending order


17 1 4 5 7
18

19 Enter the key element


20 5
21

22 Key element 5 found at position 3


23 ===============================================
24 Enter the number of elements
25 6
26 Enter the elements in ascending order
27 2 4 6 8 9 10
28

29 Enter the key element


30 9
31

32 Key element 9 found at position 5


33 ***************************************/
Listing 5.2: OUTPUT

Dept of CSE, SIT - CPP 13


Chapter 6

Matrix Multiplication

Question
Implement Matrix multiplication and validate the rules of multiplication.

C Code
1 /***************************************************************************
2 *File : A06MatrixMul.c
3 *Description : Program to implement Matrix Multiplication
4 *Author : Prabodh C P
5 *Compiler : gcc compiler, Ubuntu 22.04
6 *Date : 10 August 2022
7 ***************************************************************************/
8

9 #include<stdio.h>
10 #include<stdlib.h>
11

12 /***************************************************************************
13 *Function : main
14 *Input parameters : no parameters
15 *RETURNS : 0 on success
16 ***************************************************************************/
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

40

41 printf("\nEnter the elements of Matrix 1\n");

14
CHAPTER 6. MATRIX MULTIPLICATION

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

51

52 for(i=0;i<iM;i++)
53 {
54 for(j=0;j<iQ;j++)
55 {
56 for(k=0;k<iN;k++)
57 {
58 iaProd[i][j] += iaMat1[i][k] * iaMat2[k][j];
59 }
60 }
61 }
62

63 /*
*****************************************************************************************

64 |*| | *|
65 a00 a01 a02|*|b00 b01 b02|*|
66 |*| | *|
67 a10 a11 a12|*|b10 b11 b12|*|
68 |*| | *|
69 a20 a21 a22|*|b20 b21 b22|*|
70 |*| | *|
71

72 (a00*b00+a01*b10+a02*b20) (a00*b01+a01*b11+a02*b21) (a00*b02+a01*b12+a02*b22)


73 (a10*b00+a11*b10+a12*b20) (a10*b01+a11*b11+a12*b21) (a10*b02+a11*b12+a12*b22)
74 (a20*b00+a21*b10+a22*b20) (a20*b01+a21*b11+a22*b21) (a20*b02+a21*b12+a22*b22)
75 ********************************************************************************************
*/
76

77

78 printf("\nMatrix 1\n");
79

80 for(i=0;i<iM;i++)
81 {
82 for(j=0;j<iN;j++)
83 {
84 printf("%d\t",iaMat1[i][j]);
85 }
86 printf("\n");
87 }
88 printf("\n");
89

90 printf("\nMatrix 2\n");
91

92 for(i=0;i<iP;i++)
93 {
94 for(j=0;j<iQ;j++)
95 {
96 printf("%d\t",iaMat2[i][j]);
97 }
98 printf("\n");
99 }
100 printf("\n");

Dept of CSE, SIT - CPP 15


CHAPTER 6. MATRIX MULTIPLICATION

101

102 printf("\nThe Product matrix is is \n");


103

104 for(i=0;i<iM;i++)
105 {
106 for(j=0;j<iQ;j++)
107 {
108 printf("%d\t",iaProd[i][j]);
109 }
110 printf("\n");
111 }
112 printf("\n");
113 return 0;
114 }
Listing 6.1: A06MatrixMul.c

Output
=================================
1 /***************************************
2

3 *********************************************************
4 * PROGRAM TO IMPLEMENT MATRIX MULIPLICATION *
5 *********************************************************
6 Enter the order of Matrix1
7 2 3
8

9 Enter the order of Matrix2


10 4 5
11

12 Matrix Multiplication not possible


13

14 *********************************************************
15 * PROGRAM TO IMPLEMENT MATRIX MULIPLICATION *
16 *********************************************************
17 Enter the order of Matrix1
18 2 3
19

20 Enter the order of Matrix2


21 3 2
22

23 Enter the elements of Matrix 1


24 1 2 3
25 4 5 6
26

27 Enter the elements of Matrix 2


28 1 2
29 3 4
30 5 6
31

32 Matrix 1
33 1 2 3
34 4 5 6
35

36 Matrix 2
37 1 2
38 3 4
39 5 6
40

41 The Product matrix is is


42 22 28
43 49 64

Dept of CSE, SIT - CPP 16


CHAPTER 6. MATRIX MULTIPLICATION

44

45 *********************************************************
46 * PROGRAM TO IMPLEMENT MATRIX MULIPLICATION *
47 *********************************************************
48 Enter the order of Matrix1
49 2 2
50

51 Enter the order of Matrix2


52 2 2
53

54 Enter the elements of Matrix 1


55 1 2
56 3 4
57

58 Enter the elements of Matrix 2


59 1 0
60 0 1
61

62 Matrix 1
63 1 2
64 3 4
65

66 Matrix 2
67 1 0
68 0 1
69

70 The Product matrix is is


71 1 2
72 3 4
73 ***************************************/
Listing 6.2: OUTPUT

Dept of CSE, SIT - CPP 17


Chapter 7

Compute Sine and Cosine of an Angle

Question
Compute sin(x)/cos(x) using Taylor series approximation. Compare your result with the built-in
library function. Print both the results with appropriate inferences.

C Code
1 /***************************************************************************
2 *File : A07SineCosAngle.c
3 *Description : Program to calculate Sin(x)/Cos(x) using Taylor series
4 *Author : Prabodh C P
5 *Compiler : gcc compiler, Ubuntu 22.04
6 *Date : 10 August 2022
7 ***************************************************************************/
8 #include<stdio.h>
9 #include<stdlib.h>
10 #include <math.h>
11 /***************************************************************************
12 *Function : main
13 *Input parameters : no parameters
14 *RETURNS : 0 on success
15 ***************************************************************************/
16 int main()
17 {
18 float fAngD, fAngR;
19 float fTerm, fNum, fDen, fSVal,fCVal;
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

28 //Calculation of Sine of an angle using Taylor’s series


29 fNum=fAngR;
30 fDen=1.0;
31 fSVal =0.0;
32 fTerm=fNum/fDen;
33 for(i=1;i<=iNum;i++)
34 {
35 fSVal = fSVal + fTerm;
36 fNum = -fNum * fAngR * fAngR ;
37 fDen = fDen * (2*i) * (2*i+1);
38 fTerm = fNum/fDen;
39 }
40

18
CHAPTER 7. COMPUTE SINE AND COSINE OF AN ANGLE

41 //Calculation of Cosine of an angle using Taylor’s series


42 fNum=1.0;
43 fDen=1.0;
44 fCVal =0.0;
45 fTerm=1.0;
46 for(i=1;i<=iNum;i++)
47 {
48 fCVal = fCVal + fTerm;
49 fNum = -fNum * fAngR * fAngR ;
50 fDen = fDen * (2*i) * (2*i-1);
51 fTerm = fNum/fDen;
52 }
53

54 printf("\nCalculated value is :\nSin(%g)/Cos(%g) = %g\n",fAngD, fAngD, fSVal/


fCVal);
55 printf("\nBuilt In function value is :\nSin(%g)/Cos(%g) = %g\n", fAngD, fAngD,
sin(fAngR)/cos(fAngR));
56

57 return 0;
58 }
Listing 7.1: A07SineCosAngle.c

Output
=================================
1 /***************************************
2

3 Enter the Angle : 60


4 Enter the Number of terms : 12
5

6 Input Angle = 60 No of terms = 12


7 Calculated value is :
8 Sin(60)/Cos(60) = 1.73205
9

10 Built In function value is :


11 Sin(60)/Cos(60) = 1.73205
12 =========================================
13

14 Enter the Angle : 30


15 Enter the Number of terms : 3
16

17 Input Angle = 30 No of terms = 3


18 Calculated value is :
19 Sin(30)/Cos(30) = 0.577334
20

21 Built In function value is :


22 Sin(30)/Cos(30) = 0.57735
23 =========================================
24

25 Enter the Angle : 45


26 Enter the Number of terms : 11
27

28 Input Angle = 45 No of terms = 11


29 Calculated value is :
30 Sin(45)/Cos(45) = 1
31

32 Built In function value is :


33 Sin(45)/Cos(45) = 1
34 ***************************************/
Listing 7.2: OUTPUT

Dept of CSE, SIT - CPP 19


Chapter 8

Bubble Sort

Question
Sort the given set of N numbers using Bubble sort.

C Code
1 /***************************************************************************
2 *File : A08BubbleSort.c
3 *Description : Program to implement Bubble Sort Algorithm
4 *Author : Prabodh C P
5 *Compiler : gcc compiler, Ubuntu 22.04
6 *Date : 10 August 2022
7 ***************************************************************************/
8

9 #include<stdio.h>
10 #include<stdlib.h>
11

12 /***************************************************************************
13 *Function : main
14 *Input parameters : no parameters
15 *RETURNS : 0 on success
16 ***************************************************************************/
17

18 int main(void)
19 {
20 int iNum, i, j, iaArr[10], iTemp;
21

22

23 printf("\n*************************************************");
24 printf("\n*\tPROGRAM TO IMPLEMENT BUBBLE SORT\t*\n");
25 printf("*************************************************");
26

27 printf("\nEnter no of elements\n");
28 scanf("%d",&iNum);
29

30 printf("\nEnter the elements\n");


31 for(i=0;i<iNum;i++)
32 scanf("%d",&iaArr[i]);
33

34 for(i=0;i<iNum;i++)
35 {
36 for(j=0;j<iNum-i-1;j++)
37 {
38 if(iaArr[j] > iaArr[j+1])
39 {
40 iTemp = iaArr[j];
41 iaArr[j] = iaArr[j+1];

20
CHAPTER 8. BUBBLE SORT

42 iaArr[j+1] = iTemp;
43 }
44

45 /*Code to show the program trace*/


46 /* printf("\nIteration i=%d, j=%d\n",i,j);*/
47 /* for(k=0;k<iNum;k++)*/
48 /* printf("%d\t",iaArr[k]);*/
49 }
50

51 }
52

53 printf("\nThe Sorted array is \n");


54

55 for(i=0;i<iNum;i++)
56 printf("%d\t",iaArr[i]);
57

58 printf("\n");
59 return 0;
60 }
Listing 8.1: A08BubbleSort.c

Output
=================================
1 /***************************************
2 *************************************************
3 * PROGRAM TO IMPLEMENT BUBBLE SORT *
4 *************************************************
5 Enter no of elements
6 5
7

8 Enter the elements


9 2 1 6 5 7
10

11 The Sorted array is


12 1 2 5 6 7
13

14 *************************************************
15 * PROGRAM TO IMPLEMENT BUBBLE SORT *
16 *************************************************
17 Enter no of elements
18 6
19

20 Enter the elements


21 9 7 5 3 1 0
22

23 The Sorted array is


24 0 1 3 5 7 9
25 ***************************************/
Listing 8.2: OUTPUT

Dept of CSE, SIT - CPP 21


Chapter 9

String Operations

Question
Write functions to implement string operations such as compare, concatenate, string length.
Convince the parameter passing techniques.

C Code
1 /***************************************************************************
2 *File : B10StringFunctions.c
3 *Description : Program to implement string operations as functions
4 *Author : Prabodh C P
5 *Compiler : gcc compiler, Ubuntu 22.04
6 *Date : 10 August 2022
7 ***************************************************************************/
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 : main
18 *Input parameters : no parameters
19 *RETURNS : 0 on success
20 ***************************************************************************/
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)
38 {
39 case 1: if(fnMyStrCmp(acStr1, acStr2) == 0)

22
CHAPTER 9. STRING OPERATIONS

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 else
44 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 : fnMyStrCmp
70 *Description : Function that compares the two strings s1 and s2.
71 *Input parameters :
72 * const char *s1, const char *s2 - two strings to be compared
73 *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

84 if( k==(fnMyStrLen(s1)) && k==(fnMyStrLen(s2)) )


85 {
86 return 0;
87 }
88 else if(s1[k] > s2[k])
89 {
90 return 1;
91 }
92 else
93 {
94 return -1;
95 }
96 }
97

98 /***************************************************************************
99 *Function : fnMyStrCat

Dept of CSE, SIT - CPP 23


CHAPTER 9. STRING OPERATIONS

100 *Description : function that appends the src string to the dest string
101 *Input parameters :
102 * char * dest - first string
103 * const char *src - second string
104 *RETURNS : nothing
105 ***************************************************************************/
106

107 void fnMyStrCat(char *dest, const char *src)


108 {
109 int dest_len, i;
110 dest_len = fnMyStrLen(dest);
111 for (i = 0 ; src[i] != ’\0’ ; i++)
112 dest[dest_len + i] = src[i];
113 dest[dest_len + i] = ’\0’;
114 }
115

116 /***************************************************************************
117 *Function : fnMyStrLen
118 *Description : function that calculates the length of a string
119 *Input parameters :
120 * const char *str - string whose length needs to be found
121 *RETURNS :
122 * integer which is the length of the string
123 ***************************************************************************/
124

125 int fnMyStrLen(const char *str)


126 {
127 int iLen;
128 for(iLen=0; str[iLen] != ’\0’; iLen++);
129 return iLen;
130 }
Listing 9.1: A09StringFunctions.c

Output
=================================
1 /***************************************
2 =====================
3 STRING OPERATIONS
4 =====================
5

6 Enter two strings


7

8 String 1 : shiva
9

10 String 2 : shankar
11

12 1.String Compare
13 2.String Concatenate
14 3.String Length
15 Enter your choice : 2
16

17 Concatenated String is
18 shivashankar
19 Press 1 to continue and 0 to quit : 1
20

21 Enter two strings


22

23 String 1 : ramesh
24

25 String 2 : sumesh
26

Dept of CSE, SIT - CPP 24


CHAPTER 9. STRING OPERATIONS

27 1.String Compare
28 2.String Concatenate
29 3.String Length
30 Enter your choice : 1
31

32 String sumesh is greater than String ramesh


33 Press 1 to continue and 0 to quit : 1
34

35 Enter two strings


36

37 String 1 : sam
38

39 String 2 : samantha
40

41 1.String Compare
42 2.String Concatenate
43 3.String Length
44 Enter your choice : 3
45

46 Length of String sam is 3


47

48 Length of String samantha is 8


49

50 Press 1 to continue and 0 to quit : 0


51 ***************************************/
Listing 9.2: OUTPUT

Dept of CSE, SIT - CPP 25


Chapter 10

C Structures

Question
Implement structures to read, write and compute average- marks and the students scoring above
and below the average marks for a class of N students.

C Code
1 /***************************************************************************
2 *File : A09StudentStructure.c
3 *Description : Program to implement structure and compute average marks
4 *Author : Prabodh C P
5 *Compiler : gcc compiler, Ubuntu 22.04
6 *Date : 10 August 2022
7 ***************************************************************************/
8

9 #include<stdio.h>
10 #include<stdlib.h>
11 #define STRSIZE 30
12

13 typedef struct
14 {
15 char cName[STRSIZE];
16 char cUSN[11];
17 int iMarks;
18 }STUDENT_TYPE;
19

20 /***************************************************************************
21 *Function : main
22 *Input parameters : no parameters
23 *RETURNS : 0 on success
24 ***************************************************************************/
25

26 int main(void)
27 {
28 STUDENT_TYPE students[100];
29 int iNum, i;
30 double dAvg = 0.0;
31

32 printf("\nEnter the number of students : ");


33 scanf("%d", &iNum);
34

35 printf("\nEnter the Student details\n");


36 for(i=0;i<iNum;i++)
37 {
38 printf("\n###############################");
39 printf("\nName : "); scanf("%s", students[i].cName);

26
CHAPTER 10. C STRUCTURES

40 printf("\nUSN : "); scanf("%s", students[i].cUSN);


41 printf("\nMarks : "); scanf("%d", &students[i].iMarks);
42 dAvg += students[i].iMarks;
43 }
44

45 dAvg /= iNum;
46

47 printf("\nThe average marks for the class is : %g\n", dAvg);


48

49 for(i=0;i<iNum;i++)
50 {
51 printf("\n###############################");
52 printf("\nName\t: %s", students[i].cName);
53 printf("\nUSN\t: %s", students[i].cUSN);
54 printf("\nMarks\t: %d", students[i].iMarks);
55 if(students[i].iMarks < dAvg)
56 printf("\nThe student has scored below average\n");
57 else
58 printf("\nThe student has scored above average\n");
59 }
60

61 return 0;
62 }
Listing 10.1: A10StudentStructure.c

Output
=================================
1 /***************************************
2 Enter the number of students : 4
3 Enter the Student details
4

5 =========================================
6 Name : Raju
7 USN : 1SI17CS036
8 Marks : 67
9 =========================================
10 Name : Michael
11 USN : 1SI17CS045
12 Marks : 87
13 =========================================
14 Name : Sahana
15 USN : 1SI17CS405
16 Marks : 77
17 =========================================
18 Name : Jonathan
19 USN : 1SI17CS025
20 Marks : 83
21

22 The average marks for the class is : 78.5


23

24 =========================================
25 Name : Raju
26 USN : 1SI17CS036
27 Marks : 67
28 The student has scored below average
29 =========================================
30 Name : Michael
31 USN : 1SI17CS045
32 Marks : 87
33 The student has scored above average
34 =========================================

Dept of CSE, SIT - CPP 27


CHAPTER 10. C STRUCTURES

35 Name : Sahana
36 USN : 1SI17CS405
37 Marks : 77
38 The student has scored below average
39 =========================================
40 Name : Jonathan
41 USN : 1SI17CS025
42 Marks : 83
43 The student has scored above average
44 ***************************************/
Listing 10.2: OUTPUT

Dept of CSE, SIT - CPP 28


Chapter 11

Pointers and Arrays

Question
Develop a program using pointers to compute the sum, mean and standard deviation of all ele-
ments stored in an array of N real numbers.

C Code
1 /***************************************************************************
2 *File : B14MeanVarianceSD.c
3 *Description : Program to compute Mean, Variance and Standard Deviation
4 using pointer to an array
5 *Author : Prabodh C P
6 *Compiler : gcc compiler, Ubuntu 22.04
7 *Date : 10 August 2022
8 ***************************************************************************/
9 #include<stdio.h>
10 #include<stdlib.h>
11 #include<math.h>
12 /***************************************************************************
13 *Function : main
14 *Input parameters : no parameters
15 *RETURNS : 0 on success
16 ***************************************************************************/
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 printf("\nEnter the number of Values : ");


24 scanf("%d",&iNum);
25 fptr = faArray;
26 /* fptr = (float*)malloc(iNum*sizeof(float));*/
27 printf("\nEnter %d values\n", iNum);
28 for(i=0; i<iNum; i++)
29 {
30 scanf("%f",fptr+i);
31 fSum += *(fptr+i); //fSum += fptr[i]; this is also valid
32 }
33 fMean = fSum/iNum;
34

35 for(i=0; i<iNum; i++)


36 {
37 fVariance += (fptr[i] - fMean)*(fptr[i] - fMean);
38 //fVariance += (*(fptr+i) - fMean)*(*(fptr+i) - fMean);
39 }

29
CHAPTER 11. POINTERS AND ARRAYS

40 fVariance /= iNum;
41 fSd = sqrt(fVariance);
42 printf("\nThe values entered are");
43 for(i=0; i<iNum; i++)
44 {
45 printf("\t%g",fptr[i]); //printf("\n\t%f",*(fptr+i));
46 }
47 printf("\n");
48

49 printf("\n**************************************\n");
50 printf("\tSum\t = \t%g\n\tMean\t = \t%g\n\tVariance = \t%g\nStandard Deviation =
\t%g",fSum,fMean,fVariance,fSd);
51 printf("\n**************************************\n");
52 return 0;
53 }
Listing 11.1: A11MeanVarianceSD.c

Output
=================================
1 /***************************************
2 Enter the number of Values : 4
3

4 Enter 4 values
5 1.1 2.2 3.3 4.4
6

7 The values entered are 1.1 2.2 3.3 4.4


8

9 **************************************
10 Sum = 11
11 Mean = 2.75
12 Variance = 1.5125
13 Standard Deviation = 1.22984
14 **************************************
15 ============================================================
16 Enter the number of Values : 5
17

18 Enter 5 values
19 5.345 6.765 7.234 8.675 9.765
20

21 The values entered are 5.345 6.765 7.234 8.675 9.765


22

23 **************************************
24 Sum = 37.784
25 Mean = 7.5568
26 Variance = 2.34995
27 Standard Deviation = 1.53295
28 **************************************
29 ***************************************/
Listing 11.2: out11.c

Dept of CSE, SIT - CPP 30


Chapter 12

File Copy

Question
Write a C program to copy a text file to another, read both the input file name and target file
name.

C Code
1 /***************************************************************************
2 *File : A06MatrixMul.c
3 *Description : Program to implement Matrix Multiplication
4 *Author : Prabodh C P
5 *Compiler : gcc compiler, Ubuntu 22.04
6 *Date : 22 December 2022
7 ***************************************************************************/
8

9 #include<stdio.h>
10 #include<stdlib.h>
11

12 /***************************************************************************
13 *Function : main
14 *Input parameters : no parameters
15 *RETURNS : 0 on success
16 ***************************************************************************/
17 int main(void)
18 {
19 FILE *fp1,*fp2;
20 int ch;
21 char fname1[100], fname2[100];
22 printf("\nEnter File name to be copied\n");
23 scanf("%s",fname1);
24 fp1 = fopen(fname1,"r");
25

26 if(fp1 == NULL)
27 {
28 printf("\nInput File %s doesn’t exist\n", fname1);
29 exit(0);
30 }
31

32 printf("\nEnter target File name\n");


33 scanf("%s",fname2);
34

35 fp2 = fopen(fname2,"w");
36 while((ch=fgetc(fp1)) != EOF)
37 {
38 fputc(ch,fp2);
39 }
40 printf("\nFile %s successfully created\n",fname2);

31
CHAPTER 12. FILE COPY

41

42 fclose(fp1);
43 fclose(fp2);
44

45 return 0;
46 }
Listing 12.1: A12FileCopy.c

Output
=================================
1 /**************************************************
2 Enter File name to be copied
3 out9.c
4

5 Enter target File name


6 out99.c
7

8 File out99.c successfully created


9

10 ===============================================
11

12 Enter File name to be copied


13 secret.txt
14

15 Input File secret.txt doesn’t exist


16

17 **************************************************/
Listing 12.2: out12.c

Dept of CSE, SIT - CPP 32

You might also like