Vous êtes sur la page 1sur 224

[c programming

example for
techalvee.com
Techalvee is a leading software
firm for web into mobile apps
conversions;

Techalvvee.com

Bonosree Dhaka

info@alveetech
CHAPTER-1
Problem exercise no 1.1&1.2:
Coding of the programme:
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
printf("---------------------------------------\n");
printf("I First line :ilias ahmed design by techalvve.com I\nI Second line :12/a ,Ali sonar
lane I\nI Third line:Bogra,5800 I\n");
printf("---------------------------------------");
getch();
}
Output:

Problem exercise no. 1.3:


Coding of the programme:
#include<stdio.h>
#include<conio.h>
void main()
{clrscr();
printf("*\n* *\n* * *\n* * * * ");
getch();
}
Output:
*
**
***
****

Problem exercise no :1.4


Coding of the problem:
#include<stdio.h>
#include<conio.h>
void main()
{clrscr();
printf("a>>------------------>b");
getch();
}
Output:
a>>------------------>b
Problem exercise no:1.5
Coding of the problem:
#include<stdio.h>
#include<conio.h>
#define pi 3.14159
void main()
{
float r,A;
clrscr();
printf("\n\tENTER THE RADIUS OF A CIRCLE=");
scanf("%f",&r);
A=pi*r*r;
printf("\n\n\tArea=%f sqr unit",A);
getch();
}
Output:
ENTER THE RADIUS OF A CIRCLE=2

Area=12.566360 sqr unit


Problem exercise no:1.6
CODING:
#include<stdio.h>
#include<conio.h>
void main()
{
int b,c;
clrscr();
for(b=1;b<=10;b++)
{
c=5*b;
printf("\n\t%d*%d=%d\n",5,b,c);
getch();
}
}
Output :

Problem exercise no:1.7


Coding of the programme:
#include<stdio.h>
#include<conio.h>
void add();
void sub();
void main()
{
clrscr();
add();
sub();
getch();
}
void add()
{
printf("\n\t%d+%d=%d",20,10,30);
}
void sub()
{
printf("\n\t%d-%d=%d",20,10,10);
}
Output :
20+10=30
20-10=10

Problem exercise no:1.8


Coding:
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c,x;
clrscr();
printf("Enter values of a,b&c\n");
scanf("%d%d%d",&a,&b,&c);
x=a/(b-c);
printf("result=%d",x);
getch();
}
Output:
a)
Enter values of a,b&c
250
85
25
result=4
b)NO OUTPUT
Problem exercise no:1.9 (b)
Coding :
#include<stdio.h>
#include<conio.h>
void main()
{
float a,F,C;
clrscr();
printf("ENTER TEMPERATURE IN FARENHITE\n");
scanf("%f",&F);
a=5*(F-32);
C=a/9;
printf("\nIn celsius scale=%f",C);
getch();
}
Output :
ENTER TEMPERATURE IN FARENHITE
10
In Celsius scale=-12.222222
Problem exercise no:1.9 (a)
Coding :
#include<stdio.h>
#include<conio.h>
void main()
{
float a,F,C;
clrscr();
printf("ENTER TEMPERATURE IN CELSIUS\n");
scanf("%f",&C);
a=(9*C)/5;
F=a+32;
printf("\nIn farenhite scale=%f",F);
getch();
}
Output:
ENTER TEMPERATURE IN CELSIUS
10
In frenhite scale=50.00000

Problem exercise no: 1.10


Coding of the problem:
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
clrscr();
float a,b,c,S,A;
printf("\n\tENTER THE THREE SIDES OF A TRIANGLE=");
scanf("%f%f%f",&a,&b,&c);
S=(a+b+c)/2;
A=sqrt(S*(S-a)*(S-b)*(S-c));
printf("\n\tArea of the triangle=%f",A);
getch();
}
Sample output:
ENTER THE THREE SIDES OF A TRIANGLE=10
12
14
Area of the triangle=58.787754
Problem exercise no:1.11
Coding:
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
float D,x1,x2,y1,y2;
clrscr();
printf("ENTER CO-ORDINATES x1,x2,y1,y2=\n");
scanf("%f%f%f%f",&x1,&x2,&y1,&y2);
D=sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));
printf("Result=%f",D);
getch();
}
Output :
ENTER CO-ORDINATES x1,x2,y1,y2=
2
4
8
5
Result=3.605551
Problem exercise no:1.12
Coding:
#include<stdio.h>
#include<conio.h>
#include<math.h>
#define pi 3.14159

void main()
{
float r,x1,x2,y1,y2,A;
clrscr();
x1=0;
x2=0;
y1=4;
y2=5;
r=sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));
A=pi*r*r;
printf("Result=%f",A);
getch();
}
Output :
Result=3.14159
Problem exercise no:1.13
Coding:
#include<stdio.h>
#include<conio.h>
#include<math.h>
#define pi 3.14159
void main()
{
float D,r,x1,x2,y1,y2,A;
clrscr();
x1=2;
x2=2;
y1=5;
y2=6;
D=sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));
r=D/2;
A=pi*r*r;
printf("Result=%f",A);
getch();
}
Output :
Result=0.785398
Problem exercise no:1.14
Coding:
#include<stdio.h>
#include<conio.h>
void main()
{ int a,b,c;
clrscr();
a=5;
b=8;
c=18;
printf("%dx+%dy=%d",a,b,c);
getch();
}
Output :
5x+8y=18
Problem exercise no:1.15
Coding:
#include<stdio.h>
#include<conio.h>
void main()
{ float x,y,sum,difference,product,division;
clrscr();
printf("ENTER TWO NUMBERS=\n");
scanf("%f%f",&x,&y);
sum=x+y;
difference=x-y;
product=x*y;
division=x/y;
printf("\n\tSum=%f\tDifference=%f\n\n\tProduct=%f\tDivision=%f",sum,difference,prod
uct,division);
getch();
}
Output :
ENTER TWO NUMBERS=
10
5

Sum=15.000000 Difference=5.000000

Product=50.000000 Division=2.000000
solution of C programming by
E.Balagurusamy
CHAPTER-2

CHAPTER
2
Constants,
Variables,
and Data Types
REVIEW QUESTIONS
STATE WHETHER THE FOLLOWING STATEMENTS
ARE TRUE OR FALSE:
(a) Any valid printable ANSII character can be used in an identifier. ( False )
(b) All variables must be given a type when they are declared. ( True )
(c) Declarations can appear anywhere in a program. ( False )
(d) ANSI C treats the variable name and Name to be same. ( False )
(e) The underscore can be used anywhere in an identifier. ( True )
(f) The keyword void is a data type in C. ( True )
(g) Floating point data constants, by default, denote float type values. ( False )
(h) Like variables, constants have a type. ( True )
(i) Character constants are coded using double quotes. (False )
(j) Initialization is the process of assigning a value to a variable at the time of
declaration. ( true )
(k) All static variables are automatically initialized to zero. ( True )
(l) The scanf function can be used to read only one value at a time. ( False )
Fill in the blanks with appropriate words:
(a)The keyword ……………..can be used to create a data type identifier.
Answer: int
(b) …………… is the largest value that an unsigned short int type variable can store.
Answer: 255

(c) A global variable is also known as …………….variable.


Answer: external

(d) A variable can be made constant by declaring it with the qualifier ……………. At
the time of initialization.
Answer: constant

Question: What are trigraph characters? How are they


useful?
Answer:
Trigraph characters is one kinds of character which consists of three characters ( Two
question marks and followed by another ).
Some keyboard does not support some characters. But we can use them by trigraph
characters. If a keyboard does not support square brackets, we can still use them in a
program using the trigraph ??( and ??) .

Question: Describe the four basic data types. How


could we extend the range of values they represent?
Answer:
The basic four data types are:
(1) Char
(2) Int
(3) Float
(4) Void

We cannot extend the range of character.


We could extend the range of integer by using long beforeinteger.
We can extend the range of float by using double. To extend the precision further
we may use long double.

Question: What is an unsigned integer constant? What


is the significant of declaring a constant unsigned?
Answer:
The integer constant which does not take any + or – sign before it is called
an unsigned integer constant.
We can take the value double using an unsigned integer constant. For example,
a signed integer constant have a value between -32768 to +32767, but
an unsigned integer constant takes the value between 0 to 65535.

Question: Describe the characteristics and purpose of


escape sequence characters.
Answer:
C supports some special back slash character constants, that are used in output
function. This characters are known as escape sequence characters. For example, the
symbol “\n” stands for new line character.
Characteristics :
(1) They acts as a single character.
(2) Each escape sequence character consists of two characters.
(3) The first character must be a back slash .

Purpose:
(1) In a program we used it for new line.
(2)In a program we used it for horizontal tab.

Question: What is a variable and what is meant by


“value” of a variable?
Answer:
A variable is a data name that may used to store a data value. Like constants that
remains unchanged during the execution a program.
The meant of value it is a variable name and it can take any value like character, int,
float and double.
Question: How do variables and symbolic names
differ?
Answer:
A variable may be used to store data value. A variable may take different values at
different times during execution of a program. Variables has need to declare at the
beginning of the body but after the main.
Symbolic names is a unique constants. This constants may appear in a number of
place in the program. Symbolic names has need to define at the beginning of a
program.

Question: State the difference between the declaration


of a variable and the definition of a symbolic name?
Answer:
Variables has need to declare at the beginning of the body but after the main. The
syntax for declaring a variable is as follow:
Data-type v1,v2,……..vn;
v1, v2,……..vn are the names of variables. For example, valid declarations are
int count;
int number,total;
float ratio;
Symbolic names has need to define at the beginning of a program. A symbolic name
constants is defined as follows:
#define symbolic-name value of constant
Valid example of constant definations are:
#define STRENGTH 100
#define PASS MARK 5

Question: What is initialization? Why it is important?


Answer:
The process of giving initial values to variables is called initialization. Some examples
are
int final_value =100;
char yes =’x’;
double balance =75.84;
C permits the initialization of more then one variable using multiple assignment
operators.For example the statements
p=q=s=0;
x=y=z=MAX;
are valid.

Question: What are the qualifiers that an int can have


at a time?
Answer:
A signed int can take a value between -32768 to 32767 and an unsigned int can take
a value 0 to 65535.

Question: Describe the purpose of the qualifiers


constant and volatile.
Answer:
We may like the value of certain variables to remain constant during the
excution of a program. We can achieve this by declaring the variable with the
qualifier constant at the time of initialization. Example:
const int class_size=40;
ANSI standard defines another qualifier volatile that could be used to tell
explicitly the complier that a variables value may be changed at any time by some
external sources ( from outside the program). For example:
volatile int date;

Question: When dealing with very small or very large


numbers, what steps would you like you take to
improve the accurancy of the calculation?
Answer:
When we are dealing with a very short number we can improve the accurancy of
calculation by using a keyword short before the keyword. Example short int.
When we are dealing with a very large number we can improve the accurancy of
calculation by using a keyword long before the keyword. Example long int.

Question: Which of the following are invalid constants


and why?
0.0001
Answer: (valid)
5x1.5
Answer: (Invalid)
Reason: Exponent must be an integer.
99999
Answer: Valid
Reason: Long integer.

+100
Answer: ( valid)
75.45E-2
Answer: ( Valid )
-45.6
Answer: ( Valid )
“15.75”
Answer: ( Invalid )
Reason: “” sign is not permitted.

-1.79e+4
Answer: (valid)
0.00001234
Answer: ( Valid )
Question: Which of the following are invalid variable
and why?
Minimum
Answer: ( valid )
First.name
Answer: ( Invalid )
Reason:. Sign is not permitted.
N1+n2
Answer: ( Invalid )
Reason: + sign is not permitted.
&name
Answer: ( Invalid )
Reason: & is not permitted.
Doubles
Answer: ( Valid )
Reason: Keyword may be a part of variable name.
3rd_row
Answer: ( Invalid )
Reason: First character must be a letter or underscore.
n$
Answer: ( Invalid )
Reason: Dollar sign is not permitted.
Row1 ( Valid )
Float
Answer: ( Invalid )
Reason: float is a keyword.
Sum Total
Answer: ( Invalid )
Reason: White space is not permitted.
Row Total
Answer: ( Invalid )
Reason: White space is not permitted.
Column total
Answer: ( Invalid )
Reason: White space is not permitted.

Question: Find errors, if any, in the following


declaration statements.
{
Intx;
float letter,DIGIT;
double=p,q;
exponent alpha,beta;
m,n.z:INTEGER
short char c;
long int m;count;
long float temp;
getch();
}
Error1: intx should have a type.
Error2: Line number 6, expression syntax.
Error3: Line number 7, Declaration should be properly.
Error4:Line number 9, Unreachable code.

Problem no 2.1: Write a program to determine and


print the sum of the following harmonic series for a
given value of n:
1+1/2+1/3+………………+1/n
Solve:
#include<stdio.h>
#include<conio.h>
Void main()
{
int n;
float I, sum, t;
clrscr();
printf(“1+1/2+1/3+……………+1/n\n”);
printf(“Enter the value of n\n”);
scanf(“%d”,&n);
sum=0;
for(i=1;i<=n;i++)
{
t=1/i;
sum=sum+t;
}
printf(“%f”,sum);
getch();
}

Output:
1+1/2+1/3+………….+1/n
Enter the value of n
4
2.083333

The value of n should be given interactively through


the terminal.
Problem no 2.2: Write a program to read the price of an item in decimal form ( like
15.95 ) and print the output in paisa ( like 1595 paisa) .
Solve:
#include<stdio.h>
#include<conio.h>
void main()
{
int b;
float a;
a=15.95;
clrscr();
b=100*a;
printf("%d",b);
getch();
}

Output:
1595

Problem no 2.3: Write a program that’s prints the even


numbers from 1 to 100.
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
for(i=1;i<=100;i++)
{
if(i%2==0)
printf(" %d",i);
}
getch();
}

Output
2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50
52 54 56 58 60 62 64 66 68 70 72 74 76 78 80 82 84 86 88 90 92 94 96 9
8 100

Problem no 2.4: Write a program that request two


