Computer Science for Class XII - Programming using C (Solved Exercises/Programs)

32
Raed Bin Shahid 2013 Computer Science for Class XII - Programming using C Solved Exercises/Programs Raed Bin Shahid Pakistan School and College - Salmiya - Kuwait

description

This e-book has all the solutions for the C exercise programs of Computer Science for Class XII (FBISE).

Transcript of Computer Science for Class XII - Programming using C (Solved Exercises/Programs)

Page 1: Computer Science for Class XII - Programming using C (Solved Exercises/Programs)

R a e d B i n S h a h i d

2013

Computer Science for Class XII -

Programming using C

Solved Exercises/Programs

Raed Bin Shahid

Pakistan School and College - Salmiya - Kuwait

Page 2: Computer Science for Class XII - Programming using C (Solved Exercises/Programs)

R a e d B i n S h a h i d

Page 1

Computer Science for Class XII - Programming using C 2013

Table of Contents Introdcution ............................................................................................................................................ 2

Downloading and setting up the compiler ............................................................................................. 2

Downloading and setting up the text editor ........................................................................................... 6

Chapter 1 – Introduction to C language (How to use the MinGW/GCC compiler with the Notepad++

text editor) .............................................................................................................................................. 7

Chapter 3 – Loops ................................................................................................................................... 8

Chapter 4 – Choices and Decisions ....................................................................................................... 12

Chapter 5 – Arrays and Strings .............................................................................................................. 17

Chapter 6 – Functions ........................................................................................................................... 24

Chapter 7 – File Management .............................................................................................................. 29

Page 3: Computer Science for Class XII - Programming using C (Solved Exercises/Programs)

R a e d B i n S h a h i d

Page 2

Computer Science for Class XII - Programming using C 2013

Introdcution I am an ex-student of Pakistan School and College - Salmiya – Kuwait. As I was helping some current

students of the school with the C programming exercises, I thought if the work can be compiled into

an e-book then everyone else would be able to benefit from it too.

Downloading and setting up the compiler and text editor will be explained in here including how to

use it and then the solution for the exercises will be given. I thought explaining how to setup the

compiler was necessary because schools here are still using the Borland Turbo C++ compiler/IDE

(Integrated Development Environment) which is a bit out of date and does not work properly with

the new Windows OS’s. For this reason I am going to explain how to setup a popular compiler called

MinGW (Minimalist GNU for Windows) which is a Windows port of GNU GCC (GNU Compiler

Collection) with a very good and useful text editor for programming called Notepad++.

I have strictly used the style and method of the programs written in here similar to those in the

textbook as this will be easier for the students to understand the programs if they have gone

through the textbook thoroughly. And pardon me if you find any mistakes in here. I have tried my

best to keep this e-book error free.

Downloading and setting up the compiler First of all we will have to download the MinGW compiler, and it can be downloaded from here:

http://sourceforge.net/projects/mingw/files/

The page will come up with contents which are something like in the image above. Click the link on

link at the top (Download mingw-get-inst-20120426.exe (662.7 kB) or something similar as the

versions change) to download the compiler.

Install the compiler after it has been downloaded. I don’t think I need to explain how to install the

compiler as I hope you people should already know that, but I would give some suggestions about it.

When it asks you about Repository Catalogues select “Use pre-packaged repository catalogues”, if

you have a slow internet connection and don’t want to download the latest repository catalogues.

Else select “Download repository catalogues” to download up to date files.

Page 4: Computer Science for Class XII - Programming using C (Solved Exercises/Programs)

R a e d B i n S h a h i d

Page 3

Computer Science for Class XII - Programming using C 2013

When it asks to Select Destination Location leave it as default which will be the root of a directory,

“C:\MinGW” in my case. After that when it asks to Select Components, select “C Compiler” only as

that’s the only compiler we need.

After the installation is finished we need to add MinGW’s executable files to the system path else we

will have a hard time trying to compile the programs. I will break it down into steps and then give

Page 5: Computer Science for Class XII - Programming using C (Solved Exercises/Programs)

R a e d B i n S h a h i d

Page 4

Computer Science for Class XII - Programming using C 2013

screenshots of the process too. These instructions are for Windows 7 and 8 but they should probably

be the same for the earlier versions of Windows.

1. Right click the My Computer icon or go to My Computer and then right click on an empty

space and click on Properties.