float type numbers from the users and then divides the
first number by the second and display the result along
with the numbers.
Solve:
#include<stdio.h>
#include<conio.h>
void main()
{
float number1, number2, number3;
clrscr();
printf("Enter the value of number1 and number2\n");
scanf("%f %f",&number1,&number2);
number3=number1/number2;
printf("%f/%f=%f",number1,number2,number3);
getch();

Output:
Enter the value of number1 and number2
15.5
6.6
15.5/6,6=2.348484

Problem no 2.5: The price of one kg of rice is Rs. 16.75


and one kg of sugar is Rs. 15. Write a program to get
these values from the user and display the prices as
follows:
***LIST OF ITEMS***
Item Price
Rice Rs 16.75
Sugar Rs 15.00
Solve:
#include<stdio.h>
#include<conio.h>
void main ()
{
float Rice,Sugar;
Rice=16.75;
Sugar=15.00;
clrscr();
printf("***LIST OF ITEMS***\n");
printf("Item \tPrice\n");
printf("Rice\tRs%.2f\n",Rice);
printf("Sugar\tRs%.2f\n",Sugar);
getch();
}

Output:
***LIST OF ITEMS***
Item Price
Rice Rs16.75

Question: Identify syntax errors in the following


program. After correcting, what output would you
expect when you execute it.
#include<stdio.h>
#include<conio.h>
#define PI 3.14159
void main()
{
int R,C;
float perimeter;
float area;
C=PI;
R=5;
perimeter=2.0*C*R;
Area = C*R*R;
printf("%f", "%d",&perimeter,&area)
}

Errors:
Cpp 10: Undefined symbol Area.
Cpp 12:statement missing,in function{}
Cpp12: compound statement missing.
Solve:
#include<stdio.h>
#include<conio.h>
#define PI 3.14159
void main()
{
int R,C;
float perimeter,Area;

C=PI;
R=5;
perimeter=2.0*C*R;
Area = C*R*R;
printf("%f %f",perimeter,Area);
getch();
}

CHAPTER-3
EXERCISE NO.3.1: Given the values of the variables X,Y and Z write a program to rotate
their values such that X has the value of Y,Y has the value of Z and Z has the value of X.

SOLUTION:

#include<stdio.h>

#include<conio.h>

void main()

int x,y,z,temp;

clrscr();

printf("Enter the value of x,y,z\n");

scanf("%d %d %d",&x,&y,&z);

temp=x;

x=y;

y=z;

z=temp;

printf("%d %d %d",x,y,z);

getch();

EXERCISE NO.3.2: write a program that reads a floating-point number and then displays
right-most digit of the integral part of the number.

SOLUTION:

#include<stdio.h>

#include<conio.h>

void main()

{
int a,e;

float p;

clrscr();

printf("Enter the value of p\n");

scanf("%f",&p);

a=int(p);

printf("%d\n",a);

e=a%10;

if(a>10)

printf("%d\n",e);

getch();

EXERCISE NO.3.3. Modify the above program to display to right-most digits of the integral
part of the number.

SOLUTION:

#include<stdio.h>

#include<conio.h>

void main()

int a,e;

clrscr();

printf("Enter the value of a\n");

scanf("%d",&a);

e=a%100;

if(a>100)

printf("%d\n%d\n",a,e);
getch();

3.4: Write a program that will obtain the length and width of a rectangle from the user and
compute its area and perimeter.

SOLUTION:

#include<stdio.h>

#include<conio.h>

void main()

int length,width;

clrscr();

float area,perimeter;

printf("Enter the value of length,width\n");

scanf("%d %d",&length,&width);

area=(length*width);

perimeter=2*(length+width);

printf("%f %f",area,perimeter);

getch();

EXERCISE NO.3.5: Given an integer number, write a program that displays the number as
follows:

First line: all digits

Second line: all except first digit

Third line: all except first two digits

…………
Last line: The last digit

For example the number 5678 will be displayed as:

5678

678

SOLUTION:

#include<stdio.h>

#include<conio.h>

void main()

int a,b,c,e,x;

float p;

clrscr();

printf("Enter the value of p\n");

scanf("%f",&p);

a=int(p);

printf("%d\n",a);

e=a%10000;

b=e%1000;

c=b%100;

x=c%10;

if(a>10000)

printf("%d\n%d\n%d\n%d\n",a,e,b,c,x);

else if(a>1000)

printf("%d\n%d\n%d\n",a,b,c,x);

else if(a>100)

printf("%d\n%d\n",a,c,x);

else if(a>10)

printf("%d\n%d\n",a,x);
getch();

EXERCISE NO.3.6: The straight-line method of computing the yearly depreciation of the
value of an item is given by

Depreciation=

Write a program to determine the salvage value of an item when the purchase price , years of
service, and the annual depreciation are given.

SOLUTION:

#include<stdio.h>

#include<conio.h>

void main()

int years;

float s, d,p;

clrscr();

printf("Enter the value of years,d,p\n");

scanf("%d %f %f",&years,&d,&p);

s=p-(years*d);

printf("%f",s);

getch();

EXERCISE NO.3.7: Write the program that will read a real number from the keyboard and
print the following output in one line:

Smallest integer The given Largest integer


not less then number not greater than

the number the number

SOLUTION:

#include<stdio.h>

#include<conio.h>

void main()

float m;

int n,p;

clrscr();

printf("Enter the value of m\n");

scanf("%f",&m);

n=(m/1)+1;

p=m;

printf("%d %f %d",n,m,p);

getch();

EXERCISE NO.3.8: The total distance travelled by a vehicle in t seconds is given by

Distance= ut+(at2)/2

Where u is the initial velocity( meter per second),a is the acceleration (meter per second2).
Write a program to evaluate the distance travelled at intrevales of time, give the value
of u and a. the program should provide the flexibility to the user to select his own time
intervals and repeat the calculation for different value of u and a.

SOLUTION:

#include<conio.h>

void main()

{
int a,u,t;

float distance;

clrscr();

printf("Enter the value of a,u,t\n");

scanf("%d %d %d",&a,&u,&t);

distance=u*t+(a*t*t)/2;

printf("%f",distance);

getch();

EXERCISE NO.3.9: In inventory management ,the Economic Order Quantity for a single
item is given by

EOQ=sqrt { ( 2*demand rate*setup rate ) / ( holding cost per item per unit time ) }

And the Time Between Orders

TBO =sqrt { ( 2* setup cost ) / (demand rate * holding cost per item per unit time ) }

SOLUTION 1:

#include<stdio.h>

#include<conio.h>

#include<math.h>

void main()

{ float EOQ,d,s,h,x;

Clrscr();

printf("Enter the value of d,s,h\n");

scanf("%f %f %f",&d,&s,&h);

x=(2*d*s)/h;

EOQ=sqrt(x);
printf("%f",EOQ);

getch();

SOLUTION 2:

#include<stdio.h>

#include<conio.h>

#include<math.h>

void main()

float x,s,d,h,TOB;

clrscr();

printf("Enter the value of s,d,h\n");

scanf("%f%f%f",&s,&d,&h);

x=(2*s)/(d*h);

TOB=sqrt(x);

printf("%f",TOB);

getch();

EXERCISE NO.3.10: For a certain electrical circuit with an inductance L and resistance R,the
damped natural frequency is given by

Frequency =sqrt { (1/L*C ) - ( R*R/4*C*C ) }

It is desired to study the variation of this frequency with C(capacitance).Write a program to


calculate the frequency for different values of C starting from 0.01 to 0.1 in steps of 0.01.

SOLUTION:

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

#include<math.h>

void main()

float L,R,C,x,a,b,F;

clrscr();

printf("Enter the value of L,R,C\n");

scanf("%f %f %f",&L,&R,&C);

a={ (1/L*C) – (R*R/4*C*C) };

F=sqrt(a);

Printf(“%f”,F);

getch();

EXERCISE NO.3.11: Write program to read a four digit integer and print the sum of its digit.
Hints: Use / and % operators.

SOLUTION:

#include<stdio.h>

#include<conio.h>

void main()

int num,a,b,c,d,x,y,result;

clrscr();

printf("Enter a number");

scanf("%d",&num);

a=num%10;

x=num/10;

b=x%10;
y=x/10;

c=y%10;

d=y/10;

result=a+b+c+d;

printf("%d",result);

getch();

EXERCISE NO. 3.12: Write a program to print the size of various data types in C.

SOLUTION:

#include<stdio.h>

#include<conio.h>

void main()

int m;

clrscr();

m=sizeof(10);

printf("Size=%d",m);

getch();

EXERCISE NO.3.13: Given three values, write a program to read three values from keyboard
and print out the largest of them without using if statement.
SOLUTION:

#include<stdio.h>

#include<conio.h>

void main()

int x,y,z,a,b;

printf("Enter the value of x,y,z\n");

scanf("%d%d%d",&x,&y,&z);

printf("largest\n");

a=(x>y)?x:y

b=(a>z)?a:z

printf("%d",b);

EXERCISE NO.3.14: Write a program to read two integer values m and n and to decide and
print whether m is multiple of n.

SOLUTION:

#include<stdio.h>

#include<conio.h>

void main()

int m,n;

printf("Enter m & n,m>=n:");

scanf("%d %d",&m,&n);

if(m%n==0)

printf("m is a multiple of n");

else

printf("m is not a multiple of n");


getch();

EXERCISE N0.3.15: Write a program to read three values using scanf statement and print
the following results:

(a)Sum of the values

(b) Average of the three values

(c) Largest of the three

(d) Smallest of the three.

SOLUTION:

#include<stdio.h>

#include<conio.h>

void main()

int a,b,c,x,y;

float sum, average;

clrscr();

printf("Enter the value of a,b,c\n");

scanf("%d%d%d",&a,&b,&c);

sum=(a+b+c);

printf("sum=%f\n",sum);

average=sum/3;

printf("average=%f\n",average);

{
printf("Largest\n");

x=(a>b)?a:b;

y=(x>c)?x:c;

printf("%d\n",y);

printf("Smallest\n");

x=(a<b)?a:b;

y=(x<c)?x:c;

printf("%d\n",y);

getch();

EXERCISE NO.3.16: The cost of one type of mobile service is Rs.250 plus Rs.1.25 for each
call made over and above 100 calls. Write a program to read customer codes and calls made
and print the bill for each customer.

SOLUTION:

#include<stdio.h>

#include<conio.h>

void main()

int code,call;

float bill;

clrscr();
printf("Enter customer code and number of calls made:");

scanf("%d %d",&code,&call);

bill=250+(call*1.25);

printf("Bill=%f",bill);

getch();

EXERCISE NO.3.17: Write a program to print a table of sin and cos functions for the interval
0 180 degrees in increments of 15 as shown below.

-----------------------------------------------------------------------------------------------
x(degees) sin(x) cos(x)

O ……. …….

15 .…… …….

….. ……. …….

SOLUTION:

#include<stdio.h>

#include<conio.h>

#include<math.h>

#define p1 3.1416

#define MAX 180

void main()

int i;

float x,y,z;

clrscr();
i=0;

printf("x(degree) sin(x) cos(x)\n");

while(i<=MAX)

x=(p1/MAX)*i;

y=sin(x);

z=cos(x);

printf("%d\n %f\n %f\n",i,y,z);

i=i+15;

getch();

EXERCISE NO.3.18: Write a program to compute the values of square-roots and squares of
the number 0 to 100 in steps 10 print the output in a tabular form as shown below.

-----------------------------------------------------------------------------------------------
number Square-root square

0 0 0

100 10 10000

SOLUTION:

#include<stdio.h>

#include<conio.h>

#include<math.h>

void main()

/*......square root and square of numbers 0 to 100.....*/


int i,y;

float x;

clrscr();

printf("Number\tSquare root\tSquare\n\n");

for(i=0;i<=100;i++)

x=sqrt(i);

y=i*i;

printf("%d\t%f\t%d\n",i,x,y);

getch();

EXERCISE NO.3.19: Write a program that determines whether a given integer is odd or even
and displays the number and description on the same line.

SOLUTION:

#include<stdio.h>

#include<conio.h>

void main()

int x;

clrscr();

printf("Enter the integer number:");

scanf("%d",&x);

if(x%2==0)

printf("THe number %d is even",x);

else

printf("The number %d is odd",x);


getch();

EXERCISE NO.3.20: Write a program to illustrate the use of cast operator in a real life
situation.

SOLUTION:

include<stdio.h>

#include<conio.h>

void main()

float sum;

int n;

clrscr();

sum=0;

for(n=1;n<=10;++n)

sum=sum+1/(float)n;

printf("%2d %6.4f\n",n,sum);

getch();

Posted by hstu at 9:46:00 PM

Email ThisBlogThis!Share to TwitterShare to Facebook

4 comments:
1.

Niteesh BihadeJuly 30, 2012 at 2:30 AM

Thank you for your tutorial and lectures. I am just posting a more simple code to
your question 3.2
EXERCISE NO.3.2: Write a program that reads a floating-point number and then
displays right-most digit of the integral part of the number.

#include

main()
{
float a;
int num;

printf("Enter a real number:\t");


scanf("%f", &a);

num = (int)a%10;
printf("Rightmost integer\t %d", num);
}
Reply

2.

NiteeshAugust 1, 2012 at 2:31 AM

Code edit for solution 3.10. Please edit the given values appropriately to suit your
solution needs. The code written below is edited and is more in accordance to the
question asked.

#include
#include

main()
{
float l = 1000.0, r = 500.0;
float step = 0.01, limit = 0.1, c = 0.01;
float frequency = 0;

while(c<=limit)
{
frequency = sqrt( (1/l*c) - ((r*r)/(4*c*c)) );
printf("Step - %f\tFrequency - %f\n", step, frequency);
c = c+step;
}
}
Reply

3.

NiteeshAugust 1, 2012 at 2:50 AM

3.11 A more elegant and easy to understand code for beginners...

#include

main()
{
int a;

printf("Enter four digit integer: \t");


scanf("%d", &a);

//Remember always division operator gives quotient wheras the modulo operator
gives remainder
int a1 = a/1000; // a = 2356, a1 = 2
int a2 = a%1000; // a2 = 356
int a3 = a2/100; // a3 = 3
int a4 = a2%100; //a4 = 56
int a5 = a4/10; //a5 = 5;
int a6 = a4%10; //a6 = 6;

printf("\n\n%d", a1);
printf("\n%d", a3);
printf("\n%d", a5);
printf("\n%d", a6);
printf("\n-----------------------------------------------------------------------------------
\n\n");

int sum = a1+a3+a5+a6;


printf("Sum of Digits - %d", sum);
}
3.12 - Write a program to print the size of various data types in C.

Commentor's note - The code published above by the blogger is flawed. Below I
present the correct solution.

#include

main()
{
int i = sizeof(int);
int f = sizeof(float);
int d = sizeof(double);
int c = sizeof(char);

printf("Size of data type integer - %d", i);


printf("\nSize of data type float - %d", f);
printf("\nSize of data type double - %d", d);
printf("\nSize of data type char - %d\n\n\n", c);

E.Balagurusamy C PROGRAMMING
:CHAPTER-4

4.6 STATES ERRORS,IF ANY,IN THE


FOLLOWING STATEMENTS.
[A] :scanf(“%c %f %d”,city,&price,&year);
=NO ERROR.
[B] :scanf(“%s %d”,city,amount);
= THERE WILL BE A & BEFORE AMOUNT.
[C] :scanf(“%f %d”,&amount,&year);
=NO ERROR.
[D] :scanf(\n”%f”,root);
=\n will remain into double quote.
[E] :scanf(“%c %d %ld”,*code,&count,root);
=* IS NOT ALLOWED BEFORE CODE AND &WILL STAY
BEFORE ROOT.

4.7 WHAT WILL BE THE VALUES STORED OF


THE VARIABLES YEAR AND CODE WHEN THE
DATA 1988,X ?
[A] :scanf(“%d %c”,&year,&code);
=YEAR STORS 1988 AND CODE STORS X.
[B] :scanf(“%c %d”,&year,&code);
= YEAR STORS X AND CODE STORS 1988.
[C] :scnaf(“%d %c”,&code,&year);
=CODE STORS 1988 AND YEAR STORS X.

4.8 COUNT,PRICE,CITY HAVE VALUES:


COUNT=1275,
PRICE=235.74,
CITY=CAMBRIDGE.
WHAT WILL BE THE OUTPUT THE
STATEMENT ?
[A] :printf(“%d %f”,count,price);
OUTPUT=1275 235.75.
[B] :printf(“%d %f”,price,count);
OUTPUT=36576 790980
[C] :printf(“%c”,city);
OUTPUT=CAMBRIDGE

4.9 SHOW THE WRONG OF THE OUTPUT


STATEMENTS.
[A] :printf(“%d.7.2%f”,year,amount);
WRONG=7.2 SHOULD REMAIN AFTER THE %
[B] :printf(“%-s,%c”\n,city,code);
WRONG=COMMA IS NOT ALLOWED AND \n SHOULD STAY
INTO QUOTATION.
[C] :printf(“%f %d %s”,price,count,city);
=NO WRONG.

4.10 WHAT VALUES DOSE THE COMPUTER


ASSIGN OF THIS INPUT STATEMENTS?
Scanf(“%4d %*d”,&year,&code,&count);
IF DATA KYED IN 19883745
0UTPUT=1988.

4.11 HOW CAN WE USE getcher() FUNCTION TO


MULTICHARACTER STRINGS?
=BY INCLUDING SINGLE QUOTATION OVER
MULTICHARACTER WE
CAN USE getchar() FUNCTION.

4.12 HOW CAN WE USE putchar() FUNCTION


TO MULTICHARACTER STRINGS?
=BY INCLUDING SINGLE QUOTATION OVER
MULTICHARACTER WE
CAN USE putchar() FUNCTION.

4.13 WHAT IS THE PURPOSE OF scanf()


FUNCTION?
=IF WE WANT TO TAKE DATA AFTAR RUNNING THE
PROGRAMM THEN
WE USE scanf FUNCTION.

4.14 DESCRIBE THE PURPOSE OF COMMONLY


USED CONVERSION CHARACTERS IN A scanf()
FUNCTION ?
=IT INDICATES WHAT TYPES OF DATA WE TAKE AS
INPUT.

4.15 WHAT HAPPENS WHEN AN INPUT DATA


ITEM CONTAIN ?
[A] MORE CHARACTERS THAN SPECIFIED
FIELD WIDTH.
=VALUE WILL BE RIGHT-JUSTIFIED.
[B] FEWER CHARACTER THAN SPECIFIED
FIELD WIDTH.
=VALUE WILL BE LEFT-JUSTEFIED.
4.16 WHAT IS THE PURPOSE OF printf()
FUNCTION ?
=IT IS USED TO SHOW ANYTHIG ON OUTPUT.
4.17 DESCRIBE THE PURPOSE OF COMMONLY
USED CONVERSION CHARACTERS IN A
printf() FUNCTION ?
= IT INDICATES WHAT TYPES OF DATA WE WANT TO
SHOW ON
OUTPUT.

4.18 WHAT HAPPENS WHEN AN 0UTPUT


DATA ITEM CONTAIN ?
[A] MORE CHARACTERS THAN SPECIFIED
FIELD WIDTH.
=VALUE WILL BE RIGHT-JUSTIFIED.
[B] FEWER CHARACTER THAN SPECIFIED
FIELD WIDTH.
=VALUE WILL BE LEFT-JUSTEFIED.
Problem no. 4.1:Given the string“WORDPROCESSING”,
Write a program to read the string from the terminal and
Display the same in the following format:
(a)WORD PROCESSING
(b)WORD
PROCESSING
(c) W.P.

Solution:

#include<stdio.h>

#include<conio.h>

void main()

char s[10],d[11];

clrscr();

printf("Enter the string: ");

scanf("%4s%10s",s,d);

printf("(a)%s %s\n",s,d);

printf("(b)%s\n%s\n",s,d);

printf("(c)%.1s.%.1s",s,d);

getch();

Output:

Enter the string: WORDPROCESSING


(a) WORDPROCESSING

(b) WORD

PROCESSING

(c) W.P.

Problem no. 4.2: Write a program to read the values of x and y


and print the results of the following expression in one line:

(a)(x+y)/(x-y) (b)(x+y)/2 (c)(x+y)*(x-y)

Solution:
#include<stdio.h>

#include<conio.h>

void main()

float x,y,a,b,c;

clrscr();

printf("Enter the value of x & y: ");

scanf("%f%f",&x,&y);

if(x-y==0)

printf("(a)=imagine");

else

{
a=(x+y)/(x-y);

printf("(a)=%.2f",a);

b=(x+y)/2;

c=(x+y)*(x-y);

printf(" (b)=%.2f (c)=%.2f",b,c);

getch();

Output:
Enter the value of x & y: 4 3
(a)=7.00

(b)=3.50

(c)=12.00

Enter the value of x & y: 7 7

(a)= imagine

(b)=7.00

(c)=0.00

Problem no. 4.3: Write a program to read the following numbers,


round them off to the nearest integers and print out
the results in integer form:
35.7 50.21 -23.73 -46.45

Solution:
#include<stdio.h>

#include<conio.h>

void main()

int p,i;

float a;

clrscr();

printf("ENTER REAL NUMBER FOR GET NEAREST INTEGER NUMBER\n");

for(i=1;i<=4;i++)

scanf("%f",&a);

if(a>=0)

p=a+0.5;

else

p=a-0.5;

printf("\nNEAREST INTEGER NUMBER OF %f IS= %d\n",a,(int)p);

getch();

Output:
ENTER REAL NUMBER FOR GET NEAREST INTEGER NUMBER 35.7

NEAREST INTEGER NUMBER OF 35.7 IS= 36

ENTER REAL NUMBER FOR GET NEAREST INTEGER NUMBER 50.21

NEAREST INTEGER NUMBER OF 50.21 IS=50


ENTER REAL NUMBER FOR GET NEAREST INTEGER NUMBER -23.73

NEAREST INTEGER NUMBER OF -23.73 IS= -24

ENTER REAL NUMBER FOR GET NEAREST INTEGER NUMBER -46.45

NEAREST INTEGER NUMBER OF -46.45 IS= -46

Problem no. 4.4:write a program that read 4 floating values in


the range, 0.0 to20.0, and prints a horizontal bar chart to
represent these values using the character * as the fill
character. For the purpose of the chart, the values may be
rounded off to the nearest integer . For the example ,
the value 4.36 should be represented as follos,

* * * *
* * * * 4.36
* * * *
Solution:

#include<stdio.h>

#include<conio.h>

void main()

float a1,a2,a3,a4;

int x,y,z,t,i;

clrscr();

printf("Enter four float number:");


scanf("%f%f%f%f",&a1,&a2,&a3,&a4);

x=a1+0.5;y=a2+0.5;z=a3+0.5;t=a4+0.5;

printf("The horizontal bar chard is:\n");

for(i=0;i<x;i++)

printf("* ");

printf("%.2f\n",a1);

for(i=0;i<y;i++)

printf("* ");

printf("%.2f\n",a2);

for(i=0;i<z;i++)

printf("* ");

printf("%.2f\n",a3);

for(i=0;i<t;i++)

printf("* ");

printf("%.2f\n",a4);

getch();

Output:
Enter four float number: 4.85 4.36 3.12 5.47

The horizontal bar chard is:

* * * * * 4.85

* * * * 4.36

* * * 3.12

* * * * * 5.47

Problem no.4.5: Write a program to demonstrate the process of


multiplication. The program should ask the user to enter two
two digit integer and print the product of integers as
shown bellow.
45
X 37
7x45 is 315
3x45is 135
Add them 1665

Solution:
#include<stdio.h>

#include<conio.h>

void main()

int a,b,c,p;

clrscr();

printf("Enter 2 two digits number:");

scanf("%d%d",&a,&b);

printf(" \t%4d\n\tx%3d\n",a,b);

printf("\t------\n");

p=b/10;

c=b%10;

printf("%dx%dis%6d\n",c,a,c*a);

printf("%dx%dis%5d\n",p,a,p*a);

printf("\t-------\n");

printf("Add them %d\n",a*b);

printf("\t-------");
getch();

Output:
45

X 37

7x45 is 315

3x45is 135

Add them 1665

Problem no.4.6: Write a program to read three integers from


the keyboard using one scanf statement and output them on
one line using:
(a)three printf statements,
(b)only one printf with conversion specifiers and
(c) only one printf without conversion specifiers.

Solution:

#include<stdio.h>

#include<conio.h>

void main()

int x,y,z;

clrscr();

printf("Enter three integer value of x,y,&z:");


scanf("%d%d%d",&x,&y,&z);

printf("(a) X=%d,",x);

printf("Y=%d,",y);

printf("Z=%d\n",z);

printf("(b) X=%3d, Y=%2d, Z=%2d\n",x,y,z);

printf("(c) X= %d, Y=%d, Z=

%d",x,y,z);

getch();

Output:
Enter three integer value of x,y,&z: 45 27 89

(a) X=45, Y=27, Z=89

(b) X=45, Y=27, Z=89

(c) X=45, Y=27, Z=89

Problem no.4.7: Write a program that prints the


value 10.45678 in exponential format with the following
specifications:
(a)correct to two decimal place,
(b)correct to four decimal place and
(c)correct to eight decimal place.

Solution:

#include <stdio.h>

#include<conio.h>

int main(void)

float a=10.45678,x,y,z;

clrscr();

printf("%8.2e\n%10.4e\n%10.8e",a,a,a);

getch();

return 0;

Output:

1.04e+01

1.0456e+01

1.04567804e+01
Problem no.4.98 Write a program to print the value 345.6789
in fixed-point format with the following specifications:
(a)correct to two decimal place,
(b)correct to four decimal place and
(c)correct to zero decimal place.

Solution:

#include <stdio.h>

#include<conio.h>

void main()

float a=345.6789;

clrscr();

printf("The two decimal place is: %.2f\n",a);

printf("The five decimal place is: %.5f\n",a);

printf("The zero decimal place is: %.0f",a);

getch();
}

Output:
The two decimal place is: 345.67

The five decimal place is: 345.67889

The two decimal place is: 345

Problem no.4.9: Write a program to read the name ANIL


KUMAR GUPTA in three parts using the scanf statement
and to display the same in the following format using the printf
statement.

(a) ANIL K. GUPTA


(b) A. K. GUPTA
(c) GUPTA A. K.

Solution:

#include<stdio.h>

#include<conio.h>

void main()

char s[6],d[6],c[6];

clrscr();

printf("Enter the string:");

scanf("%5s%5s%5s",s,d,c);

printf("(a) %s %.1s. %s\n",s,d,c);

printf("(b) %.1s.%.1s.%s\n",s,d,c);

printf("(c) %.1s.%.1s.\n",c,s,d);

getch();

Output:
Enter the string: ANIL KUMAR GUPTA

(a) ANIL K. GUPTA

( b) A. K. GUPTA
(d) GUPTA A. K.

Problem no.4.10: Write a program to read and disply the


following table of data

Name Code Price


Fan 67831 1234.50
Motor 450 5786.70
The name and code must be left-justified and price must
be right-justified .

Solution:
#include<stdio.h>

#include<conio.h>

void main()

int code1,code2;

float price1,price2;

char name1[10],name2[10];

clrscr();

printf("Enter first name ,code and price :");


scanf("%s%d%f",name1,&code1,&price1);

printf("Enter second name ,code and price :");

scanf("%s%d%f",name2,&code2,&price2);

printf("Name\tCode\tPrice\n");

printf("%-s\t%-d\t%.2f\n",name1,code1,price1);

printf("%-s\t%-d\t%.2f\n",name2,code2,price2);

getch();

Output:
Enter first name ,code and price : Fan 67831 1234.50

Enter second name ,code and price : Motor 450 5786.70

Name Code Price

Fan 67831 1234.50

Motor 450 5786.70

Chapter 5
DECISION MAKING AND BRANCHING
REVIEW QUESTION:
RQ-5.1:State whether the following are true or false :
(a)When if statements are nested , the last else gets associated with the
nearest
if without an else.
Ans: False.
(b)One if can have more than one else clause.
Ans: False.
(c)A switch statement can always be replaced by a series of if..else statements.
Ans: False.
(d)A switch expression can be of any type.
Ans: False.
(e)A program stops its execution when a break statement is encountered.
Ans: False.
(f)Each expression in the else if must test the same variable.
Ans: True.
(g)Any expression can be used for the if expression.
Ans: True.
(h)Each case label can have only one statement.
Ans: True.
(i)The default case is required in the switch statement.
Ans: True.
(j)The predicate !( (x>=10) (y==5) ) is equivalent to (x<10) && (y!=5 ).
Ans: True.

RQ-5.2:Fill in the blanks in the following statements:


(a)The ……….operator is true only when both the operands are true.
Ans: logical AND (&&).
(b)Multiway section can be accomplished using an else if statement or
the . ……………statement.
Ans: switch.
(c)The……….. statement when executed in a switch statement causes.
immediate exit from the structure
Ans: break.
(d)The ternary conditional expression using the operator ?: code be easily
coded using ………..statement.

Ans: if…else.
(e)The expression !(x!=y)can be replaced by the expression…………
Ans: x==y.

RQ-5.3:Find errors, if any, in each of the following segments:


Solution:
(a)if((x+y=z) && (y>0) )
printf(" ");
Ans: Error.
Correct ans: if((x+y==z) && (y>0) )
printf(" ");
(b) if (code >1)
a= b+c
else
a=0
Ans: Error.
Correct ans: if (code >1)
a= b+c;
else
a=0;
(c) if(p>0) || (q <0)
printf("Sign is negative”);
Ans: Error.
Correct ans:if((p>0) || (q <0))
printf("Sign is negative”);

RQ-5.4:The following is a segment of a program:


x=1;
y=1;
if(n>0)
x=x+1;
y=y-1;
printf("%d %d", x,y);
what will be the values of x and y if n assumes a value of (a) 1and (b) 0.
Solution:
(a)The value of x is 2 & y is 0.
(b)The value of x & y is imaginary.
RQ-5.5:Rewrite each of the following without using compound relations:
(a) if(grade<=59&&grade>=50)
second=second+1;
Solution:
if(grade<=59)
second=second+1;
if(grade>=50)
second=second+1;

(b) if ( number>100||number<0)
printf(“Out of range”);
else
sum=sum+number;
Solution:
if ( number>100)
printf(“Out of range”);
else if(number<0)
printf(“Out of range”);
else
sum=sum+number;
(c) if (M1>60&&M2>60||T>200)
printf(“Admitted\n”);
else
printf (“Not admitted”);
Solution:
if (M1>60)
printf (“Admitted\n”);
if (M2>60)
printf (“Admitted\n”);
else if(T>200)
printf (“Admitted\n”);
else
printf (“Not admitted”);

RQ-5.6:Assuming x=10 ,state whether the following logical expressions are


true or false:
(a)x==10 && x>10 && !x Ans:False.
(b)x==10 || x> 10 && !x Ans:True.
(c)x==10 && x>10 ||!x Ans:False.
(d)x==10 ||x>10 || !x Ans:True.

RQ-5.7:Find errors,if any, in the following switch related statements.Assume


that the variables x and y are of int type and x=1 and y=2.
Solution:
(a)switch(y);
Ans: Error.
Correct ans: switch(y)
(b)case 10;
Ans: Error.
Correct ans: case 10:
(c)switch(x+y)
Ans:No error.
(d)switch(x) {Case 2: y= x+y; break};
Ans: Error.
Correct ans: switch(x) {Case 2: y= x+y; break;}

RQ-5.8:Simplify the following compound logical expressions:


(a) !(x<=10) (b)!(x==10)||!((y==5)||(z<0))
Ans:(x>10) Ans: (x>0)
(c)!((x+y==z)&&!(z>5)) (d)!((x<=5)&&(y==10)&&(z<5))
Ans: (x<z) Ans: (x>5)

RQ-5.9:Assuming that x=5, y=0,and z=1 initially ,what will be their


values after executing the following code segments?
(a)if(x && y)
x=10;
else
y=10;
Output:
10
10
(b)if(x|| y ||z)
y=10;
else
z=0;
Output:
1
0
(c)if(x)
if(y)
z=10;
else
z=0;
Output:
10
0
(d)if(x ==0 || x && y)
if(!y)
z=0;
else
y=1;
Output:
0
1

RQ-5.10:Assuming that x=2,y=1 and z=0 initially ,what will be their


values after executing the following code segments?
(a)
switch(x)
{
case 2:
x=1;
y=x+1;
case 1:
x=0;
break;
default:
x=1;
y=0;
}
Output:
1
0
(b)
switch(y)
{
case 0:
x=0;
y=0;
case 2:
x=2;
z=2;
default:
x=1;
y=2;
}
Output:
0 0 0
RQ-5.11:Find the error ,if any,in the following statements:
Solution:
(a)if(x>=10)
printf("\n");
Ans: No error.
(b)if(x>=10)
printf("OK");
Ans: No error.
(c)if(x==10)
printf ("Good");
Ans : No error.
(d)if(x=<10)
printf("Welcome");
Ans : Error.
Correct ans: if(x<=10)
Printf(“Welcome”);

RQ-5.12:What is the output of the following program?


Program:
main()
{
int m=5;
if(m<3) printf("%d", m+1);
else if (m<5) printf("%d", m+2);
else if (m<7) printf("%d", m+3);
else printf("%d", m+4);
getch();
}
Output:
8

RQ-5.13:What is the output of the following program?


Program:
main ()
{
int m=1;
if( m==1)
{
printf ("Delhi");
if(m==2)
printf("Chennai");
else
printf("Banglore");
}
else
Printf("END");
getch();
}
Output:
1
Delhi
2
Chennai
3
Banglore

RQ-5.14:What is the output of the following program?


Program:
main()
{
int m;
for(m=1; m<5; m++)
printf("%d\n",(m%2) ? m : m*2);
getch();
}
Output:
1 4 3 8

RQ-5.15:What is the output of following program?


Program:

main()
{
int m,n,p;
for(m=0; m<3;m++)
for(n=0;n<3;n++)
for(p=0;p<3;p++)
if(m+n+p==2)
goto print;
print:
printf("%d %d %d",m,n,p);
getch();
}

Output:
0 0 2

RQ-5.16:What will be the value of x when the following segment is executed?


int x=10,y=15;
x= (x<y)? (y+x) : (y-x) ;

Solution:
The value of x after execution is :-25.
RQ-5.17:What will be the output when the following segment is executed?
int x=0;
if(x>=0)
if(x>0)
printf("Number is positive");
else
printf("Number is negative");
Output:
0
Number is positive
1
Number is negative

RQ-5.18: What will be the output when the following segment is executed?
Program:
char ch = ‘a’
switch(ch)
{
case ‘a’:
printf(“A”);
case ‘b’:
printf(“B”);
case ‘c’:
printf(“C”);
}
Output:
a
A
b
B
c
C

RQ-5.19:What will be the output of the following segment when executed?


Program:
main()
{
int x=10,y=20;
if(( x<y)|| (x+5)>10)
printf("%d",x);
else
printf("%d",y);
getch();
}
Output:
10

RQ-5.20:What will be the output of the following segment when executed?


Program:
main()
{
int a=10, b=5;
if(a>b)
{
if(b>5)
printf("%d",b);
}
else
printf("%d",a);
getch();
}
Output:
10
CHAPTER 5
Decision Making and Branching
EXERCISE-5.1 Write a program to determine whether a given number is odd or even and
print the message:
NUMBER IS EVEN or NUMBER IS ODD

(a) without using else option, and (b) with using else option.

Solution:

(a) without using else option:

/*………………even or odd……………*/

#include<stdio.h>
#include<conio.h>
void main()
{
int n;
clrscr();
printf(“Enter a number\n”)
scanf("%d",&n);
if(n%2==0)
printf("NUMBER IS EVEN ");
if(n%2==1)
printf("NUMBER IS ODD ");
getch();
}
(b) with else option:

/*………………even or odd……………*/

#include<stdio.h>
#include<conio.h>
void main()
{
int n;
clrscr();
printf(“Enter a number\n”)
scanf("%d",&n);
if(n%2==0)
printf("Even");
else
printf("Odd");
getch();
}
EXERCISE-5.2 Write a program to find the number of and sum of all integers greater than
100 and less than 200 that are divisible by 7.

Solution:

/*…..number between 100-200 divisible by 7……*/

#include<stdio.h>
#include<conio.h>
void main()
{
int i,n,r,sum;
sum=0;
clrscr();
for(i=100;i<=200;i++)
{
r=i%7;
if(r==0)
{
printf(" %d",i);
sum=sum+i;
}
printf(“Sum=%d”,sum);
}
getch();
}
EXERCISE-5.3 A set of two linear equations with two unknowns x1 and x2 is given below:
ax1 +bx2=m and cx1+dx2=n
The set has unique solution
x1= and x2=
provided the determinate ad-cb is not equal to zero.
Write a program that will read the values of constants a,b,c,d,m and n and compute the values
of x1 and x2 .An appropriate message should be printed if ad-cb=0.

Solution:

/*…….two linear equation………*/

#include<stdio.h>
#include<conio.h>
void main()
{
float a,b,c,d,m,n,x1,x2;
clrscr();
printf("Input a,b,c,d,m,n:\n");
scanf("a=%f b=%f c=%f d=%f m=%f n=%f",&a,&b,&c,&d,&m,&n);
x1=(m*d-b*n)/(a*d-c*b);
x2=(n*a-m*c)/(a*d-c*b);
if((a*d-c*b)!=0)
printf("x1=%f x2= %f",x1,x2);
else
printf("The value is infinity.\n");
getch();
}
EXERCISE-5.4 Given a list of marks ranging from 0 to 100, write a program to print
number of students:
(a)Who have obtained more than 80 marks, (b) who have obtained more than 60 marks,
(c)Who have obtained more than 40 marks, (d) who have obtained 40 or less marks,
(e)In the range 81 to 100, (f) in the range 61 to 80,
(g)in the range 41 to 60, and (h) in the range 0 to 40.
The program should use a minimum numbers of if statements.
Solution:
/*….marks obtain……*/
#include<stdio.h>
#include<conio.h>
void main()
{
int marks,count,a,b,c,d,i;
a=0; b=0; c=0;d=0;
clrscr();
printf("Input 20 boy's marks\n");
for(i=1;i<=20;i++)
{
scanf("%d",&marks);
if(marks>80)
a++;
else if(marks>60)
b++;
else if(marks>40)
c++;
else if(marks<=40)
d++;
}
printf("Number of students who have obtained more than 80 marks=%d\nNumber
of

students who have obtained more than 60 marks=%d\n Number of students


who have obtained more than 40 marks=%d\n Number of students who have obtained 40 or
less marks=%d",a,b,c,d);
getch();
}

EXERCISE-5.5 Admission to a professional course is subjects to the following conditions:


(a) Marks in Mathematics>=60
(b) Marks in Physics>=50
(c) Marks in Chemistry>=40
(d) Total in all three subjects>=200 or
Total in Mathematics and Physics>=150
Given the marks in the three subjects, write a program to process the applications to list the
eligible candidates.

Solution:

/*……..admission for a professional course……*/

#include<stdio.h>
#include<conio.h>
void main()
{
int r,m,c,p,b;
clrscr();
printf("Input Mathmatics,Physics and Chemistry");
scanf("%d%d%d",&m,&p,&c);
r=m+p+c;
b=m+p;
if(m>=60&&p>=50&&c>=40&&r>=200&&b>=150)
printf("The candidate is eligible");
else
printf("The candidate is not eligible");
getch();
}
EXERCISE-5.7: Shown below is a Floyd’s triangle .
1
23
456
7 8 9 10
11………..15
79........ .. .. .. .. ..91

(a) Write a program to print this triangle.


Solution:

/*……….Floyd’s triangle………..*/

#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,count,n;
clrscr();
count=0;
printf("\n\nHow many rows of Floyd triangle: ");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(j=1;j<=i;j++)
{
count++;
printf("%d",count);
printf(" ");
}
printf("\n");
}
getch();
}

(b) Modify the program the following from of Floyd’s triangle.


1
01
101
0101
10101

Solution:

/*……….Floyd’s triangle………..*/

#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,count,n;
clrscr();
count=0;
printf("\n\nHow many rows of Floyd triangle: ");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(j=2;j<=i+1;j++)
{
printf("%d",(i+j)%2);
printf(" ");
}
printf("\n");
}
getch();
}
EXERCISE-5.8 A cloth showroom has announced the following seasonal discounts on
purchase of items:

Purchase amount Discount


Mill cloth Handloom items
0-100 5%
101-200 5% 7.5%
201-300 7.5% 10.0%
Above300 10.0% 15.0%
Write a program using switch and if statements to compute the net amount to be paid by a
coustomer.

Solution:

/*………….marketing of a showroom………………*/

#define MC1 0
#define MC2 0.05
#define MC3 0.075
#define MC4 0.10
#define HI1 0.05
#define HI2 0.075
#define HI3 0.10
#define HI4 0.15
#include<stdio.h>
#include<conio.h>
void main()
{
float price,net,discount;
int level,jobnumber;
clrscr();
input:
printf("Enter level jobnumber and purchase amount\n");
printf("Enter zero for level to End\n");
scanf("%d%d%f",&level,&jobnumber,&price);
if(level==0) goto stop;
if(0<=price<=100)
level=1;
else if(101<=price<=200)
level=2;
else if(201<=price<=300)
level=3;

else
level=4;
switch(level)
{
case 1:
discount=MC1+HI1;
break;
case 2:
discount=MC2+HI2;
break;
case 3:
discount=MC3+HI3;
break;
case 4:
discount=MC4+HI4;
break;
default:
printf("Error in level code\n");
goto stop;
}
net=price-(price*discount);
printf("Net amount=%f\n",net);
goto input;
stop:printf("\n\nEND OF THE PROGRAM");
getch();
}
EXERCISE-5.9 Write a program that will read the value of x and evaluate the following
function
y=
using
(a) nested if statements.
(b) else if statements and
(c) conditional operator ?

Solution:
/*…………evaluate the equation………..*/

(a)nested if statements:
#include<stdio.h>
#include<conio.h>
void main()
{
float x,y;
clrscr();
printf("Input x\n");
scanf("%f",&x);
if(x!=0)
{
if(x>0)
printf("y=1");
if(x<0)
printf("y=-1");
}
if(x==0)
printf("y=0");
getch();
}
(b)else if statements:
#include<stdio.h>
#include<conio.h>
void main()
{
float x,y;
clrscr();
printf("Input x\n");
scanf("%f",x);
if(x!=0)
{
if(x>0)
{
printf("1");
}
else
printf("-1");
}
else
printf("0");
getch();
}
(c)conditional operator:
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
float y,x;
printf("Input x\n");
scanf("%f",&x);
y=(x!=0)?((x>0)?1:-1):0;
printf("%d",y);
getch();
}
EXERCISE-5.10 Write a program to compute the real roots of a quadratic equation
ax2+bx2+c=0
The roots are given by the equtions:
x1 and x2
The program should request for the values of the constants a,b and c print the values of x1
and x2.Use the following:

(a) No solution, if both a and b are zero


(b) There is only one root if a=0(x=-c/b)
(c) There are no real roots, if b2-4ac is negative
(d) Otherwise, there no real roots
Test your program with appropriate data so that all logical paths are working as per your
design. Incorporate appropriate output messages.

Solution:

/*…….roots of quadratic equation ….*/

#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
float a,b,c,x,discriminant,root1,root2;
clrscr();
printf("Input values of a, b and c\n");
scanf("%f %f %f",&a,&b,&c);
discriminant=b*b-4*a*c;
if(a==0&&b==0)
printf("No solution\n");
else if(a==0)
{
x=-(c/b);
printf("x=%f",x);
}
else if(discriminant<0)
printf("Roots are imaginary\n");
else
{
root1=-b+sqrt(discriminant)/2*a;
root2=-b-sqrt(discriminant)/2*a;
printf("Root1=%f Root2=%f",root1,root2);
}
getch();
}

EXERCISE-5.11: Write a program to read three integer values from the keyboard and
displays the output stating that they are the sides of right-angled triangle.
Solution:
/*………………right-angled triangle……..*/

#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c,x,y,z;
clrscr();
printf("Input three integer values a b and c\n");
scanf("%d%d%d",&a,&b,&c);
x=a*a;
y=b*b;
z=c*c;
if(a>b&&a>c&&(x==y+z))
printf("The values are sides of right-angled triangle");
else if(b>a&&b>c&&(y==x+z))
printf("The values are sides of right-angled triangle");
else if(c>a&&c>b&&z==x+y)
printf("The values are sides of right-angled triangle");
else
printf("The values are not sides of right-angled triangle");
getch();
}
EXERCISE-5.12: An electricity board charges the following rates for the use of electricity:
For the first 200 units: 80 per unit
For the next 100 units: 90per unit
Beyond 300 units: Rs.1.00 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 names of users and number of units consumed and print out the charges with names.
Solution:
/*………….pay bill…………..*/

#include<stdio.h>
#include<conio.h>
void main()
{
float units,total,net;
char name;
clrscr();
printf("Input users name and units\n");
scanf("%s %f",&name,&units);
{
if(units<=200)
total=100+0.80*units;
else if(units<=300)
total=100+0.90*units;
else if(units>300)
total=100+1.00*units;
}
if(total>400)
{
net=total+total*0.15;
printf("Total=%f",net); }
else
printf("Total=%f",total);
getch();
}
EXERCISE-5.13: Write a program to compute and display the sum of all integers that are
divisible by 6 but not divisible by 4 and lie between 0 to 100. The program should also count
and display the number of such values.

Solution:

/*……numbers between 0-100 divisible by 6 but not divisible by 4….*/

#include<stdio.h>
#include<conio.h>
void main()
{
int i,count;
count=0;
clrscr();
for(i=0;i<=100;i++)
{
if(i%6==0&&i%4!=0)
{
count=count+1;
printf(" %d",i);
}
}
printf(“\n”);
printf("count=%d",count);
getch();
}
EXERCISE-5.14 Write an interactive program that could read a positive integer number and
decide whether the number is a prime number display the output accordingly. Modify the
program to count all prime numbers that lie 100 to 200. [Note: A prime number is positive
integer that is divisible only by 1 or by itself]
Solution:

/*………….prime number …………*/

#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,count;
count=0;
clrscr();
printf("\n\nSeries of prime number from 100 to 200:\n");
for(i=100;i<=200;i++)
{
for(j=2;j<=i;j++)
{
if(i%j==0)
break;
}
if(i==j)
{
printf("%4d\n",i);
count+=1;
}
}
printf("The countable number is: %d",count);
getch();
}
EXERCISE-5.15: Write a program read a double-type value x that represents angle in
radians and a character-type variable t that represents the type of trigonometric function and
display the value of
(a) sin(x), if s or S is a assigned to T,
(b) cos(x), if c or C is assigned to T, and
(c) tan(x), if t or T is assigned to T
Using (i) if…else statement and (ii) switch statement.
Solution-1:
(i)if…else statement :
/*……………trigonometric function……….*/
#include<stdio.h>
#include<conio.h>
#include<math.h>
#include<ctype.h>
void main()
{
int x,c,s,d,t; clrscr();
float r,result;

s=1;
c=2;
t=3;
printf(“Input the value of x and character value\n”);
scanf("%d",&x);
r=x*(180/3.1416);
scanf("%d",&d);
{
if(d==1)
result=sin(r);
else if(d==2)
result=cos(r);
else if(d==3)
result==tan(r);
else
printf("no response.");
}
printf("\n%f",result);
getch();
}
Solution-2:
(ii) switch statement:
/*………….trigonometric function…………..*/
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int i,x;
float v,r;
char t;
clrscr();
printf("Input the value of x\n");
scanf("%d",&x);

r=x*(180/3.1416);
printf("Input charecter");
scanf("%c",&t);
switch(t)
{
case 's':
case 'S':
v=sin(r);
case 'c':
case 'C':
v=cos(r);
case 't':
case 'T':
v=tan(r);
}
printf("%f",v);
getch();

}
Chapter-06
Decision making and
looping
REVIEW QUESTIONS
6.1 State whether the following statements are true or false:
(a) The do… while statement first executes the loop body and then evaluate the
loop control expression.
Ans: True.
(b) In a preset loop, if the body is executed n terms, the test expression is
executed n+1 times.
Ans: True.
(c) The number of times a control variable is updated always equals the
number of loop iterations.
Ans: True.
(d) Both the preset loops include initialization within the statement.
Ans: True.
(e) In a for loop expression, the starting value of the control variable must be less
than its ending value.
Ans: True.
(f) The initialization, test condition and increment parts may be missing in a for
statement.
Ans: False.
(g) While loops can be used to replace for loops without any change in the
body of the loop.
Ans: False.
(h) An exit control loop is executed a minimum of a one line.
Ans: False.
(i) The use of continue statement considered as unstructured programming.
Ans: True.
(j) The three loop expressions used in a for loop header must be separated by
commas.
Ans: True.
6.2: Fill in the blanks in the following statements.
(a) In an exit controlled loop, if body is executed n times, test condition is
evaluated
times.
Ans: (n-1)
(b) The statements is use to skip a part of the statements in a loop.
Ans: continue.
(c) A for loop with the no test condition is known as loop.
Ans: infinite
(d) The sentinel controlled loop is also; known as loop.
Ans: indefinite repetition.
(e)In a counter controlled loop, variable known as is used to count the
loop operation.
Ans: definite repetition.
6.8 explain the operation of each of the following for loops.
(a)for (n=1;n!=10;n+=2)
sum=sum+n;
Ans :The loop repeats 5 times.
(b)for(n=5;n<=m;n-=1)
sum+=n;
Ans: The continue until n<=m where m initializes from 5 and decrements by 1.
(c) for(n=1;n<=5)
sum+=n;
Ans: Since theren is no increment or decrement condition the loop repeats 5
times.
(d) for(n=1; ;n+=1)
sum+=n;
Ans: The loop repeats infinity times.
(e)for(n=1;n<5;n++)
n=n-1;
Ans: The loop repeats infinity times.
6.9: what would be the output of each of the following code segments?
(a)count=5;
while(count-- >0)
printf(“count”);
Output:
5 4 3 2 1
(b)count=5;
while(-- count>0)
Printf(“count”);
Output:
4 3 2 1
(c) count=5;
do printrf(“count”);
while(count>0)
Output:
5 4 3 2 1
(d)for(m=10;m>7;m-=2)
printf(“m”);
output;
10 8
6.11:Analyse each of the program segment that follow the determine how many times
the body of each loop will be executed.
(a)x=5;
y=50;
while(x<=y)
{
x=y/x;
…………………..
…………………..
}
Ans: Infinity times
(b) m=1;
do
{
……………………
……………………….
m+=2;
}
while(m<10)
Ans: 5 times.
(c) int i;
for(i=0;i<=5;i=i+2/3)
{
…………………..
…………………….
}
Ans: Infinity times.
(d) int m=10;
Int n=7;
while(m%n>=0)
{
………………
m+=1;
n+=2;
…………….
}
Ans: 4 times.
6.12: Find errors, if any, in each of the following looping segments. Assume that all
the variables have been declared and assigned values.
(a)while(count!=10);
{
count=1;
sum+=x;
count+=1;
}
Error: while(count!=10);
Correct Ans: while(count!=10)

(b) name=0;
do
{
name+=1;
printf(“my name is Dinar\n”);
while(name=1);
Error: while (name=1);
Correct Ans: while(name==1);
(c) do;
total+=value;
scanf(“%f”,&value);
while(value!=999);
Error: do;
Correct Ans: do
(E) m=1;
n=0;
for(p=10;p>0;)
p-=1;
printf(“%f”,p);
Error: for(p=10;p>0;)
p-=1;
printf(“%f”,p);
Correct ans: for(p=10;p>0;)
{
p-=1;
printf(“%f”,p);
}
6.13:Write a for statement to pront each of the following sequence of integers:
(a) 1,2,4,8,16,32
Ans: for(i=1;i<=32;i=i*2)
printf(“%d”,i);
(b) 1,3,9,27,81,243
Ans: for(i=1;i<=243;i=i*i)
printf(“%d”,i);
(c) -4,-2,0,4
for(i=-4;i<=4;i=i+2)
printf(“%d”,i);
(d) -10,-12,-14,-18,-26,-42
for(i=-10;i<=-42;i=i-2)
printf(“%d”,i);
6.14: Change the following for loops to while loops :
(a)for(m=1;m<10;m=m+1)
printf(“m”);
Ans: m=1;
while(m<10)
{
…………….
m++;
}
printf(“m”);
(b)for(;scanf(“%d”,&m)!=-1;)
printf(“m”);
Ans:
while(scanf(“%d”,&m)!=-1)
printf(“m”);

6.16: What is the output of following code?


Int m=100,n=0;
while(n==0)
{

if(m<10)
break;
m=m-10;
}
Output: No output
6.17: What is output of the following code?
int m=0;
do
{
if(m>10)
continue;
m=m+10;
}
while(m<50);
printf(“%d”,m);
Output: 50
6.18: What is the output of the following code?
int n=0,m=1;
do
{
printf(“m”);
m++;
}
while(m<=n);
Output: 1
6.19: What is the output of the following code?
int n=0,m;
for(m=1;m<=n+1;m++)
printrf(“m”);
Output: 1
6.20: When do we use the following statement?
for(; ;)
Ans : When we need an infinity loop the statement for(; ;) can be used.
CHAPTER-7
By Tanvir on January 15, 2013
4 Votes

7.1 Write a program for fitting a straight line through a set of points (xi,

yi),i=1,2,3….n. The straight line equation is:

Y =mx+c

and the values of m and c are given by:

m=((n ∑(xi,yi))- (∑xi)(∑yi) )/( n(∑xi2)-(∑xi)2)

c=1/n(∑yi -m(∑xi))

All summations are from 1 to n.

Answer:

#include

#include

void main()

int i,n=10,v1,v2,x[10],y[10];

int total_x,total_y,total_xy,total_x2;

float m,c,temp,temp1;

clrscr();

printf(“Enter the values for x: “);


for(i=0;i<10;i++)

scanf(“%d”,&v1);

x[i]=v1;

printf(“Enter the values for y: “);

for(i=0;i<10;i++)

scanf(“%d”,&v2);

y[i]=v2;

total_x=total_y=total_xy=total_x2=0;

for(i=0;i<10;i++)

total_x=total_x+x[i];

total_y=total_y+y[i];

total_xy=total_xy+(x[i]*y[i]);

total_x2=total_x2+(x[i]*x[i]);

}
temp= total_x*total_y;

temp1=total_x*total_x;

m=((n*total_xy)-(temp))/((n*total_x2)-temp1);

c=((total_y)-(m*total_x))/n;

printf(” \nThe equation of the straight line is: “);

printf(” Y=%fX+%f”,m,c);

getch();

Output

Enter the values for x:

1 2 3 4 5 6 7 8 9 10

Enter the values for y:

1 2 3 4 5 6 7 8 9 10

The equation of the straight line is:

Y=1.00000X+0.000000

7.2 The daily maximum temperature recorded in 10 cities during the month of
January (for all 31 days) have been tabulated as follows:

City

1 2 3 4 5 6 ……………………………10

Day
1

31

7.2. Write a program to read the table elements into a two-dimensional array
temperature, and to find the city and day corresponding to

a) the highest temperature

b) the lowest temperature