2. Go to Advanced system settings which should be on the top left.

3. Click on the Environment Variables button in the Advanced tab.

4. In the System variables find the Variable called Path and then double click on it. Or just click

on it once and then click on the Edit button.

5. Add a semicolon (;) at the end of the Variable value in the text field if it’s already not there.

Then add the path to the bin folder which is present is the MinGW installation folder,

“C:\MinGW\bin” in my case.

Page 6: Computer Science for Class XII - Programming using C (Solved Exercises/Programs)

R a e d B i n S h a h i d

Page 5

Computer Science for Class XII - Programming using C 2013

Page 7: Computer Science for Class XII - Programming using C (Solved Exercises/Programs)

R a e d B i n S h a h i d

Page 6

Computer Science for Class XII - Programming using C 2013

The Path system variable specifies a bunch of directories in Windows. Where if you include one and

you are in the Command Prompt and you type a name of a program, it will search these directories

for that name of the program. The semicolon separate’s multiple directory paths. Now we will be

using the gcc.exe executable to compile our C programs which is present in the bin folder of the

MinGW installation folder through the Command Prompt to compile the programs. For this reason

we have to add the path location of the bin folder to the system variable path to easily use the

gcc.exe all the time by just typing gcc instead of the whole path of file location again and again.

Now we will check if the gcc.exe can be run from the Command Prompt. Go to Run (Windows

Logo+R is the shortcut to Run) and then type ‘cmd’ in the text field and click ok. The Command

Prompt will open, now type ‘gcc’ over there and press enter. If you get something like this, then you

followed the steps correctly and the C compiler is ready to compile C programs.

Else if you get “'gcc' is not recognized as an internal or external command, operable program or

batch file.” Then you made a mistake while setting up the path and should follow the instruction

above and try it again.

Downloading and setting up the text editor You can use the default text editor of Windows (Notepad) to type in the programs. But I recommend

you use Notepad++ because it helps a lot while programming. Such as keeping track of open and

close braces and every element is distinct as they have different colors. I will not go much in depth

about downloading and installing Notepad++ as the procedure is similar to the one that has been

explained above. Notepad++ can be downloaded from the following link.

http://sourceforge.net/projects/notepad-plus/files/

Install it the same way as showed before. No important changes have to be made during the

installation. In the next chapter how to use the compiler and text editor will be shown.

Page 8: Computer Science for Class XII - Programming using C (Solved Exercises/Programs)

R a e d B i n S h a h i d

Page 7

Computer Science for Class XII - Programming using C 2013

Chapter 1 – Introduction to C language (How to use the MinGW/GCC

compiler with the Notepad++ text editor) There is only one program in the first chapter. The answer of it is same as the program in the in the

textbook under ‘1.3 Basic structure of a program’ on page 7 which prints ‘I Love Pakistan’. I am just

going to use this simple program to demonstrate how to use the MinGW compiler and the

Notepad++ text editor.

Q 6. Write a program that will print the message

I Love Computers

And compile and run it on the computer.

Answer: #include <stdio.h> void main(void) { printf("I Love Computers"); }

Open the Notepad++ and save new file with any name as C source file.

Now type the C program in the file and then save it.

Now go to the Command Prompt and to the directory where the C source file is saved and then

compile the C source file with the gcc.exe application located in the bin folder of the MinGW

installation folder which we added in the system path before. The C source file can be compiled with

the following syntax.

gcc ilc.c –o ilc.exe

gcc is the MinGW C compiler which we are calling to compile the C source file.

ilc.c is the C source file which is to be compiled.

–o is the output file flag switch which tells the compiler that the next argument will be the name of the output file.

Ilc.exe is the name of the output executable file created from the C source code by the C

compiler.

Sometimes it will give a warning while compiling some programs in the text book and not compile

the program. You can use the –w swtich while compiling to bypass the warning.

Page 9: Computer Science for Class XII - Programming using C (Solved Exercises/Programs)

R a e d B i n S h a h i d

Page 8

Computer Science for Class XII - Programming using C 2013

Now compile the C source file with the syntax given above in the Command Prompt and then

execute the output file. If the source file has any errors the program will not compile and the

debugger will tell what is the error and in which line is it, So that you can debug it. Else the program

will compile successfully and you can then execute the output file to run the program.

Output:

Chapter 3 – Loops Q 6. What will be printed by the following program?

#include <stdio.h>

void main(void)

{

int count, total=0;

for(count=0;count<8;count++)

{

total=total+count;

printf("\nCount=%d, Total=%d",count,total);

}

}

Answer: The answer of this question can simply be found by compiling and executing the code itself.

But during the examination you won’t have that privilege. So it’s better to try and work out the

output just by reading the code.

Output:

Q 7. Write the above program using while loop.

Answer: In this program the code of the previous program which uses a for loop has to be done using a while loop instead. We have to translate all the expressions of the for loop into a while loop. The count variable will be set to 0 in its initialization. The condition is given in the while’s loop expression. The increment to the count variable is made at the end of the while loop.

Page 10: Computer Science for Class XII - Programming using C (Solved Exercises/Programs)

R a e d B i n S h a h i d

Page 9

Computer Science for Class XII - Programming using C 2013

#include <stdio.h> void main(void) { int count=0, total=0; while(count<8) { total=total+count; printf("\nCount= %d, Total= %d", count, total); count++; } }

Output:

Q 8. Write the program of question 6 using do while loop.

Answer: This is similar to the previous question but now instead of re-doing the question 6 using a

while loop, this time we have to do is using a do while loop. Just converting the while loop in the

previous answer to a do while loop will do the trick.

#include <stdio.h> void main(void) { int count=0, total=0; do { total=total+count; printf("\nCount=%d, Total=%d",count,total); count++; } while(count<8); }

Output:

Page 11: Computer Science for Class XII - Programming using C (Solved Exercises/Programs)

R a e d B i n S h a h i d

Page 10

Computer Science for Class XII - Programming using C 2013

Q 9. Write a program to find the sum of positive odd numbers and the product of positive even

numbers less than or equal to 30.

Answer: This one can be done in different ways but I’m going to do it purely with loops as we are

dealing with loops in this chapter. There is a problem in this question though. The product that is

going to be calculated here is an enormous number around 30 digits long which cannot be stored

and represented accurately without some external help in C. The data types cannot hold the full

precision but at least they can represent some number without overflowing. Data type’s long long

int and double can be used to represent the result of this program. The long long int data type is not

described in the textbook so I am going to use the double data type for this program.

#include <stdio.h> void main(void) { int j, sum=0; double product=1; for(j=1;j<=30;j=j+2) { sum=sum+j; } for(j=2;j<=30;j=j+2) { product=product*j; } printf("The sum of positive odd numbers is: %d\n", sum); printf("The product of positive even numbers is: %6.2f", product); }

Output:

Q 10. Write two programs that read an integer and print its table in descending order using for

loop and while loop.

Answer: For this question the answer is required using for loop and while loop so two separate

programs will be written for this question. As the table needs to be printed in descending order, I

will print it starting from 12 down to 1.

//Using for loop. #include <stdio.h> void main(void) { int n, j, p; printf("Enter a number to get its table: "); scanf("%d",&n); for(j=12;j>0;j--) {

Page 12: Computer Science for Class XII - Programming using C (Solved Exercises/Programs)

R a e d B i n S h a h i d

Page 11

Computer Science for Class XII - Programming using C 2013

p=j*n; printf("\n %2d x %2d = %3d", j, n, p); } }

//Using while loop. #include <stdio.h> void main(void) { int n, j=12, p; printf("Enter a number to get its table: "); scanf("%d",&n); while(j>0) { p=j*n; printf("\n %2d x %2d = %3d", j, n, p); j--; } }

Output:

Q 11. Write a program that prints the square of all the numbers from 1 to 10.

Number Square

---------- ---------

1 1

2 4

3 9

. .

. .

. .

10 100

Answer: We have to print the output just as it’s formatted in the question above.

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

Page 13: Computer Science for Class XII - Programming using C (Solved Exercises/Programs)

R a e d B i n S h a h i d

Page 12

Computer Science for Class XII - Programming using C 2013

int j, sqr; printf("\tNumber\t\tSquare\n"); printf("\t------\t\t------\n"); for(j=1;j<=10;j++) { sqr=j*j; printf("\t%2d\t\t%3d\n",j,sqr); } }

Output:

Chapter 4 – Choices and Decisions Q 2. Write a program that reads temperature and prints a message as given below.

Temperature Message

t>35 It is hot!

t≥20, t≤35 Nice day!

t<20 It is cold!