Answer:

//Write a program to read the table elements into a two-dimensional array


temperature, and to find the city and day corresponding to

//a) the highest temperature

//b) the lowest temperature

// Date : 16/03/2010

#include

#include
void main()

int Temp[2][2];

int i,j,City1,City2,MaxTemp,MinTemp;

clrscr();

printf(“Enter temperature:–\n\n”);

for(i=0;i<2;i++) { printf(“For City %d ->\n”,i);

for(j=0;j<2;j++) { printf(“For Day %d ->”,j);

scanf(“%d”,&Temp[i][j]);

clrscr();

printf(“Temperature Matix :— \n”);

printf(” City \n “);

for(i=0;i<2;i++)

printf(“%d “,i+1);

printf(“\n Day\n”);

for(i=0;i<2;i++)

{
printf(” %d “,i+1);

for(j=0;j<2;j++)

printf(” %d”,Temp[i][j]);

printf(“\n”);

MinTemp=MaxTemp=Temp[0][0];

City1=0;

City2=0;

for(i=0;i<2;i++)

for(j=0;j<2;j++)

if(MaxTemp<Temp[i][j]) { MaxTemp=Temp[i][j]; City1=j+1; }


if(MinTemp>Temp[i][j])

MinTemp=Temp[i][j];

City2=j+1;

}
}

printf(“\n\nHighest Temperature of City %d is %d\n”,City1,MaxTemp);

printf(“Lowest Temperature of City %d is %d\n”,City2,MinTemp);

getch();

7.3 An election is contested by 5 candidates. The candidate are numbered are


1 to 5

and the voting is done by marking the candidate number on the ballot paper.
Write

a program to read the ballots and count the votes cast for each candidate
using an

array variable count. In case, a number, read is outside the range 1 to 5,the
ballot

should be considered as a ‘spoilt ballot’ and the program should also count
the

number of spoilt ballots.

Program:–

/* An election is contested by 5 candidates.


The candidate are numbered are 1 to 5 and the voting is done by marking the
candidate number on the ballot paper. Write a program to read the ballots and
count the votes cast for each candidate using an array variable count. In case, a
number, read is outside the range 1 to 5,the ballot should be considered as a ‘spoilt
ballot’ and the program should also count the number of spoilt ballots. */

// Date March 16,2010

#include

#include

void main()

int i,vote[5],c1=0,c2=0,c3=0,c4=0,c5=0,count=0,count_sp=0,v;

clrscr();

printf(“Enter your votes for 5 candidates:”);

for(i=1;i<=5;i++)

scanf(“%d”,&v);

vote[i]=v;

for(i=1;i<=5;i++)

if(vote[i]==1)
c1=c1+1;

else

if(vote[i]==2)

c2=c2+1;

else

if(vote[i]==3)

c3=c3+1;

else

if(vote[i]==4)

c4=c4+1;

else

if(vote[i]==5)

c5=c5+1;

}
}