Answer: The algorithm is already given in the question that is the temperatures, which will be used

as the condition expression for the if conditions. It is quite similar to the grading program on page

60.

#include <stdio.h> void main(void) { int temp; printf("Enter the temprature: "); scanf("%d",&temp); if(temp>35) printf("It is hot!"); else if(temp>=20 && temp<=35) printf("Nice Day!"); else if(temp<20) printf("It is cold!"); }

Page 14: Computer Science for Class XII - Programming using C (Solved Exercises/Programs)

R a e d B i n S h a h i d

Page 13

Computer Science for Class XII - Programming using C 2013

Output:

Q 3. Write a program that reads a phrase and prints the number of upper-case and lower-case

letters in it.

Answer: This program can be done by the combining two programs given in this chapter. The first

one is on page 57 at the bottom, which counts the number of characters and words in a phrase. The

second one is on page 64 which determines whether the entered character is a vowel or consonant.

#include <stdio.h> #include <conio.h> void main(void) { int uppercount=0, lowercount=0; char ch; printf("Enter a phrase: "); while((ch=getche())!='\r') { if(ch>='A' && ch<='Z') uppercount=uppercount+1; if(ch>='a' && ch<='z') lowercount=lowercount+1; } printf("\nUppercount= %d",uppercount); printf("\nLowercount= %d",lowercount); }

Output:

Page 15: Computer Science for Class XII - Programming using C (Solved Exercises/Programs)

R a e d B i n S h a h i d

Page 14

Computer Science for Class XII - Programming using C 2013

Q 4. Write a program that reads three numbers and prints the largest.

Answer: This program can be done in a number of ways with different algorithms. I’m going to do it

in a simple way and just print the largest of the three numbers. If you want to print which variable

has the largest value or which variables have equal values or if all variables are equal, then that can

be done with different ways but I want to keep the program short and simple and do just what the

question says using if-else and else-if constructs.

#include <stdio.h> void main(void) { int x, y, z; printf("Enter 3 numbers: "); scanf("%d %d %d", &x, &y, &z); if(x>y && x>z) printf("%d is the largest.",x); else if(y>z) printf("%d is the largest.",y); else printf("%d is the largest.",z); }

Output:

Q 5. A class of 35 students took an examination in which marks range from 0 to 100. Write a

program which finds

a) The average marks

b) The number of students failed (marks below 50)

c) The number of students who scored 100 marks

Answer: This program can be done using arrays because we haven’t studied arrays yet at this point

in the textbook. Thus I will do this program using loops and if conditions only.

#include <stdio.h> void main(void) { int i, fail=0, full=0; float n, marks=0, avg; printf("Enter the marks of students(35) between 0 and 100: "); for(i=1;i<=35;i++) { scanf("%f",&n); marks=marks+n; if(n<50) fail=fail+1; if(n==100)

Page 16: Computer Science for Class XII - Programming using C (Solved Exercises/Programs)

R a e d B i n S h a h i d

Page 15

Computer Science for Class XII - Programming using C 2013

full=full+1; } avg=marks/35; printf("\nThe average marks are: %6.2f", avg); printf("\nThe number of students failed: %d", fail); printf("\nThe number of students who scored 100 marks: %d", full); }

Output: The marks I entered were 0, 7, 11, 21, 35, 42, 49, 52, 53, 55, 57, 58, 63, 64, 66, 68, 69, 71,

72, 73, 76, 77, 81, 85, 86, 88, 89, 91, 95, 96, 97, 99, 100, 100, 100.

Q 6. Write a program that prints all odd positive integers less than 100 skipping those that are

exactly divisible by 7.

1 3 5 9 11 13 15 17 19 23 25 … 99

Answer: First make a loop, preferably for loop which only prints positive odd integers less than 100.

The loop will be similar to the one used in Chapter 3 – Loops Q 9. Then in the loop eliminate all the

numbers which are divisible by 7 by using an if condition.

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

int i; for(i=1;i<100;i=i+2) { if (i%7!=0) printf("%d ",i); }

}

Output:

Q 7. Write a program that reads two integers and prints their Greatest Common Divisor (GCD).

Answer: I have not written the code for this and the next program myself but found it on the inter-

webs (as my math sucks lol). I will add the URL of the original source here so that you can read the

explanation and different ways of doing the program. http://www.cquestions.com/2008/01/write-c-

program-to-find-gcd-of-two.html

#include<stdio.h> void main(void)

Page 17: Computer Science for Class XII - Programming using C (Solved Exercises/Programs)

R a e d B i n S h a h i d

Page 16

Computer Science for Class XII - Programming using C 2013

{ int x,y,m,i; printf("Insert two integers: "); scanf("%d %d",&x,&y); if(x>y) m=y; else m=x; for(i=m;i>=1;i--) if(x%i==0&&y%i==0) { printf("GCD of the two integers: %d",i); break; } }

Output:

Q 8. Write a program that reads the coefficients, a, b and c of the quadratic equation

and prints the real solutions of x, using the following formula

Note that if

then there is only one real solution. If it is greater than zero then there are two real solutions and

if it is less than zero then print the message “NO REAL SOLUTION”.

Answer: The program can be found here http://www.cquestions.com/2011/09/c-program-for-

solving-quadratic.html. I have made some changes in it to fit the question as we only need to print

the real solutions and not the complex ones.

#include<stdio.h> #include<math.h> void main(void) { float a,b,c,d,root1,root2; printf("Enter a, b and c of quadratic equation: "); scanf("%f%f%f",&a,&b,&c); d=b*b-4*a*c; if(d<0) { printf("NO REAL SOLUTION"); } else if(d==0)

Page 18: Computer Science for Class XII - Programming using C (Solved Exercises/Programs)

R a e d B i n S h a h i d

Page 17

Computer Science for Class XII - Programming using C 2013

{ printf("Only one real solution."); root1=-b/(2*a); printf("\nRoot of quadratic equation is: %6.2f ",root1); } else { printf("Roots are real numbers.\n"); root1=(-b+sqrt(d))/(2*a); root2=(-b-sqrt(d))/(2*a); printf("Roots of quadratic equation are: %6.2f, %6.2f",root1,root2); } }

Output:

Chapter 5 – Arrays and Strings Q 5. Write a program that reads n integers and prints the smallest along with its subscript value in

the list.

Answer: There is a program to find the largest integer on page 71. This one is quite similar to it but

with a few additions. Instead of 15 inputs we will have n inputs where n in any number inputted by

the user. Plus we have to print the subscript value of the smallest number.

#include <stdio.h> void main(void) { int n, num[50], i, small, subscript=0; printf("How many numbers do you want to compare?(max 50): "); scanf("%d",&n); for(i=0;i<n;i++) { printf("Enter a number [%d]: ", i);

Page 19: Computer Science for Class XII - Programming using C (Solved Exercises/Programs)

R a e d B i n S h a h i d

Page 18

Computer Science for Class XII - Programming using C 2013

scanf("%d",&num[i]); } small=num[0]; for(i=1;i<n;i++) if(small>num[i]) { small=num[i]; subscript=i; } printf("The smallest number is %d with subscript value %d.",small,subscript); }

Output:

Q 6. Write a program that reads two integer arrays, a and b, having 5 elements each and prints the

sum of the products as given below.

sum=a[0]*b[0] + a[1]*b[1] + … + a[4]*b[4]

Answer: This is a simple one. We just have to translate the formula given above into code.

#include<stdio.h> void main(void) { int a[4], b[4], i, sum=0; for(i=0;i<5;i++) { printf("Enter [%d]element of the first array: ", i); scanf("%d",&a[i]); } for(i=0;i<5;i++) { printf("Enter [%d]element of the second array: ", i); scanf("%d",&b[i]); } for(i=0;i<5;i++) sum=sum+(a[i]*b[i]); printf("The result is: %d",sum); }

Output:

Page 20: Computer Science for Class XII - Programming using C (Solved Exercises/Programs)

R a e d B i n S h a h i d

Page 19

Computer Science for Class XII - Programming using C 2013

Q 7. Write a program that reads n floating point numbers and prints the sum of positive numbers.

Answer: Another easy one. Just have to fill an array with n floating point numbers and then calculate

the sum of all positive numbers with an if condition elimination all the negative numbers.

#include<stdio.h> void main(void) { int n=1, i; float num[50], sum=0; printf("How many numbers do you want to compare?(max 50): "); scanf("%d",&n); for(i=0;i<n;i++) { printf("Enter a number [%d]: ", i); scanf("%f",&num[i]); } for(i=0;i<n;i++) if(num[i]>0) sum=sum+num[i]; printf("The result is: %6.2f",sum); }