printf(” votes to candidate1=%d”,c1);

printf(” \nvotes to candidate2=%d”,c2);

printf(“\n votes to candidate3=%d”,c3);

printf(” \nvotes to candidate4=%d”,c4);

printf(” \nvotes to candidate5=%d”,c5);

for(i=1;i<=5;i++)

if(vote[i]<=5)

count=count+1;

else

count_sp=count_sp+1;

printf(” The number of valid votes is:%d”,count);

printf(” \nThe number of spoilt votes is:%d”,count_sp);

getch();

Output

Enter your votes for 5 candidates:


1

Votes to Candidate 1: 2

Votes to Candidate 2: 1

Votes to Candidate 3:1

Votes to Candidate 4:0

Votes to Candidate 5:0

The number of valid votes is: 4

The number of spoilt votes is: 1

7.51 The annual examination results of 10 students are tabulated as follows:

Roll No. Subject1 Subject2 Subject3

.__________________________________________________________________
__

Write a program to read the data and determine the following:


(a) Total marks obtained by each student.

(b) The highest marks in each subject and the Roll No. of the student who
secured it.

(c) The student who obtained the highest total marks.

Program:–

/* The annual examination results of 10 students are tabulated as follows:

Roll No. Subject1 Subject2 Subject3

Write a program to read the data and determine the following:

(a) Total marks obtained by each student.

(b) The highest marks in each subject and the Roll No. of the student who secured
it.

(c) The student who obtained the highest total marks.

*/

// Date March 16,2010

#include
#include

#define MAX 10

void main()

int i,roll,m1,m2,m3,sub1[MAX],sub2[MAX],sub3[MAX];

int total_sub1,total_sub2,total_sub3,total[MAX];

int max,max1,max2,max3,roll1,roll2,roll3;

clrscr();

printf(“Enter the marks for subject1 of all the students: “);

for(i=0;i<MAX;i++)

scanf(“%d”,&sub1[i]);

printf(“Enter the marks for subject2 of all the students: “);

for(i=0;i<MAX;i++)

scanf(“%d”,&sub2[i]);

printf(“Enter the marks for subject3 of all the students: “);

for(i=0;i<MAX;i++)

scanf(“%d”,&sub3[i]);

total_sub1=total_sub2=total_sub3=0;

for(i=0;i<MAX;i++)
{

total_sub1=total_sub1+sub1[i];

total_sub2=total_sub2+sub2[i];

total_sub3=total_sub3+sub3[i];

total[i]=sub1[i]+sub2[i]+sub3[i];

for(i=0;i<MAX;i++)

printf(“The total marks obtained by the student%d is =%d\n”,i+1,total[i]);

max1=sub1[0];

max2=sub2[0];

max3=sub3[0];

max=total[0];

roll1=0;

roll2=0;

roll3=0;

roll=0;

for (i=0;i<MAX;i++)
{

if(max1<sub1[i])

max1=sub1[i];

roll1=i+1;

if(max2<sub2[i])

max2=sub2[i];

roll2=i+1;

if(max3<sub3[i])

max3=sub3[i];

roll3=i+1;

if(max<total[i])

max=total[i];
roll=i+1;

printf(“\nThe highest marks in subject1 is %d and the roll number is


%d”,max1,roll1);

printf(“\nThe highest marks in subject2 is %d and the roll number is


%d”,max2,roll2);

printf(“\nThe highest marks in subject3 is %d and the roll number is


%d”,max3,roll3);

printf(“\n The highest total marks is %d and the roll number is %d “,max,roll);

getch();

7.6 Given are one dimensional arrays A and B which are sorted in ascending

order. Write a program to merge them into a single sorted array C that
contains

every item form array A and B, in ascending order.

Program:–
// Given are one dimensional arrays A and B which are sorted in ascending

// order. Write a program to merge them into a single sorted array C that contains

// every item form array A and B, in ascending order.

//Date: 16/03/2010

#include

#include

#define MAX 50

void main()

int a[MAX],b[MAX],c[MAX];

int ax,bx,cx,n,m,mn;

clrscr();

ax=bx=cx=0;

printf(“Enter no. of elements of array : “);

scanf(“%d %d”,&n,&m);

printf(“Enter elements of first array :\n”);

for(i=0;i<n;i++)

scanf(“%d”,&a[i]);

printf(“Enter elements of Second array :”);


for(i=0;i<m;i++)

scanf(“%d”,&b[i]);

mn=m+n;

while(ax
{

if(a[ax]<b[bx])

c[cx]=a[ax];

ax++;

else

c[cx]=b[bx];

bx++;

cx++;

if(ax==n)

while(bx<m)
{

c[cx]=b[bx];

bx++;

cx++;

else

while(ax<n)

c[cx]=a[ax];

ax++;

cx++;

//sorted array

printf(“the sorted array is : \n”);

for(i=0;i<mn;i++)

printf(“%d “,c[i]);
getch();

7.7 Write a program that will read the values of elements of A and B and
produce the

product matrix C.

Program:–

// Write a program that will read the values of elements of A and B and produce the

// product matrix C.

//Date: 16/03/2010

#include

#include

#define MAX 10

void main()

int a[MAX][MAX],b[MAX][MAX],c[MAX][MAX];

int i,j,k,row,col;

clrscr();
printf(“Enter row of matrix”);

scanf(“%d”,&row);

printf(“Enter column of matrix”);

scanf(“%d”,&col);

printf(“Enter first matrix\n”);

for(i=0;i<row;i++)

for(j=0;j<col;j++)
scanf(“%d”,&a[i][j]);

printf(“\nEnter second matrix \n”);

for(i=0;i<row;i++)

for(j=0;j<col;j++)
scanf(“%d”,&b[i][j]);

printf(“\nFirst matrix is : \n”);

for(i=0;i<row;i++)

for(j=0;j<col;j++)
printf(“%d “,a[i][j]);

printf(“\n”);

printf(“\nSecond matrix is\n”);

for(i=0;i<row;i++)
{

for(j=0;j<col;j++)
printf(“%d “,b[i][j]);

printf(“\n”);

for(i=0;i<row;i++)

for(j=0;j<col;j++)
{ c[i][j]=0;

for(k=0;k<col;k++)
c[i][j]=c[i][j]+(a[i][k]*b[k][j]);

printf(“\nMultiplication is\n”);

for(i=0;i<row;i++)

for(j=0;j<col;j++)
printf(“%d “,c[i][j]);

printf(“\n”);

getch();

}
7.8 Write a program that fills a five-by-five as follows:

• Upper left triangle with +1s

• Lower right triangle with -1s

• Right to left diagonal with zeros

Display the contents of the matrix using not more than two printf statements.

Program:–

//Write a program that fills a five-by-five as follows:

//• Upper left triangle with +1s

//• Lower right triangle with -1s

//• Right to left diagonal with zeros

//Display the contents of the matrix using not more than two printf statements.

// Date : 16/03/2010

#include

#include

void main()
{

int A[5][5];

int a,i,k,j;

clrscr();

a=3;

for(i=0;i<=3;i++)

for(j=0;j<=a;j++)

A[i][j]=+1;

a–;

j=4;

for(i=0;i<=4;i++)

A[i][j]=0;

j–;

}
a=4;

for(i=1;i<=4;i++) { for(j=4;j>=a;j–)

A[i][j]=-1;

a–;

printf(“Array is:–\n\n”);

for(i=0;i<=4;i++)

for(j=0;j<=4;j++) printf(“%d “,A[i][j]); printf(“\n”); } getch(); } 7.9 Write a


program to implement selection sort. Algorithm:– Step 1: Read Array A. Step 2:
For k=0 to 9 repeat Step 3 to Step 8. Step 3: Compute Small=A[k] & Loc=k. Step
4: For i=0 to 9 repeat Step 5 to Step 7 otherwise go to Step 7. Step 5: Check
Small>A[i] then go to Step 6 otherwise go to Step 4.

Step 6: Compute Small=A[i] & Loc=i.

Step 7: Compute A[Loc]=A[k], A[k]=Small.

Step 8: Display Sorted Array A.

Flowchart:–

Program:–

//Write a program to implement selection sort.


// Date : 16/03/2010

#include

#include

void main()

int A[10];

int i,k,Small,Loc;

clrscr();

printf(“Enter Elements of Array:—\n”);

for(i=0;i<=9;i++)

scanf(“%d”,&A[i]);

for(k=0;k<=9;k++)

Small=A[k];

Loc=k;

for(i=k;i<=9;i++) if(Small>A[i])

Small=A[i];

Loc=i;
}

A[Loc]=A[k];

A[k]=Small;

printf(“Sorted Array is:–\n\n”);

for(i=0;i<=9;i++)

printf(“%d “,A[i]);

getch();

7.10 Write a program to implement Binary Search algorithm.

Program:–

//Write a program to implement Binary Search algorithm.

// Date : 16/03/2010

#include

#include

void main()
{

int Str[10];

int i,Beg,End,Mid,Item;

clrscr();

Beg=0;

End=9;

Mid=(Beg+End)/2;

printf(“Enetr Any Sorted Array:–\n”);

for(i=0;i<10;i++)

scanf(“%d”,&Str[i]);

printf(“Enter Item Which U want to Search:–\n”);

scanf(“%d”,&Item);

while((Item!=Str[Mid])&&(Beg<=End))

if(Item<Str[Mid]) End=Mid-1; else Beg=Mid+1; Mid=(Beg+End)/2; }


if(Beg>End)

printf(“Item Not Found\n”);

else

printf(“%d Found At Index %d\n”,Item,Mid);

getch();
}

7.11 Write a program that will compute the length of a given character string.

Program:–

//Write a program that will compute the length of a given character string.

// Date : 16/03/2010

#include

#include

void main()

char Str[50];

int i,Len;

clrscr();

Len=0;

printf(“Enter a String:—\n”);

scanf(“%[^\n]s”,&Str);

for(i=0;Str[i]!=”;i++)
Len=Len+1;

printf(“Length of String is %d”,Len);

getch();

7.12 Write a program that will count the number occurrences of a specified
character in a

given line of text.

Program:–

//Write a program that will count the number occurrences of a specified character
in a

// given line of text.

// Date : 16/03/2010

#include

#include

void main()

char Str[50],CheckChar;
int i,Count,Len;

clrscr();

Count=0;

printf(“Enter a String:—\n”);

scanf(“%[^\n]s”,&Str);

Len=strlen(Str);

fflush(stdin);

printf(“Enter a charatcer:–\n”);

scanf(“%c”,&CheckChar);

for(i=0;i<=Len;i++)

if(CheckChar==Str[i])

Count=Count+1;

printf(“Number of occurences of %c is %d”,CheckChar,Count);

getch();

7.13 Write a program to read a matrix of size m*n and print its transpose.
Program:–

//Write a program to read a matrix of size m*n and print its transpose.

// Date : 16/03/2010

#include

#include

#define MAX 10

void main()

int A[MAX][MAX],C[MAX][MAX];

int Row,Col,i,j;

clrscr();

printf(“Enter Number of Rows:–\n”);

scanf(“%d”,&Row);

printf(“Enter Number of Column:–\n”);

scanf(“%d”,&Col);

printf(“Enter Matrix:—\n”);

for(i=0;i<Row;i++)

for(j=0;j<Col;j++)
scanf(“%d”,&A[i][j]);
clrscr();

printf(“Matrix:—\n”);

for(i=0;i<Row;i++)

for(j=0;j<Col;j++)
printf(“%d “,A[i][j]);

printf(“\n”);

for(i=0;i<Col;i++)
for(j=0;j<Row;j++)

C[i][j]=A[j][i];

printf(“Transpose of Matrix:—\n”);

for(i=0;i<Col;i++)
{

for(j=0;j<Row;j++)

printf(“%d “,C[i][j]);

printf(“\n”);

getch();

}
7.3 An election is contested by 5 candidates. The candidate are numbered are
1 to 5

and the voting is done by marking the candidate number on the ballot
paper. Write

a program to read the ballots and count the votes cast for each candidate
using an

array variable count. In case, a number, read is outside the range 1 to


5,the ballot

should be considered as a ‘spoilt ballot’ and the program should also count
the

number of spoilt ballots.

Algorithm:–

Step1. Initialize c1,c2, c3,c4,c5,count,count_sp with 0.

Step2. For i=0 to i=5, repeat step3.


Step3. Enter the value of v and store in vote[i]

Step4. For i=0 to i=5, repeat from step5 till step14 and for i>5,go to step15.

Step5. Check if vote[i]==1,if true, go to step6,if false go to step7.

Step6.Calculate c1=c1+1

Step7. Check if vote[i]==2,if true, go to step8,if false go to step9.

Step8.Calculate c2=c2+2

Step9.Check if vote[i]==3,if true, go to step10,if false go to step11.

Step10. Calculate c3=c3+2

Step 11.Check if vote[i]==4,if true, go to step12,if false go to step13.

Step12.Calculate c4=c4+2

Step13.Check if vote[i]==5,if true, go to step14,if false go to step15.

Step14.Calculate c5=c5+2

Step15. Display c1,c2,c3,c4 and c5.

Step16. For i=0 to i=5, repeat from step 17 to step, and i>5,go to step 20

Step17.Check if vote[i]<5,if true go to step18 and if false, go to step 19.

Step18.count=count+1 and go to step 20.

Step19.count_sp=count_sp+1 and go to step 20.

Step20. Display count and count_sp

Step21. Stop.
Flowchart:–

Program:–

/* An election is contested by 5 candidates.

The candidate are numbered are 1 to 5 and the voting is done by marking the
candidate number on the ballot paper. Write a program to read the ballots and
count the votes cast for each candidate using an array variable count. In case, a
number, read is outside the range 1 to 5,the ballot should be considered as a ‘spoilt
ballot’ and the program should also count the number of spoilt ballots. */

// Date March 16,2010

#include<stdio.h>

#include<conio.h>

void main()

int i,vote[5],c1=0,c2=0,c3=0,c4=0,c5=0,count=0,count_sp=0,v;

clrscr();

printf(“Enter your votes for 5 candidates:”);

for(i=1;i<=5;i++)

scanf(“%d”,&v);
vote[i]=v;

for(i=1;i<=5;i++)

if(vote[i]==1)

c1=c1+1;

else

if(vote[i]==2)

c2=c2+1;

else

if(vote[i]==3)

c3=c3+1;

else

if(vote[i]==4)

c4=c4+1;

else
if(vote[i]==5)

c5=c5+1;

printf(” votes to candidate1=%d”,c1);

printf(” \nvotes to candidate2=%d”,c2);

printf(“\n votes to candidate3=%d”,c3);

printf(” \nvotes to candidate4=%d”,c4);

printf(” \nvotes to candidate5=%d”,c5);

for(i=1;i<=5;i++)

if(vote[i]<=5)

count=count+1;

else

count_sp=count_sp+1;

printf(” The number of valid votes is:%d”,count);


printf(” \nThe number of spoilt votes is:%d”,count_sp);

getch();

Output

Enter your votes for 5 candidates:

Votes to Candidate 1: 2

Votes to Candidate 2: 1

Votes to Candidate 3:1

Votes to Candidate 4:0

Votes to Candidate 5:0

The number of valid votes is: 4

The number of spoilt votes is: 1

5.1 The annual examination results of 10 students are tabulated as follows:


Roll No. Subject1 Subject2 Subject3

.__________________________________________________________________
__

Write a program to read the data and determine the following:

(a) Total marks obtained by each student.

(b) The highest marks in each subject and the Roll No. of the student who
secured it.

(c) The student who obtained the highest total marks.

Algorithm:–

Step1. Declare

Step2. For i=0 to i<10, Enter sub1[i]

Step3. For i=0 to i<10, Enter sub2[i]

Step4. For i=0 to i<10, Enter sub3[i]


Program:–

/* The annual examination results of 10 students are tabulated as follows:

Roll No. Subject1 Subject2 Subject3

.
Write a program to read the data and determine the following:

(a) Total marks obtained by each student.

(b) The highest marks in each subject and the Roll No. of the student who
secured it.

(c) The student who obtained the highest total marks.

*/

// Date March 16,2010

#include<stdio.h>

#include<conio.h>

#define MAX 10

void main()

int i,roll,m1,m2,m3,sub1[MAX],sub2[MAX],sub3[MAX];

int total_sub1,total_sub2,total_sub3,total[MAX];

int max,max1,max2,max3,roll1,roll2,roll3;

clrscr();

printf(“Enter the marks for subject1 of all the students: “);

for(i=0;i<MAX;i++)

scanf(“%d”,&sub1[i]);

printf(“Enter the marks for subject2 of all the students: “);


for(i=0;i<MAX;i++)

scanf(“%d”,&sub2[i]);

printf(“Enter the marks for subject3 of all the students: “);

for(i=0;i<MAX;i++)

scanf(“%d”,&sub3[i]);

total_sub1=total_sub2=total_sub3=0;

for(i=0;i<MAX;i++)

total_sub1=total_sub1+sub1[i];

total_sub2=total_sub2+sub2[i];

total_sub3=total_sub3+sub3[i];

total[i]=sub1[i]+sub2[i]+sub3[i];

for(i=0;i<MAX;i++)

printf(“The total marks obtained by the student%d is =%d\n”,i+1,total[i]);

max1=sub1[0];

max2=sub2[0];
max3=sub3[0];

max=total[0];

roll1=0;

roll2=0;

roll3=0;

roll=0;

for (i=0;i<MAX;i++)

if(max1<sub1[i])

max1=sub1[i];

roll1=i+1;

if(max2<sub2[i])

max2=sub2[i];

roll2=i+1;

if(max3<sub3[i])
{

max3=sub3[i];

roll3=i+1;

if(max<total[i])

max=total[i];

roll=i+1;

printf(“\nThe highest marks in subject1 is %d and the roll number is


%d”,max1,roll1);

printf(“\nThe highest marks in subject2 is %d and the roll number is


%d”,max2,roll2);

printf(“\nThe highest marks in subject3 is %d and the roll number is


%d”,max3,roll3);

printf(“\n The highest total marks is %d and the roll number is %d “,max,roll);

getch();

7.6 Given are one dimensional arrays A and B which are sorted in ascending
order. Write a program to merge them into a single sorted array C that
contains

every item form array A and B, in ascending order.

Algorithm:–

Step 1: Read m, n, Array a & Array b.

Step 2: Store 0 to ax, bx and cx.

Step 3: Compute mn=m+n

Step 4: Repeat Step 5 to Step 8 while ax<n && bx<m otherwise go to Step 9

Step 5: Check a[ax]<b[bx] then go to Step 6 otherwise go to Step 7

Step 6: Compute c[cx]=a[ax], ax=ax+1

Step 7: Compute c[cx]=b[bx], bx=bx+1

Step 8: Compute cx=cx+1

Step 9: Check ax==n then go to Step 10 otherwise go to Step 12

Step 10: Repeat Step 11 while bx<m


Step 11: Compute c[cx]=b[bx], bx=bx+1, cx=cx+1.

Step 12: Repeat Step 13 while ax<n

Step 13: Compute c[cx]=a[ax], ax=ax+1, cx=cx+1.

Step 14: Display Sorted Array c.

Flowchart:–

Program:–

// Given are one dimensional arrays A and B which are sorted in ascending

// order. Write a program to merge them into a single sorted array C that
contains

// every item form array A and B, in ascending order.

//Date: 16/03/2010

#include<stdio.h>

#include<conio.h>

#define MAX 50

void main()

{
int a[MAX],b[MAX],c[MAX];

int ax,bx,cx,n,m,mn;

clrscr();

ax=bx=cx=0;

printf(“Enter no. of elements of array : “);

scanf(“%d %d”,&n,&m);

printf(“Enter elements of first array :\n”);

for(i=0;i<n;i++)

scanf(“%d”,&a[i]);

printf(“Enter elements of Second array :”);

for(i=0;i<m;i++)

scanf(“%d”,&b[i]);

mn=m+n;

while(ax<n && bx<m)

if(a[ax]<b[bx])

c[cx]=a[ax];

ax++;
}

else

c[cx]=b[bx];

bx++;

cx++;

if(ax==n)

while(bx<m)

c[cx]=b[bx];

bx++;

cx++;

else

{
while(ax<n)

c[cx]=a[ax];

ax++;

cx++;

//sorted array

printf(“the sorted array is : \n”);

for(i=0;i<mn;i++)

printf(“%d “,c[i]);

getch();

7.7 Write a program that will read the values of elements of A and B and
produce the

product matrix C.

Algorithm:–
Step 1: Read row, col, Array a and Array b.

Step 2: Display Array a and b.

Step 3: For i=0 to row repeat Step 4 to Step 7

Step 4: For j=0 to col repeat Step 5 to Step 7

Step 5: Store 0 to c[i][j]

Step 6: For k=0 to col repeat Step 7

Step 7: Compute c[i][j]=c[i][j]+(a[i][k]*b[k][j])

Step 8: Display c.

Flowchart:–
Program:–

// Write a program that will read the values of elements of A and B and produce the

// product matrix C.
//Date: 16/03/2010

#include<stdio.h>

#include<conio.h>

#define MAX 10

void main()

int a[MAX][MAX],b[MAX][MAX],c[MAX][MAX];

int i,j,k,row,col;

clrscr();

printf(“Enter row of matrix”);

scanf(“%d”,&row);

printf(“Enter column of matrix”);

scanf(“%d”,&col);

printf(“Enter first matrix\n”);

for(i=0;i<row;i++)

for(j=0;j<col;j++)

scanf(“%d”,&a[i][j]);

printf(“\nEnter second matrix \n”);

for(i=0;i<row;i++)
for(j=0;j<col;j++)

scanf(“%d”,&b[i][j]);

printf(“\nFirst matrix is : \n”);

for(i=0;i<row;i++)

for(j=0;j<col;j++)

printf(“%d “,a[i][j]);

printf(“\n”);

printf(“\nSecond matrix is\n”);

for(i=0;i<row;i++)

for(j=0;j<col;j++)

printf(“%d “,b[i][j]);

printf(“\n”);

for(i=0;i<row;i++)

for(j=0;j<col;j++)

{ c[i][j]=0;
for(k=0;k<col;k++)

c[i][j]=c[i][j]+(a[i][k]*b[k][j]);

printf(“\nMultiplication is\n”);

for(i=0;i<row;i++)

for(j=0;j<col;j++)

printf(“%d “,c[i][j]);

printf(“\n”);

getch();

7.8 Write a program that fills a five-by-five as follows:

 Upper left triangle with +1s


 Lower right triangle with -1s
 Right to left diagonal with zeros

Display the contents of the matrix using not more than two printf
statements.

Algorithm:–

Step 1: Store Upper left triangle with +1s

Step 2: Store Lower right triangle with -1s

Step 3: Store Right to left diagonal with zeros

Step 4: Display A
Flowchart:–
Program:–

//Write a program that fills a five-by-five as follows:

//• Upper left triangle with +1s

//• Lower right triangle with -1s

//• Right to left diagonal with zeros

//Display the contents of the matrix using not more than two printf statements.
// Date : 16/03/2010

#include<stdio.h>

#include<conio.h>

void main()

int A[5][5];

int a,i,k,j;

clrscr();

a=3;

for(i=0;i<=3;i++)

for(j=0;j<=a;j++)

A[i][j]=+1;

a–;

j=4;

for(i=0;i<=4;i++)
{

A[i][j]=0;

j–;

a=4;

for(i=1;i<=4;i++)

for(j=4;j>=a;j–)

A[i][j]=-1;

a–;

printf(“Array is:–\n\n”);

for(i=0;i<=4;i++)

for(j=0;j<=4;j++)

printf(“%d “,A[i][j]);

printf(“\n”);
}

getch();

7.9 Write a program to implement selection sort.

Algorithm:–

Step 1: Read Array A.

Step 2: For k=0 to 9 repeat Step 3 to Step 8.

Step 3: Compute Small=A[k] & Loc=k.

Step 4: For i=0 to 9 repeat Step 5 to Step 7 otherwise go to Step 7.

Step 5: Check Small>A[i] then go to Step 6 otherwise go to Step 4.

Step 6: Compute Small=A[i] & Loc=i.

Step 7: Compute A[Loc]=A[k], A[k]=Small.

Step 8: Display Sorted Array A.


Flowchart:–
Program:–

//Write a program to implement selection sort.

// Date : 16/03/2010

#include<stdio.h>

#include<conio.h>

void main()

int A[10];

int i,k,Small,Loc;

clrscr();

printf(“Enter Elements of Array:—\n”);


for(i=0;i<=9;i++)

scanf(“%d”,&A[i]);

for(k=0;k<=9;k++)

Small=A[k];

Loc=k;

for(i=k;i<=9;i++)

if(Small>A[i])

Small=A[i];

Loc=i;

A[Loc]=A[k];

A[k]=Small;

printf(“Sorted Array is:–\n\n”);

for(i=0;i<=9;i++)

printf(“%d “,A[i]);

getch();
}

7.10 Write a program to implement Binary Search algorithm.

Algorithm:–

Step 1: Store 0 to Beg & 9 to End.

Step 2: Compute Mid=(Beg+End)/2.

Step 3: Read a Sorted Array Str & an Item to Search.

Step 4: Repeat Step 5 to Step 8 while Item!=Str[Mid])&&(Beg<=End) otherwise


go to Step 9

Step 5: Check Item<Str[Mid] then go to Step 6 otherwise go to Step 7

Step 6: Compute End=Mid-1

Step 7: Compute Beg=Mid+1

Step 8: Compute Mid=(Beg+End)/2

Step 9: Check Beg>End go to Step 10 otherwise go to Step 11

Step 10: Display “Item Not Found”

Step 11: Display “Item Found”

Flowchart:–
Program:–

//Write a program to implement Binary Search algorithm.

// Date : 16/03/2010

#include<stdio.h>

#include<conio.h>

void main()

{
int Str[10];

int i,Beg,End,Mid,Item;

clrscr();

Beg=0;

End=9;

Mid=(Beg+End)/2;

printf(“Enetr Any Sorted Array:–\n”);

for(i=0;i<10;i++)

scanf(“%d”,&Str[i]);

printf(“Enter Item Which U want to Search:–\n”);

scanf(“%d”,&Item);

while((Item!=Str[Mid])&&(Beg<=End))

if(Item<Str[Mid])

End=Mid-1;

else

Beg=Mid+1;

Mid=(Beg+End)/2;

}
if(Beg>End)

printf(“Item Not Found\n”);

else

printf(“%d Found At Index %d\n”,Item,Mid);

getch();

7.11 Write a program that will compute the length of a given character string.

Algorithm:–

Step 1: Read a string Str.

Step 2: For i=0 to End of String repeat Step 3 to Step

Step 3: Compute Len=Len+1

Step 4: Display Len.

Flowchart:–
Program:–

//Write a program that will compute the length of a given character string.

// Date : 16/03/2010

#include<stdio.h>

#include<conio.h>

void main()

char Str[50];

int i,Len;

clrscr();

Len=0;

printf(“Enter a String:—\n”);

scanf(“%[^\n]s”,&Str);

for(i=0;Str[i]!=”;i++)

Len=Len+1;

printf(“Length of String is %d”,Len);

getch();
}

7.12 Write a program that will count the number occurrences of a specified
character in a

given line of text.

Algorithm:–

Step 1: Read a string Str & a Character CheckChar

Step 2: Length of String is Len

Step 3: For i=0 to Len repeat Step 4 to Step 5

Step 4: Check CheckChar==Str[i] go to Step 5 otherwise go to Step 3

Step 5: Count=Count+1

Step 6: Display Count


Flowchart:–
Program:–

//Write a program that will count the number occurrences of a specified character
in a

// given line of text.

// Date : 16/03/2010

#include<stdio.h>

#include<conio.h>

void main()

char Str[50],CheckChar;

int i,Count,Len;

clrscr();
Count=0;

printf(“Enter a String:—\n”);

scanf(“%[^\n]s”,&Str);

Len=strlen(Str);

fflush(stdin);

printf(“Enter a charatcer:–\n”);

scanf(“%c”,&CheckChar);

for(i=0;i<=Len;i++)

if(CheckChar==Str[i])

Count=Count+1;

printf(“Number of occurences of %c is %d”,CheckChar,Count);

getch();

7.13 Write a program to read a matrix of size m*n and print its transpose.
Algorithm:–

Step 1: Read Row, Col & Matrix A

Step 2: Display A

Step 3: For i=0 to Col repeat Step 4 to Step 5 otherwise go to Step 6

Step 4: For j=0 to Row repeat Step 5 otherwise go to Step 3

Step 5: Compute C[i][j]=A[j][i]

Step 6: Display C
Flowchart:–
Program:–

//Write a program to read a matrix of size m*n and print its transpose.

// Date : 16/03/2010

#include<stdio.h>

#include<conio.h>

#define MAX 10
void main()

int A[MAX][MAX],C[MAX][MAX];

int Row,Col,i,j;

clrscr();

printf(“Enter Number of Rows:–\n”);

scanf(“%d”,&Row);

printf(“Enter Number of Column:–\n”);

scanf(“%d”,&Col);

printf(“Enter Matrix:—\n”);

for(i=0;i<Row;i++)

for(j=0;j<Col;j++)

scanf(“%d”,&A[i][j]);

clrscr();

printf(“Matrix:—\n”);

for(i=0;i<Row;i++)

for(j=0;j<Col;j++)

printf(“%d “,A[i][j]);
printf(“\n”);

for(i=0;i<Col;i++)

for(j=0;j<Row;j++)

C[i][j]=A[j][i];

printf(“Transpose of Matrix:—\n”);

for(i=0;i<Col;i++)

for(j=0;j<Row;j++)

printf(“%d “,C[i][j]);

printf(“\n”);

getch();

7.14 Every book published by international publishers should carry an


International

Standard Book Number (ISBN). It is a 10 character 4 part number as


shown below.

0-07-041183-2
The first part denotes the region, the second represents publisher, the third
identifies the book and the fourth is the check digit. The check digit is
computed as follows:

Sum= (1*first digit) + (2*second digit) + (3*third digit)+…………….+


(9*ninth digit)

Check digit is the remainder when Sum is divided by 11. Write a program
that reads a given ISBN number and check whether it represents a valid
ISBN.

Algorithm:–

Step 1: Read Array ISBN.

Step 2: Compute Sum=Sum+(i*ISBN[i]) for i=0 to 9

Step 3: Compute CheckDig=Sum%11

Step 4: Check CheckDig=ISBN[10] then go to Step 5 Otherwise go to Step 6

Step 5: Display “Valid ISBN”

Step 6: Display “Invalid ISBN”

Flowchart:–
Program:–

//Write a program that reads a given ISBN number and check whether it represents
a valid ISBN.

// Date : 16/03/2010

#include<stdio.h>

#include<conio.h>
#define MAX 10

void main()

int ISBN[11];

int i,j,Sum,CheckDig;

clrscr();

Sum=0;

printf(“Enter ISBN Number:—\n”);

for(i=1;i<=10;i++)

scanf(“%d”,&ISBN[i]);

for(i=1;i<=9;i++)

Sum=Sum+(i*ISBN[i]);

CheckDig=Sum%11;

if(CheckDig==ISBN[10])

printf(“\nValid ISBN\n”);

else

printf(“\nInvalid ISBN\n”);

getch();

}
7.15 Write a program to read two matrices A and B and print the following:

a) A + B and

b) A – B.