Output:

Q 8. For a floating-point array x whose size Is n, find the geometric mean.

GM = √

Answer: I tried doing this math formula myself and thankfully it worked. First we will find the

product of n floating-point numbers inside the square root and then we will calculate the square

root itself.

Page 21: Computer Science for Class XII - Programming using C (Solved Exercises/Programs)

R a e d B i n S h a h i d

Page 20

Computer Science for Class XII - Programming using C 2013

#include<stdio.h> #include<math.h> void main(void) { int i; float n=1, x[50], geoProt=1.0, geoMean; printf("Enter the size of the array (max 50): "); scanf("%f",&n); for(i=0;i<n;i++) { printf("Enter a number [%d]: ",i); scanf("%f",&x[i]); geoProt=geoProt*x[i]; } geoMean=pow(geoProt,1/n); printf("The Geometric Mean is: %6.2f",geoMean); }

Output:

Q 9. Write codes that will print the following patterns.

Answer: Now the following programs are a bit tricky. They are actually a good exercise on how loops

work or rather how nested loops work. The question c is the trickiest and the other three are easy. B

is just the reverse of a, and d is exactly the same as a but instead of printing the numbers you will be

printing asterisks. If you follow the programs and compare them, then you will be able to get the

logic behind them.

a) 1

1 2

1 2 3

1 2 3 4

1 2 3 4 5

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

int i,j; for(i=1;i<=5;++i) { for(j=1;j<=i;++j) { printf("%d ",j); }

Page 22: Computer Science for Class XII - Programming using C (Solved Exercises/Programs)

R a e d B i n S h a h i d

Page 21

Computer Science for Class XII - Programming using C 2013

printf("\n"); } }

Output:

b) 1 2 3 4 5

1 2 3 4

1 2 3

1 2

1

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

int i,j; for(i=5;i>=1;i--) { for(j=1;j<=i;++j) { printf("%d ",j); } printf("\n"); } }

Output:

c) 1 2 3 4 5

2 3 4 5

3 4 5

4 5

5

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

Page 23: Computer Science for Class XII - Programming using C (Solved Exercises/Programs)

R a e d B i n S h a h i d

Page 22

Computer Science for Class XII - Programming using C 2013

int i,j; for(i=1;i<=5;i++) { for(j=i;j<=5;j++) { printf("%d ",j); } printf("\n"); } }

Output:

d) *

* *

* * *

* * * *

* * * * *

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

int i,j; for(i=1;i<=5;++i) { for(j=1;j<=i;++j) { printf("* "); } printf("\n"); } }

Output:

Page 24: Computer Science for Class XII - Programming using C (Solved Exercises/Programs)

R a e d B i n S h a h i d

Page 23

Computer Science for Class XII - Programming using C 2013

Q 10. For a two dimensional array x that has r rows and c columns, print the sum and average of

each row.

Answer: This one was a bit is a bit tough. It is another good exercise to better understand the loops

and functionality of two dimensional arrays. Instead to having a static value for the row and arrays, I

have made the program such that the value of rows and columns is input by the user thus making

the program a bit more flexible.

#include<stdio.h> void main() { int x[10][10],r,c,sum=0,i,j; float avg=1; printf("Enter the size of the array(rows and columns): "); scanf("%d%d",&r,&c); printf("Fill the Two dimensional array \n"); for(i=0;i<r;i++) for(j=0;j<c;j++) { printf("Enter the value of row %d and column %d: ",i,j); scanf("%d",&x[i][j]); } for(i=0;i<r;i++) { for(j=0;j<c;j++) sum=sum+x[i][j]; avg=(float)sum/(float)c; printf("The sum of row %d is: %d\n",i,sum); printf("The average is: %6.2f\n",avg); sum=0; } }

Output: I entered a 3 x 3 matrix with the values

7 13 6

9 21 42

2 3 666

Page 25: Computer Science for Class XII - Programming using C (Solved Exercises/Programs)

R a e d B i n S h a h i d

Page 24

Computer Science for Class XII - Programming using C 2013

Chapter 6 – Functions Q 2. Write a program that prints the larger of two numbers entered from the keyboard. Use a

function to do the actual comparison of the two numbers. Pass the two numbers to the function

as arguments and have the function return the answer with return ().