Algorithm:–

Step 1: Read Row, Col, Array A & B.

Step 2: Display Array A & B.

Step 3: Compute Addition of Array A & B & Store in Array C.

Step 4: Display Array C

Flowchart:–
Program:–

//Write a program to read two matrices A and B and print the following:

//a) A + B and

//b) A – B.

// Date : 16/03/2010

#include<stdio.h>

#include<conio.h>

#define MAX 10

void main()
{

int A[MAX][MAX],B[MAX][MAX],C[MAX][MAX];

int Row,Col,i,j;

clrscr();

printf(“Enter Number of Rows:–\n”);

scanf(“%d”,&Row);

printf(“Enter Number of Column:–\n”);

scanf(“%d”,&Col);

printf(“Enter First Matrix:—\n”);

for(i=0;i<Row;i++)

for(j=0;j<Col;j++)

scanf(“%d”,&A[i][j]);

printf(“Enter Second Matrix:—\n”);

for(i=0;i<Row;i++)

for(j=0;j<Col;j++)

scanf(“%d”,&B[i][j]);

clrscr();

printf(“First Matrix:—\n”);

for(i=0;i<Row;i++)
{

for(j=0;j<Col;j++)

printf(“%d “,A[i][j]);

printf(“\n”);

printf(“Second Matrix:—\n”);

for(i=0;i<Row;i++)

for(j=0;j<Col;j++)

printf(“%d “,B[i][j]);

printf(“\n”);

for(i=0;i<Row;i++)

for(j=0;j<Col;j++)

C[i][j]=A[i][j]+B[i][j];

printf(“Addition of Matrix:—\n”);

for(i=0;i<Row;i++)

for(j=0;j<Col;j++)
printf(“%d “,C[i][j]);

printf(“\n”);

for(i=0;i<Row;i++)

for(j=0;j<Col;j++)

C[i][j]=A[i][j]-B[i][j];

printf(“Subtration of Matrix:—\n”);

for(i=0;i<Row;i++)

for(j=0;j<Col;j++)

printf(“%d “,C[i][j]);

printf(“\n”);

getch();

Algorithm:–

Step 1: Read Array ISBN.

Step 2: Compute Sum=Sum+(i*ISBN[i]) for i=0 to 9

Step 3: Compute CheckDig=Sum%11


Step 4: Check CheckDig=ISBN[10] then go to Step 5 Otherwise go to Step 6

Step 5: Display “Valid ISBN”

Step 6: Display “Invalid ISBN”

Flowchart:–

Program:–

//Write a program that reads a given ISBN number and check whether it represents
a valid ISBN.

// Date : 16/03/2010

#include

#include

#define MAX 10

void main()

int ISBN[11];

int i,j,Sum,CheckDig;

clrscr();

Sum=0;

printf(“Enter ISBN Number:—\n”);

for(i=1;i<=10;i++)

scanf(“%d”,&ISBN[i]);
for(i=1;i<=9;i++)

Sum=Sum+(i*ISBN[i]);

CheckDig=Sum%11;

if(CheckDig==ISBN[10])

printf(“\nValid ISBN\n”);

else

printf(“\nInvalid ISBN\n”);

getch();

7.15 Write a program to read two matrices A and B and print the following:

a) A + B and

b) A – B.

Program:–

//Write a program to read two matrices A and B and print the following:

//a) A + B and

//b) A – B.

// Date : 16/03/2010

#include

#include
#define MAX 10

void main()

int A[MAX][MAX],B[MAX][MAX],C[MAX][MAX];

int Row,Col,i,j;

clrscr();

printf(“Enter Number of Rows:–\n”);

scanf(“%d”,&Row);

printf(“Enter Number of Column:–\n”);

scanf(“%d”,&Col);

printf(“Enter First Matrix:—\n”);

for(i=0;i<Row;i++)

for(j=0;j<Col;j++)
scanf(“%d”,&A[i][j]);

printf(“Enter Second Matrix:—\n”);

for(i=0;i<Row;i++)

for(j=0;j<Col;j++)
scanf(“%d”,&B[i][j]);

clrscr();

printf(“First Matrix:—\n”);
for(i=0;i<Row;i++)

for(j=0;j<Col;j++)
printf(“%d “,A[i][j]);

printf(“\n”);

printf(“Second Matrix:—\n”);

for(i=0;i<Row;i++)

for(j=0;j<Col;j++)
printf(“%d “,B[i][j]);

printf(“\n”);

for(i=0;i<Row;i++)

for(j=0;j<Col;j++)
C[i][j]=A[i][j]+B[i][j];