Answer: The programs in this chapter are simple as we have done similar programs before. In these

programs we have to do the actual computation of the program in the functions. This program is a

simple comparison program of two number where the comparison will be done by the function.

#include<stdio.h> int compare(int x,int y); void main(void) { int a,b,c; printf("Enter two numbers: "); scanf("%d%d",&a,&b); c=compare(a,b); printf("%d is the larger no.",c); } int compare(int x,int y) { if(x>y) return x; else return y; } Output:

Q 3. Write a program using a function to calculate the area of a rectangle.

Answer: Another easy one where we just have to take the input of length and width of a rectangle

by the user and then calculate the area of the rectangle using a function. The formula is area =

length x width.

#include<stdio.h> int area(int a,int b); void main(void) { int length,width,areaz; printf("Enter length and width of the rectangle: "); scanf("%d%d",&length,&width); areaz=area(length,width); printf("The area of the rectangle is %d.",areaz); } int area(int a,int b) {

Page 26: Computer Science for Class XII - Programming using C (Solved Exercises/Programs)

R a e d B i n S h a h i d

Page 25

Computer Science for Class XII - Programming using C 2013

int c; c=a*b; return c; }

Output:

Q 4. Write a program that produces the following table of temperature in Centigrade and

Fahrenheit from 0 degrees to 50 degrees centigrade. Use a function for conversion.

-------------------------------------------------------------------

Centigrade Fahrenheit

-------------------------------------------------------------------

0 32

5

10

.

.

.

50

Answer: An almost similar conversion of temperature program has already been done on the page

41 of the textbook. Refer there to understand better how to do this program.

#include<stdio.h> void convert(void); void main(void) { printf("\t--------------------------------\n"); printf("\t Centigrade"); printf("\t Fahrenheit\n"); printf("\t--------------------------------\n"); convert(); } void convert(void) { int c,f; for(c=0;c<=50;c=c+5) { f=(9*c/5)+32; printf("\t\t%d\t\t%d\n",c,f); } }

Page 27: Computer Science for Class XII - Programming using C (Solved Exercises/Programs)

R a e d B i n S h a h i d

Page 26

Computer Science for Class XII - Programming using C 2013

Output:

Q 5. Write a program that reads a phrase and prints the number of lower-case letters in it using a

function for counting.

Answer: The answer of this question is almost similar to the program in Chapter 4 – Choices and

Decisions Q 3. We just have to do it using a function.

#include<stdio.h> int count(void); void main() { int lowercase; printf("Enter a phrase: "); lowercase=count(); printf("\nThe no of lowercase letters: %d",lowercase); } int count(void) { int lowercount=0; char ch; while((ch=getche())!='\r') if(ch>='a'&&ch<='z') lowercount++; return(lowercount); }

Output:

Q 6. Write a program that reads n floating-point number in an array and prints their product using

a function.

Page 28: Computer Science for Class XII - Programming using C (Solved Exercises/Programs)

R a e d B i n S h a h i d

Page 27

Computer Science for Class XII - Programming using C 2013

Answer: The question seems simple but the program is a bit bigger that the normal programs in the

exercises. Fill an array with n number of floating-point values. Pass the array and the variable n to

the function and then calculate the product of the values in the array and then print it.

#include<stdio.h> void product(float x[],int n); void main(void) { float x[50]; int i, n; printf("How many elements do you want to enter? "); scanf("%d",&n); for(i=0;i<n;i++) { printf("Enter the %d element in the array: ",i); scanf("%f",&x[i]); } product(x,n); } void product(float x[],int n) { float productz=1; int i; for(i=0;i<n;i++) productz=productz*x[i]; printf("The Product is: %6.2f",productz); }

Output:

Q 7. Write a program that reads numbers in two integer arrays, x and y, of size m and n and prints

them in ascending order using a function.

Answer: There is a sorting program on page 72 which will be used to do the actual sorting procedure

of this program in the function, which is by the exchange sort method. We will pass the arrays x and

y respectively with their sizes m and n respectively to sort and print the array. This is probably the

longest exercise program in the book.

#include<stdio.h> void sort(int x[],int m); void main(void) {

Page 29: Computer Science for Class XII - Programming using C (Solved Exercises/Programs)

R a e d B i n S h a h i d

Page 28

Computer Science for Class XII - Programming using C 2013