printf(“Addition of Matrix:—\n”);

for(i=0;i<Row;i++)

for(j=0;j<Col;j++)
printf(“%d “,C[i][j]);
printf(“\n”);

for(i=0;i<Row;i++)

for(j=0;j<Col;j++)
C[i][j]=A[i][j]-B[i][j];

printf(“Subtration of Matrix:—\n”);

for(i=0;i<Row;i++)

for(j=0;j<Col;j++)
printf(“%d “,C[i][j]);

printf(“\n”);

getch();

}
CHAPTER-8

8.3 Write a program to extract a portion of a character string and print the
extracted string. Assume that m characters are extracted, starting with the
nth character.

Answer:

//Write a program to extract a portion of a character


string and print the extracted string.

//Assume that m characters are extracted, starting with


the nth character.

//Date: 18/03/2010#include

#include

#define MAX 50

void main()

char Str1[MAX];

int i,m,n,j;

clrscr();

printf("Enter A String:--\n");

scanf("%[^\n]s",Str1);

printf("\nEnter Number of Characters Which U Wnat to


Extract-->\n");
scanf("%d",&m);

printf("\nEnter Beginnig Index from Which U Want to


Extract-->\n");

scanf("%d",&n);

printf("\nExtracted String is:--\n\n");

for(i=n-1;i

getch();

8.7 A Maruti car dealer maintains a reecord of sales of various vehicles in the
following

form:

Vehicle Type Month of sales Price

MARUTI-800
02/01 210000

MARUTI-DX
07/01 265000

GYPSY 04/02
315750
MARUTI-VAN 08/02
240000

Write a program to read this data into a table of strings and output the
details of a

particular vehicle sold during a specified period. The program should


request the user to

input the vehicle type and the period (starting month, ending month).

Answer:

#include<stdio.h>

#include<conio.h>

#define MAX 10

void main()

char Veh[MAX][MAX]={“”};

char Vehicle[MAX];

int St_Mon[MAX],En_Mon[MAX],StMon,EnMon;

long int Price[MAX];

int n,i;

clrscr();
printf(“How Entries U Want to Enter\n”);

scanf(“%d”,&n);

printf(“Enter Vehcle Type,Starting Month, Ending Month & Price:–\n”);

for(i=0;i<n;i++)

scanf(“%s”,Veh[i]);

scanf(“%d”,&St_Mon[i]);

scanf(“%d”,&En_Mon[i]);

scanf(“%ld”,&Price[i]);

clrscr();

printf(“Vehicle Type Month of Sales Price\n”);

for(i=0;i<n;i++)

printf(“%s 0%d / 0%d


%ld\n”,Veh[i],St_Mon[i],En_Mon[i],Price[i]);

printf(“Enter The Type of Vehicle\n”);

scanf(“%s”,Vehicle);

printf(“Enter the Starting & Ending Month\n”);


scanf(“%d %d”,&StMon,&EnMon);

for(i=0;i<n;i++)

if((strcmp(Veh[i],Vehicle)==0))

if(St_Mon[i]>=StMon)

if(En_Mon[i]<=EnMon)

printf(“Vehicle Type %s is Sold During Period


0%d/0%d\n”,Vehicle,StMon,EnMon);

getch();

exit(0);

printf(“Vehicle Type %s Not Sold During Period


0%d/0%d\n”,Vehicle,StMon,EnMon);

getch();
}

8.9 Write a program that reads the cost of an item in the form RRRR.PP
(where RRRR denotes Rupees and PP denotes Paise) and converts the value
to a string of words that express the numeric value in words. For example, if
we input 125.75 the ouput should be“ONE HUNDRED TWENTY FIVE AND
PAISE SEVENTY FIVE”.

Answer:

#include<stdio.h>

#include<conio.h>

void main()

float Cost,Pai,Re,j;

int Rup,i,R;

clrscr();

printf("\nEnter Cost of an ITEM-->\n");

scanf("%f",&Cost);

Rup = Cost;

Pai = (Cost - Rup)*100;


i=Rup/100;

switch(i)

case 1: printf("ONE HUNDRED "); break;

case 2: printf("TWO HUNDRED "); break;

case 3: printf("THREE HUNDRED "); break;

case 4: printf("FOUR HUNDRED "); break;

case 5: printf("FIVE HUNDRED "); break;

case 6: printf("SIX HUNDRED "); break;

case 7: printf("SEVEN HUNDRED "); break;

case 8: printf("EIGHT HUNDRED "); break;

case 9: printf("NINE HUNDRED "); break;

i=Rup%100;

R=i/10;

Re=(float)i/10;

switch(R)

case 1: printf("TEN"); break;


case 2: printf("TWENTY "); break;

case 3: printf("THIRTY "); break;

case 4: printf("FOURTY "); break;

case 5: printf("FIFTY "); break;

case 6: printf("SIXTY "); break;

case 7: printf("SEVENTY "); break;

case 8: printf("EIGHTY "); break;

case 9: printf("NINETY "); break;

R=(Re-R)*10;

switch(R)

case 1: printf("ONE"); break;

case 2: printf("TWO "); break;

case 3: printf("THREE "); break;

case 4: printf("FOUR "); break;

case 5: printf("FIVE "); break;

case 6: printf("SIX "); break;

case 7: printf("SEVEN "); break;


case 8: printf("EIGHT "); break;

case 9: printf("NINE "); break;

printf("AND PAISE ");

i=Pai/10;

Re=(float)Pai/10;

R=(Re-i)*10;

switch(i)

case 1: printf("TEN"); break;

case 2: printf("TWENTY "); break;

case 3: printf("THIRTY "); break;

case 4: printf("FOURTY "); break;

case 5: printf("FIFTY "); break;

case 6: printf("SIXTY "); break;

case 7: printf("SEVENTY "); break;

case 8: printf("EIGHTY "); break;

case 9: printf("NINETY "); break;

}
switch(R)

case 1: printf("ONE"); break;

case 2: printf("TWO "); break;

case 3: printf("THREE "); break;

case 4: printf("FOUR "); break;

case 5: printf("FIVE "); break;

case 6: printf("SIX "); break;

case 7: printf("SEVEN "); break;

case 8: printf("EIGHT "); break;

case 9: printf("NINE "); break;

getch();

}
8.10 Develop a program that will read and store the details of a list of students
in the format

Roll No. Name Marks Obtained

…………. ……… ………………..

…………. ……… ………………..

And produce the following output lists:

a) Alphabetical list of names, roll numbers and marks obtained.

b) List sorted on roll numbers.

c) List sorted on marks (rank-wise list)

Answer:

#include<stdio.h>

#include<conio.h>

#define MAX 50

void main()

{
char Stu_Name[MAX][MAX]={“”};

//char Stu_Name1[MAX][MAX]={“”};

char Temp[MAX]=”";

int roll_No[MAX],Marks[MAX],n,i,In[MAX],Roll_No1[MAX],Marks1[MAX];

int Temp1,Temp2;

int j;

clrscr();

printf(“How Many Student Name U Want to Enter\n\n”);

scanf(“%d”,&n);

printf(“Enter Roll No. & Students Name & Total Marks:–\n”);

for(i=0;i<n;i++)

scanf(“%d”,&Roll_No[i]);

scanf(“%s”,Stu_Name[i]);

scanf(“%d”,&Marks[i]);

clrscr();

printf(“Roll No Name Marks\n”);

for(i=0;i<n;i++)
{

printf(“%d%s%d\n”,Roll_No[i],Stu_Name[i],Marks[i]);

for(i=0;i<n;i++)

for(j=0;j<n-i-1;j++)

if(strcmp(Stu_Name[j],Stu_Name[j+1])>0)

strcpy(Temp,Stu_Name[j]);

strcpy(Stu_Name[j],Stu_Name[j+1]);

strcpy(Stu_Name[j+1],Temp);

Temp1=Roll_No[j];

Roll_No[j]=Roll_No[j+1];

Roll_No[j+1]=Temp1;

Temp2=Marks[j];

Marks[j]=Marks[j+1];

Marks[j+1]=Temp2;

}
}

printf(“\nAccording to Student Names:–\n”);

printf(“Roll No Name Marks\n”);

for(i=0;i<n;i++)

printf(“%d %s %d\n”,Roll_No[i],Stu_Name[i],Marks[i]);

for(i=0;i<n;i++)

for(j=0;j<n-i-1;j++)

if(Roll_No[j]>Roll_No[j+1])

strcpy(Temp,Stu_Name[j]);

strcpy(Stu_Name[j],Stu_Name[j+1]);

strcpy(Stu_Name[j+1],Temp);

Temp1=Roll_No[j];

Roll_No[j]=Roll_No[j+1];
Roll_No[j+1]=Temp1;

Temp2=Marks[j];

Marks[j]=Marks[j+1];

Marks[j+1]=Temp2;

printf(“\nAccording to Marks:–\n”);

printf(“Roll No Name Marks\n”);

for(i=0;i<n;i++)

printf(“%d %s %d\n”,Roll_No[i],Stu_Name[i],Marks[i]);

for(i=0;i<n;i++)

for(j=0;j<n-i-1;j++)

if(Marks[j]<Marks[j+1])

{
strcpy(Temp,Stu_Name[j]);

strcpy(Stu_Name[j],Stu_Name[j+1]);

strcpy(Stu_Name[j+1],Temp);

Temp1=Roll_No[j];

Roll_No[j]=Roll_No[j+1];

Roll_No[j+1]=Temp1;

Temp2=Marks[j];

Marks[j]=Marks[j+1];

Marks[j+1]=Temp2;

printf(“\nAccording to Roll No:–\n”);

printf(“Roll No Name Marks\n”);

for(i=0;i<n;i++)

printf(“%d %s %d\n”,Roll_No[i],Stu_Name[i],Marks[i]);

getch();
}

8.11 Write a program to read to strings and compare them using the function
strcmp() and print a mesaage that the first string is equal, less or greater than
the second one.

Answer:

#include<stdio.h>

#include<conio.h>

#define MAX 50

void main()

char Str1[MAX],Str2[MAX];

clrscr();

printf(“Enter First String:–\n”);

scanf(“%[^\n]s”,Str1);
fflush(stdin);

printf(“Enter Second String:–\n”);

scanf(“%[^\n]s”,Str2);

if(strcmp(Str1,Str2)==0)

printf(“\nBoth Strings are Equal\n”);

else if(strcmp(Str1,Str2)<0)

printf(“\nFirst String is Less Than\n”);

else

printf(“\nFirst String is Greater Than\n”);

getch();

8.12 Write a program to read a line of text from the keyboard and print out
the number of occurrences of a given substring using the function strstr().

Answer:

#include<stdio.h>

#include<conio.h>
#define MAX 50

void main()

char *Str1,*Str2,*Str3;

int i,Len,Len1,Count;

clrscr();

Count=0;

printf(“Enter Text:–\n”);

scanf(“%[^\n]s”,Str1);

fflush(stdin);

printf(“Enter Substring:–\n”);

scanf(“%[^\n]s”,Str2);
Len=strlen(Str1);

Len1=strlen(Str2);

strcpy(Str3,Str1);

for(i=0;i<Len;i++)

if((Str3=strstr(Str3,Str2))!=NULL)

i=i+Len1;

Count=Count+1;

strcpy(Str3,(Str3+Len1));

printf(“\n\nNumber of occurences is:– %d”,Count);

getch();

}
8.13 Write a program that will copy m consecutive characters from a string s1
beginning at position n into another string s2.

Answer:

#include<stdio.h>

#include<conio.h>

#define MAX 50

void main()

char Str1[MAX],Str2[MAX];

int i,m,n,j;

clrscr();

printf(“Enter A String:–\n”);

scanf(“%[^\n]s”,Str1);
printf(“\nEnter Number of Characters Which U Wnat to Copy–>\n”);

scanf(“%d”,&m);

printf(“\nEnter Beginnig Index from Which U Want to Copy–>\n”);

scanf(“%d”,&n);

for(i=n-1,j=0;i<m+n;i++,j++)

Str2[j]=Str1[i];

Str2[m]=”;

printf(“\n\nCopied String is–> %s \n\n”,Str2);

getch();

}
8.14 Write a program to create a directory of students with roll numbers.The
program should display the roll number for a specified name and vice-versa.

Answer:

#include<stdio.h>

#include<conio.h>

#define MAX 50

void main()

char Stu_Name[MAX][MAX],Name[MAX];

int Roll_No[MAX],n,i,Roll,Index;

clrscr();

printf(“How Many Student Name U Want to Enter\n\n”);

scanf(“%d”,&n);

printf(“Enter Roll No. & Students Name:–\n”);


for(i=0;i<n;i++)

scanf(“%d”,&Roll_No[i]);

scanf(“%s”,Stu_Name[i]);

printf(“\nEnter Student Roll No which U want to Search:–\n”);

scanf(“%d”,&Roll);

for(i=0;i<n;i++)

if(Roll==Roll_No[i])

Index=i;

printf(“\nName of Student is –> %s whose Roll No is:–


%d”,Stu_Name[Index],Roll);
printf(“\n\nEnter Student Name which U want to Search:–\n”);

scanf(“%s”,Name);

for(i=0;i<n;i++)

if(strcmp(Stu_Name[i],Name)==0)

Index=i;

printf(“\n\nRoll No of is:– %d Student Whose Name is:–


%s\n”,Roll_No[Index],Stu_Name[Index]);

getch();

8.15 Given a string char str[ ] =”123456789”; Write a program that displays
the following:
1

232

34543

4567654

567898765

answer:

#include<stdio.h>

#include<conio.h>

void main()

char Str[]=”123456789″;

int i,j,k,l;

clrscr();

for(i=0;i<5;i++)

for(k=4;k>i;k–)
{

printf(” “);

for(j=0,l=i;j<=i;j++,l++)

printf(“%c”,Str[l]);

l=l-2;

for(k=0;k<i;k++,l–)

printf(“%c”,Str[l]);

printf(“\n”);

getch();

Vous aimerez peut-être aussi