int i,x[50],y[50],m,n; printf("Enter the number of elements of the first array: "); scanf("%d",&m); printf("Enter the number of elements of the second array: "); scanf("%d",&n); for(i=0;i<m;i++) { printf("Enter the %d element of the first array: ",i); scanf("%d",&x[i]); } for(i=0;i<n;i++) { printf("Enter the %d element of the second array: ",i); scanf("%d",&y[i]); } printf("First array in ascending order: "); sort(x,m); printf("\nSecond array in ascending order: "); sort(y,n); } void sort(int x[],int m) { int i,j,holder; for(i=0;i<m-1;i++) for(j=0;j<m-1;j++) if(x[j]>x[j+1]) { holder=x[j]; x[j]=x[j+1]; x[j+1]=holder; } for(j=0;j<m;j++) printf("%d ",x[j]); }

Output:

Page 30: Computer Science for Class XII - Programming using C (Solved Exercises/Programs)

R a e d B i n S h a h i d

Page 29

Computer Science for Class XII - Programming using C 2013

Chapter 7 – File Management Q 3. Write a program that will read a C source file and verify that the number of right and left

braces in the file are equal. Use getc() function to read the file.

Answer: File management programs are the trickiest ones from the textbook but once you

understand them then they are very fun to play around with. To understand this program better

take a look at the program at page 109 ‘Reading Characters from a file’. We have to read a C source

file, preferably the one where you write the code of this program on. And then check if the number

of right and left braces are the same. I will use the file name verifybrace.c but you will have to put

the name of the file you want to read from over there.

#include<stdio.h> void main(void) { FILE *fptr; int r=0,l=0; char ch; fptr=fopen("verifybrace.c ","r"); while((ch=getc(fptr))!=EOF) { if(ch=='{') l++; if(ch=='}') r++; } if(l==r) printf("The Left and Right braces are equal."); else printf("The Left and Right braces are not equal."); fclose(fptr); }

Output:

Q 4. Write a program that will read names and marks of six subjects of five students and stores

them in a file called result.txt.

Answer: The next two programs are done by using formatted input/output. In the beginning I had a

bit of confusion that whether the names here mean the names of subjects or the names of students.

I did the program both ways but then after reading the next question realized that it meant name of

students. So in this program we will store the information into the text file result.txt using fprintf().

Page 31: Computer Science for Class XII - Programming using C (Solved Exercises/Programs)

R a e d B i n S h a h i d

Page 30

Computer Science for Class XII - Programming using C 2013

#include<stdio.h> void main(void) { FILE *fptr; int i,j,marks; char name[30]; fptr=fopen("result.txt","w"); for(i=1;i<=5;i++) { printf("Enter the Name of student(%d): ",i); scanf("%s",&name); fprintf(fptr,"%s ",name); for(j=1;j<=6;j++) { printf("The marks of subject(%d): ",j); scanf("%d",&marks); fprintf(fptr,"%d ",marks); } fprintf(fptr,"\n"); } fclose(fptr); }

Output:

Page 32: Computer Science for Class XII - Programming using C (Solved Exercises/Programs)

R a e d B i n S h a h i d

Page 31

Computer Science for Class XII - Programming using C 2013

After all the entry in the result.txt the text in it should look like in the following image.

Q 5. Write a program that will read names and marks of six subjects of five students from the

result.txt file created in the previous question and prints each student’s name along with his total

and average marks.

Answer: This program requires that you have successfully compiled and executed the previous

program because in this program we are going to read the values from the result.txt file created in

the previous program and do some calculation with the data and then display it. This program can

also be done using arrays and loops but the way I’ve done it is the short version and similar to the

one showed in the textbook on page 113 ‘Reading Formatted Data from a File’. We will use fscanf()

to read the data from the text file result.txt.

#include<stdio.h> void main(void) { FILE *fptr; int mark1,mark2,mark3,mark4,mark5,mark6,total; char name[30]; float avg; fptr=fopen("result.txt","r"); while(fscanf(fptr,"%s %d %d %d %d %d %d",name,&mark1,&mark2,&mark3,&mark4,&mark5,&mark6)!=EOF) { total=mark1+mark2+mark3+mark4+mark5+mark6; avg=(float)total/6; printf("Name:%s\tTotal Marks:%d\t\tAvergae Marks:%6.2f\n",name,total,avg); } fclose(fptr); }

Output: