Beginners C-Programs List: Since 1999

Download as pdf or txt
Download as pdf or txt
You are on page 1of 135

Beginners C-Programs list

Since 1999
C-Family Computer Education
Flyover Pillar No:16, Service Road, Benz Circle,
Vijayawada, AP, India, pincode-520010,
9440-030405, 8500-117118
S.NO CHAPTER PAGE Problems
1 Basic Programs 1-8 35
2 If-Else programs 9-16 44
3 Loops 17-35 104
4 Nested Loops 36-40 50
5 Arrays 41-49 36
6 Functions 51-57 25
7 Recursion 59-70 44
8 Pointers 71-81 30
9 Strings 83-92 50
10 Structures 93-100 15
11 Files 101-107 12
12 C++ Programs List 109-122 14
13 Java Programs List 1230-133 11

For self-practice exercises on C-language programming, around 500 simple


exercises provided to the beginners who wish to expertise on programming

This programs list & c-material softcopy is available in pdfhost.io website, to download the file, search
through keyword ‘cfamily1999’ This pdf file(s) designed for 2-sided print-copy (Xerox hard copy).
For your suggestions contact: [email protected]
3 C-Family | Basic Programs

Basic Programs
* the division 20/8 gives 2, but not 2.5, whereas 20.0/8 gives 2.5
* if two values are integer then C-language gives only integer part of result and fraction is omitted
* the division int/int gives result as int, whereas float/int gives float value result
* output type of any expression is highest type operand in the expression. For example, if ‘x’ is int-type and
‘y’ is float-type then ‘x+y’ gives float-type result value.
Following programs are basic level programs, so do not use any control structures like if, if-else, while-loop,
for-loop, arrays,…etc.
------------------------------------------------------------------------------------------------------------------------------------------------
1) write a program to accept a value (N) from keyboard and print its opposite sign value.
Process: read N from keyboard, multiply it with -1 to get opposite sign value and print on the screen.
ip: 19 ip: -19
op: -19 op: 19
------------------------------------------------------------------------------------------------------------------------------------------------
2) code to accept a number N from keyboard and print N for 3 times, but the next value of N is double of the
previous value. Note: Try without using multiplication operator and using only single variable.
ip: 6 ip: 100
op: 6, 12, 24 op: 100, 200, 400
Hint: we can solve this problem by writing three printf() or single printf() statment. (for doubling n=n+n)
------------------------------------------------------------------------------------------------------------------------------------------------
3) code to print N-5, N, N+5 (3 values) where N is input. (do with single variable N in the program, do not
take two or more variables) Hint: we can solve problem using single printf() or three printf() statements.
ip: N=26
op: 21, 26, 31
------------------------------------------------------------------------------------------------------------------------------------------------
4) code to print 3x2+2x+1 value for 3 times, where ‘x’ is input from keyboard for first time, for 2nd & 3rd time,
the x value is double of previous value.(2x, 4x). Note: try using two variables.
op: 6 (if x is 1)
17 (when x becomes 2x)
57 (when 2x becomes 4x)
209 (when 4x becomes 8x) …
------------------------------------------------------------------------------------------------------------------------------------------------
5) code to print 3x+2 value for 3 times, for first time, the ‘x’ values is input, for second or third time,
the ‘x’ value is output of previous sum. output1=3*x+2, output2=3*output1+2, output3=3*output2+2
Note: Try using single variable ‘x’ in the program.
ip: x=1 ip: x=5
op: 5, 17, 53. op: 17, 53, 161
------------------------------------------------------------------------------------------------------------------------------------------------
6) code to accept a number N from keyboard and print N for 3 times, but the next value of N is half of the
previous value. Note: use the number 2, and do not use any other number.
ip: 64 ip: 100 ip: 70
op: 64, 32, 16 op: 50, 25, 12 op: 70, 35, 17
Hint: we can solve this problem using single printf() or three printf() statements.
------------------------------------------------------------------------------------------------------------------------------------------------
4 C-Family | Basic Programs

7) code to accept two numbers as numerator & denominator and print remainder without using modulus
operator (%). For example, if input is 22 & 4 then remainder is 2.
Logic: use operators *, - and /
Hint: 22/4 gives result 5 (not 5.5)
The purpose of this program to teach you to
* the division int/int gives result int, whereas float/int gives float.
* output type of any sum is highest type operand in the expression. For example, if ‘x’ is int-type and ‘y’
is float-type then ‘x+y’ gives float-type result value.
------------------------------------------------------------------------------------------------------------------------------------------------
8) code to accept radius of circle from keyboard and print area and perimeter
ip: radius: 5
op: area =78.5
perimeter=31.4
Process: Area of circle is “pie*radius*radius”, perimeter of circle is “2*pie*radius”
Note: The symbol ‘pie’ or ‘pie value’ is not available or not known to C-language, so use the constant value
3.14 (22/7) in the equation, for example: “area=3.14*radius*radius”
Algorithm:
step1: scan ‘radius’ as input
step2: find ‘area’ // area=3.14*radius*radius
step3: find ‘perimeter’ // perimeter=2*3.14*radius
step4: print ‘area’ and ‘perimeter’
step5: stop.
-----------------------------------------------------------------------------------------------------------------------------------------------
-9) code to accept area of circle and find radius (input is area, output is radius)
ip: area: 78.5,
op: radius of circle is: 5
Process: radius = sqrt(area/3.14)
Note: use sqrt() function to get square root, also add header file “#include<math.h>” to the program
-----------------------------------------------------------------------------------------------------------------------------------------------
-10) code to find Fahrenheit from a given Celsius temperature
ip: Celsius : 34
op: Fahrenheit : 93.2
Process: Celsius to Fahrenheit: F  (C × 9/5) + 32
-----------------------------------------------------------------------------------------------------------------------------------------------
-11) code to find simple interest(si) from a given principle, rate of interest and time
ip: say principle is 1000, rate of interest is 2.00, time is 12 (12months)
op: simple interest = 240.00
Process: step1: scan( p, t, r ) as input values.
step2: calculate si=p*t*r/100.
step3: print( si )
-----------------------------------------------------------------------------------------------------------------------------------------------
12) code to accept employee basic salary from keyboard and print net salary as shown below.
(hraHouseRentAllowence; daDearnessAllowence, taTravellingAllowence)
hra24.3% on basic salary
da 8.5% on basic salary
ta 10% on basic salary
net salary = basic salary + hra + da + ta;
5 C-Family | Basic Programs

Algorithm:
step1: take basicSalary, netSalary, HRA, DA, TA as variables
step2: read basicSalary as input
step3: calculate hra // hra=24.3*basicSalary/100
step4: calcucate da // da=8.5*basicSalary/100
step5: calcucate ta // ta =10*basicSalary/100
step6: find netSalary // netSalary=basicSalary+hra+da+ta
step7: print netSalary
step8: stop
-----------------------------------------------------------------------------------------------------------------------------------------------
*13) code to accept two values into variables (x, y) and print after swapping(exchanging) them,
use third variable while swapping x , y.
ip: 12 34
op: 34 12
Algorithm:
step1. take variables x , y for input // for swapping take extra variable ‘temp’ (temporary/supporting variable)
step2. scan x ,y
step3. store x to ‘temp’
step4. store y to x
step5. store ‘temp’ to y
step6. print(x, y)
step7. Stop
Method2: without using ‘temp’ variable
subtract one with another value (x=x-y), using this difference, we can swap x, y values. For example
Let x=10, y= 4
x=x-y; // now x is 6
y=x+y; // y got 10, this is value of x
x=y-x; // x got 4, this is value of y
This logic works for any values of x , y
-----------------------------------------------------------------------------------------------------------------------------------------------
*14) If 3 values entered through keyboard, write a program to find sum and average of them.
Note: take only two variables in the program (let ‘N’, ‘sum’ are variables)
ip: enter value1: 10
enter value2: 20
enter value3: 30
op: sum=60, average=20
Process: read 3 values one by one into ‘N’ using three scanf() statements, after scanning every single value
add it to ‘sum’, algorithm is as follows:
step1: read first input into N
step2: save N value to sum. (store N to ‘sum’)
step3: read second input into N
step4: add N to ‘sum’ // ‘sum’ already contained first value, so add second input N to sum.
step5: read third input into N
step6: add N to ‘sum’
step7: print(sum, sum/3)
step7: stop
-----------------------------------------------------------------------------------------------------------------------------------------------
6 C-Family | Basic Programs

15) The BigBite shop owner priced 3/- per each egg and also giving bonus eggs as given below
Bonus1) one extra bonus egg for every 5 eggs purchased, if customer purchased 15 eggs then he get 3 extra
eggs as bonus1, if he purchased 35 eggs then he get 7 eggs).
Bonus2) again two more extra bonus eggs, if customer purchased 100 eggs as one lot, that is, for every 100
eggs he get 2 eggs. For example, if he purchased 100 eggs then customer get 2 eggs as bonus2. If he
purchased 230 then he gets 4 eggs.
Here the input of the program is number of eggs wanted by customer and output is pay Amount and
number of eggs to be delivered to the customer.
ip: 120 (N=120, no.of eggs wanted by customer)
op: total cost of 120 eggs is: 360rs/-
total eggs delivered: 120+24+2146 ( N + bonus1 + bonus2 )
take variables names as: N, pay, totalEggsDelivered.
-----------------------------------------------------------------------------------------------------------------------------------------------
-16) A fruit seller told 5 apples cost is 65rs/- and the customer wanted to buy apples for 100rs/-.
Here each apple costs 13rs/-, and he can get nearly 7 apples for 100rs/- and change return is 9rs/-
Now generalize this problem by writing a program, for example, if N apples cost is C, then what is the cost of
each apple and how many apples customer can get for amount M, tell if any change to be returned.
List of variables names:
input: N  no.of apples, C  Cost of N apples, M Amount the customer can spent (buying amount).
output: eachAppleCost cost of each apples, countOfApplesCustomerGainedforM  total no.of apples
customer can get nearly for amount M, changeReturn  change to be returned to the customer.
ip: N=5, C=68rs, M=1000rs
op: each apple cost is 13.60rs
he can get 73 apples for 1000rs-
he get back 8rs/- change roughly.
Note: use format string “%.2f” in printf() statement, for example printf(“%.2f”, 23.123456)  23.12
if you use type-casting/type-conversion concept we can get result accurately.
Example for type-casting: (int)10.45 = 10, (float)14= 14.00, let a=45.67 then (int)a=45
-----------------------------------------------------------------------------------------------------------------------------------------------
*17) Code to accept a time in H : M : S format as input and print output in seconds format.
Hint: Here we have to scan time like 3 values, for example: scanf(“%d%d%d”, &H, &M, &S);
ip: 2 40 50 (2-hr , 40-min , 50-sec) ip: 0 2 50 (0-hr , 2-min, 50-sec)
op: 9650 seconds op: 170 seconds
Logic: each minutes has 60 seconds
each hour has 3600 seconds
variable list: Hhours, Mminutes, Sseconds, Noutput value of seconds (take N as long int)
N = H*3600L + M*60 + S;
Note: 3600 takes as int value, but 3600L takes as long int value.
---------------------------------------------------------------------------------------------------------------------------------------------
*18) Code to accept a time(N) in seconds format and print output in time format (H:M:S format)
ip: 7270
op: 2-hours, 1-minutes, 10-seconds
Logic: divide N with 3600 and take the quotient as hours, (1hour=3600seconds)
divide N with 3600 and take the remainder(R). This R is the remaining seconds left after
taking hours from N. Again divide R with 60 and collect quotient and remainder.
The quotient would be minutes and remainder would be seconds.
-----------------------------------------------------------------------------------------------------------------------------------------------
7 C-Family | Basic Programs

19) Code to accept a sample time and increment it by N seconds, here N is also an input.
ip: 12 59 58 (sample time taken from keyboard : Hours=12, Min=59, Seconds=58)
124 (sample no.of seconds to increment, N=124)
op: 13hr 2min 2sec (time after incrementing N seconds)
Method1:
1. take variables H,M,S and N as variables
2. scan(H,M,S and N) values from keyboard.
3. add N to S (to increment the given time by N seconds)
4. Now S may go out of 59 seconds, so takeout minutes from S by dividing S with 60 (S/60)
add this quotient(minutes) to M, later assign remaining seconds to S (S=S%60)
5: Now M may go out of 59 minutes, so do as above said.
Method2:
1. Take variables H,M,S and N as variables
2. Convert total time into seconds (k).
3. Now add N with total time of seconds (K).
4. Now distribute this K into H,M,S as said in above problem
(this method2 is simple than method1)
(try using these two methods )
----------------------------------------------------------------------------------------------------------------------------------------------
*20) Code to accept two shifts of working time of an employee and find total time worked in two shifts.
ip: 12 50 58 (shift-1 worked duration : Hours=12, Min=50, Seconds=58 )
2 53 55 (shift-2 worked duration : H= 2, M=53, S=55 )
op: 15hr 44min 53sec (total duration worked in two shifts)
----------------------------------------------------------------------------------------------------------------------------------------------
*21) Code to accept only two digit number(N) like 47 and print sum of digits (4+7)
ip: 47 ip: 84
op: 4+7  11 op: 8+4  12
Logic: divide the input N( Let N=47) with 10, collect remainder & quotient .
The quotient will be 4 and remainder will be 7. This is as shown below,
10) 47 (4 quotient
40
---------------
7  remainder
N/10  47/10  4
N%10  47%10  7
now do sum=N/10+N%10; // sum=4+7
----------------------------------------------------------------------------------------------------------------------------------------------
22) Code to accept only two digit number(N) like 47 and print reverse of it (74)
ip: 47 ip: 84
op: 74 op: 48
if input is 47 then output generated as 7 * 10 + 4 74
----------------------------------------------------------------------------------------------------------------------------------------------
23) Code to accept a number and print its boundaries surrounded by ten multiples
eg1) if input is 34 then print output as “surrounded by 30-40”
eg2) if input is 89 then print output as “surrounded by 80-90”
Hint: 34/103 (not 3.4), so use formula 34/10*1030
-----------------------------------------------------------------------------------------------------------------------------------------------
8 C-Family | Basic Programs

*24) Code to accept 3-digit number(N) like 247 and print sum of all digits 2+4+7, following text may help you
Let N=2345
2345%10  gives 5 as remainder  2345/10  gives 234 as quotient
2345%100  gives 45 as remainder  2345/100  gives 23 as quotient
2345%1000  gives 345 as remainder  2345/1000  gives 2 as quotient
2345%10000  gives 2345 as remainder  2345/1000  gives 0 as quotient
Hint1: N=247
* N%10  247%10  7
* (N%100)/10  (247%100)/10  (47)/104 OR (N/10)%10  (247/10)%10  (24)%104
* N/100  2
----------------------------------------------------------------------------------------------------------------------------------------------
-25) Code to accept a number (N) and print next nearest divisible of 5.
eg1) if input is 34 then next nearest 5 divisible is 35
eg2) if input is 46 then next nearest 5 divisible is 50
eg3) if input is 40 then next nearest 5 divisible is 40 (not 45)
Logic: divide the input N with 5 and take the remainder, with the help of remainder we can solve it.
----------------------------------------------------------------------------------------------------------------------------------------------
26) If a four-digit number is input through the keyboard, write a program to obtain the sum of the first and
last digits of input.
ip: 4567 ip: 1234 ip: 2000
ip: 4+7=11 op: 1+4 5 op: 2+0  2
---------------------------------------------------------------------------------------------------------------------------------------------
27) If a four-digit number is input through the keyboard, write a program to print middle two-digits
ip: 4567 ip: 1234
ip: 56 op: 23
---------------------------------------------------------------------------------------------------------------------------------------------
28) If a four-digit number(N) is input through the keyboard, write a program to swap first and last digit and
print them. (Let last digit of N is not zero)
ip: 3456 ip: 3778
op: 6453 op: 8773
---------------------------------------------------------------------------------------------------------------------------------------------
*29) Write a program to accept 4-digit single number from keyboard and print sum of all digits
ip: 4567
op: 4+5+6+7
step1: Divide N with 10 and take the remainder, the remainder is always last-digit when a number
divide with 10, here for N=4567, the remainder is 7, add this 7 to variable ‘sum’.

step2: To get next digit(6), now remove current last-digit 7 from N by doing N=N/10.
after N=N/10, the N value becomes 4567 to 456

step3: Again divide N with 10, and take the last-digit 6 as remainder, add this 6 to ‘sum’.

Repeat this process for 4 times.


9 C-Family | Basic Programs

Let us see, how digits are added to ‘sum’.


Initially, N=4567, sum=0
sum = sum + N%10 N=N/10
step1: sum = 0 + 4567%10  0 + 7  7 N=4567/10  456
step2: sum = 7 + 456%10  7 + 6  13 N=456/10  45
step3: sum = 13 + 45%10  13+5  18 N=45/10  4
step4: sum = 18 + 4%10  18+4  22 N=4/10  0
sum = 1 8 + 4
finally sum=22

We can do above program in other method as


sum = ( n%10 ) + ( n/10%10 ) + ( n/100%10 ) + ( n/1000 )
sum = ( 7 ) + ( 6 ) + ( 5 ) + ( 4 )
---------------------------------------------------------------------------------------------------------------------------------------------
30) Write a program to accept 4-digit single number from keyboard and print reverse of it
ip: 4567 op: 7654
Logic: like previous program logic, but replace “sum=sum+n%10” with “sum=sum*10+n%10” to get reverse
value (initially sum=0).
sum = sum * 10 + n%10
= 0 * 10 + 7  7
= 7 * 10 + 6  76
= 76 * 10 + 5  765
= 765 * 10 + 4  7654
= 7654
----------------------------------------------------------------------------------------------------------------------------------------------
*31) Write a program to accept 4-digit binary value N and print equaling decimal value.
ip: 1101
op: (1*23) + (1*22) + (0*21) + (1*20)  8 + 4 + 0 + 1  13
step1: divide N with 10 and get last digit as remainder, here remainder of 1101 is  (1)
step2: multiply this remainder ‘1’ with 20 and add to ‘sum’. Like sum=sum + (1*20)
step3: to get next-digit of N, remove current last-digit from N, by doing N=N/10, [1101/10110]
step4: repeat these steps for 4 times. We can’t take or type values 20, 21, 22, 23, 24 … directly in the
program, so take these values as 1, 2, 4, 8, 16,….
-------------------------------------------------------------------------------------------------------------------------------------------
*32) Write a program to find binary number from given decimal number (Let the input is below 15)

2 13
2 6- 1
2 3- 0
2 1- 1
0- 1
103*1 + 102*1 + 101*0 + 100*1  1101

step1: divide N with 2 and take the remainder(R)


step2: now multiply remainder(R) with 100 and add to variable ‘sum’ * sum=sum+ R*100 ]
step3: now cut down N to N/2 as shown in the picture. [ 13/2 6 ]
step3: repeat above steps for 4 times. [ here for 100, 101 ,102… take 1, 10, 100 … ]
10 C-Family | Basic Programs

-----------------------------------------------------------------------------------------------------------------------------------------------
33) If a four-digit number is input through the keyboard, write a program to print a new number by adding
one to each of its digits. If the number 2391 then the output should be displayed as 3502
----------------------------------------------------------------------------------------------------------------------------------------------
-34) If a four-digit number is input through the keyboard, write a program to print a new number by adding
one to each of its digits. For example if the number 2391 then the output should be displayed as 3402 (do
not forward ‘carry’ to next digits when summing)
logic: it is little bit difficult but possible, to stop carry to the next digit, take each digit and increment by 1
and then divide the digit with 10 and get remainder, using these remainders form the output number.
-----------------------------------------------------------------------------------------------------------------------------------------------
-35) Following program prints given single digit in English words, for example
void main()
{ char *arr*+=,“zero”, “one”, “two”, … “nine”-
printf(“output is: %s ”, arr[2] ); // two
printf(“\noutput is: %s ”, arr[9] ); // nine
}
op: output is : two
output is : nine
Now try to extend this program to print 4-digit number.
ip: 3456
op: three four five six
------------------------------------------------------------------------------------------------------------------------------------------------
11 C-Family | if-else

if-else
01) If integer, N is input through keyboard, write a program to print its absolute value [ mod(N) ]
the input number may be +ve/–ve entered by user, but the output should be +ve.
Method: if input is –ve then convert into +ve by multiplying it with -1. // If(N<0) then N is -Ve;
ip: –12 ip: 14
op: 12 op: 14
-----------------------------------------------------------------------------------------------------------------------------------------------
02) If two integers are input through keyboard, write a program to find difference b/w them.
The output difference must be +ve.
Method1: subtract one with another value, if difference is –ve, then convert into +ve by multiplying with -1.
Method2: subtract small from bigger value.
ip: 12 18 ip: 18 12
op: 6 op: 6
----------------------------------------------------------------------------------------------------------------------------------------------
03) if two integers are input through keyboard, write a program to find biggest among them.
ip: 12 45 ip: 15 53
op: 45 op: 53
----------------------------------------------------------------------------------------------------------------------------------------------
04) If basic salary of employee scanned through keyboard, find net salary as given below
If basic salary <= 3000 then
DA is 5% on basic [ DA means Dearness Allowance]
TA is 9% on basic [ TA means Travelling Allowance]
If basic salary > 3000 then
DA is 9% on basic
TA is 12% on basic
HRA(house rent allowance) is 24%, this is common for both below & above 3000 salaried employees. Now
find net salary as sum of all allowances [net salary = basic salary + hra + da + ta]
----------------------------------------------------------------------------------------------------------------------------------------------
05) Program to find given number N is an odd or even.
Method: divide the input number with 2, and check the remainder, if remainder is zero then print as “even”
otherwise “odd”. (Use % operator to get remainder).
ip: 45 ip: 44
op: odd op: even
----------------------------------------------------------------------------------------------------------------------------------------------
06) Program to accept a single number(N), the number may have 2 or 3 digits, print its reverse.
ip: 234 ip: 27
op: 432 op: 72
logic: if N<100 then it is 2-digit number or else it is 3-digit number.
----------------------------------------------------------------------------------------------------------------------------------------------
07) Program to accept a single number, the number may have 2 or 3 digits, then find the number and its
reverse are equal or not?
ip: 234 ip: 272 ip: 44
op: not equal op: equal op: equal
----------------------------------------------------------------------------------------------------------------------------------------------
12 C-Family | if-else

08) Accept a value from keyboard and find whether it is +ve/–ve/zero


ip: 12 ip: -12 ip: 0
op: +ve op: -ve op: zero
method1: try without using ‘else’ keyword (write 3 independent if-statement)
method2: try using normal nested-if style
method3: try using if-else-if ladder style
-----------------------------------------------------------------------------------------------------------------------------------------------
09) Code to accept salary from keyboard and find tax.
if salary<=10000 then tax is zero
if salary >10000 and <=20000 then tax is 5% on salary
if salary >20000 then tax is 8% on salary.
ip: enter salary: 9000 ip: enter salary: 20000 ip: enter salary:42000
op: tax = 0/- op: tax = 1000/- op: tax = 3,360/-
method1: try without using ‘else’ keyword (write 3 independent if-statement)
method2: try using normal nested-if style and as well as ladder-style
-----------------------------------------------------------------------------------------------------------------------------------------------
10) Code to accept salary from keyboard and find tax, tax is 5% on salary but minimum tax is rs:200/-
For ex, if salary is 20,000/- then 5% tax is 1000/-, this is greater than minimum tax 200, so no change in tax
If salary is 1000/- then 5% tax is 50/- , but we have to collect 200/- as minimum, so change tax value to
200/-
Method: first calculate tax as 5% on salary, if tax is <200 then replace tax=200 as minimum.
ip: salary: 20000 ip: salary: 1000
op: tax=1000/- op: tax=200/-
----------------------------------------------------------------------------------------------------------------------------------------------
11) if three integers are input through keyboard, then find how many –ve values exist.
ip: -12 34 -42 ip: 52 64 -72 ip: 62 44 42
op: count=2 op: count=1 op: count=0
----------------------------------------------------------------------------------------------------------------------------------------------
12) if three integers are input through keyboard, then find at least one value is –ve or not?
ip: -12 34 -42 ip: 52 64 -72 ip: 62 44 42
op: “yes, –ve exist” op: “yes, –ve exist” op: “no, –ve is not exist”
method-1) find using logical operators
method-2) find without using logical operators (ladder style)
method-3) find without using logical operators and else keyword (use ‘bool' logic)
-----------------------------------------------------------------------------------------------------------------------------------------------
13) Code to accept 3 values from keyboard, here some values are +ve/-ve entered by the user,
later find sum & product of +ve values only. (don’t take zero neither +ve nor –ve)
ip: -2 3 4
op: sum of +ve: 3+4  7
product of +ve: 3*4  12
----------------------------------------------------------------------------------------------------------------------------------------------
14) Code to find given input number (N) is in b/w 10 and 20 or not?
ip: 12 ip: 25
op: yes, it is op: no, it is not
method1: using logical operators
method2: without using logical operators (nested-if)
method3: without using logical operators and ‘else’ keyword. (use ‘bool’ logic)
13 C-Family | if-else

----------------------------------------------------------------------------------------------------------------------------------------------
15) A number N which is b/w 10-100 input through keyboard and find whether it is prime or not?
case1: If the input N is not in limits of 10-100 then show an error message called “invalid input”.
case2: If N is in limits then find prime-ness by dividing N with 2,3,5,7. If N is divided with any of these
numbers then it is said to be not prime, or else prime (Try with and without using logical operators)
Note: Prime numbers divide only with 1 and itself, i.e., it does not divide with any other number such as
2,3,4,5,6,7,8,….N-1. If not divided with these numbers then we can say it is ‘prime’.
Logic: if not divided with 2 then it will not be divided with 4,6, 8,10…(all 2 multiples)
similarly, if not divided with 3 then it will not be divided with 6,9,12,15…(all 3 multiples)
So it is better check prime-ness with 2,3,5,7 for N below 100.
ip: 17 ip: 15 ip: 97
op: yes, prime op: no, not prime op: prime
----------------------------------------------------------------------------------------------------------------------------------------------
16) The railway dept charges rs:2/- per every kilometer(km) travelled by passenger, and also giving discount.
The input of program is distance in ‘km’ travelled by passenger and output is fare (amount to be charged).
The discount is as follows
If km <= 50 the discount is 0/–
If km > 50 the discount is 30% on above 50 kilometers travelled.
for example,
 if km is 40 then: discount = 0 // here km<=50
if km is 90km then: discount = charge*(90-50)*30/100; // 30% discount on above 50 km travelled.
 fare= km*charge – discount
The traveller has one more discount, if fare > 200 then he get 50% discount on above rs200/- amount.
ip: km=40 ip: km=80 ip: 350
op: fare is 80/- op: fare is 142/- op: fare is 360/-
----------------------------------------------------------------------------------------------------------------------------------------------
17) Government providing nearly ticket free travelling for hill station by rope, for children whose age is <13
years, the ticket cost for <13 years people is 10/- fixed. If age>=13 then cost of ticket depends upon weight
of person, the cost is 2/- per every 5 kilograms. Now write a program to scan age of person, if age<13 then
then take cost as 10/- or else scan weight of a person and calculate cost as (weight/5)*2/-
----------------------------------------------------------------------------------------------------------------------------------------------
18) Write a program to find person is eligible for job or not? If age of a person>30 then he is eligible,
if age <=30 then scan input for education years, if edu-years>=16 then say ‘eligible’ otherwise ‘not eligible’.
ip: enter age: 49 ip: enter age: 23 ip: enter age: 29
op: eligible enter education years:17 enter education years: 10
op: eligible op: not eligible
----------------------------------------------------------------------------------------------------------------------------------------------
19) In Japan, population is diminishing, the government encouraging population by cutting down tax to zero
those who have more than 1 child. Keep this in mind, write a program to accept employee salary and
calculate tax, if salary <=20000 then tax is zero, or else 30% tax on above 20000/- salary. For example, if
salary is 50000 then taxable salary is 50000-2000030000.
Method: For this program, first scan salary as input, if salary<20000 then set tax to zero, if salary > 20000
then scan input for no.of children he has, if children >=2 then set tax=0 or else calculate tax.
For this program input is ‘salary’ and output is ‘tax’
ip: enter salary: 5000 ip: enter salary: 50000 ip: enter salary:50000
op: tax=0 enter no.of children:3 enter no.of children:1
op: tax=0 op: tax= 9000
14 C-Family | if-else

----------------------------------------------------------------------------------------------------------------------------------------------
20) Any year is input through keyboard, determine whether the year is a leap-year or not.
Method: if year is divisible by 4 then it is “leap year” otherwise “not a leap year”.
ip: 2005 ip: 2008
op: Non Leap year op: Leap year
----------------------------------------------------------------------------------------------------------------------------------------------
21) Above program checks the leap-year with simple condition by 4, but for every 400 years one more extra
leap year happened. Now find whether given year is leap-year or not?
case1: If year divisible by 400, said to be leap-year (eg:1600, 2000 are leap-years but not 1700,1800, 2100)
case2: If year is divisible by 4 but not with 100 is also said to be leap-year, for eg:1996,2004,2008
case3: if above two cases are not satisfied then it is non-leap year.
ip: 1800 ip: 1600 ip: 1400
op: non leap year op: leap year op: non leap year
method1: try using logical operators && and ||
method2: try without using logical operators. (We have to use nested-if)
----------------------------------------------------------------------------------------------------------------------------------------------
22) If marks of a student are input from keyboard, write a program to print student is passed or failed;
If student obtained>50 in all subjects then print “passed” or else “failed”.
Logic: let student has 3 subjects; (Assume that 50 is the pass mark out of 100)
1) find using logical operators
2) find without using logical operators (use ‘nested-if’ keyword)
3) find without using logical operators and ‘else’ statement (use bool keyword)
ip: 51 60 70 ip: 30 60 70 ip: 90 52 60
op: passed op: failed op: passed
-----------------------------------------------------------------------------------------------------------------------------------------------
23) If marks of 2 subjects are input through a keyboard, write a program to print result.
Logic: Generally, to get pass mark, student must obtain >= 50 marks in 2 subjects, but university gave an
exemption to the students. If he got 10 marks less in any one subject out of 2 then he is also passed.
That is, he must get 50 marks in one subject and 40 in other subject.
ip: 70 46 ip: 77 66 ip: 45 45 ip: 46 59 ip: 70 74
op: passed op: passed op: failed op: passed op: passed
method1: use logical operators
method1: without using logical operators
method1: use Boolean logic operators
----------------------------------------------------------------------------------------------------------------------------------------------
24) If marks of 3 subjects of a student are input through keyboard and find result
if student obtained <35 in any one or more subjects then print “failed”
Otherwise print “A-grade/B-grade/C-grade” based on average.
If average >= 60 then print “ passed in A-grade”
If average 50 to 60 then print “passed in B-grade”
If average <50 then print “passed in C-grade”
ip: 80 90 90 ip: 45 60 50 ip: 40 36 41 ip: 20 40 50
op: passed in A-Grade op: passed in B-Grade op: passed in C-Grade op: Failed
-----------------------------------------------------------------------------------------------------------------------------------------------
15 C-Family | if-else

25) If three integers are input through keyboard, find biggest among them.
1.use logical operators and ‘else’ keyword
2.use logical operators but do not use ‘else’ keyword ( write 3 separate if-statements)
-----------------------------------------------------------------------------------------------------------------------------------------------
26) Find whether the given character is upper case alphabet or lower case alphabet or digit or any other
character?
ip: A ip: a ip: 9 ip: &
op: upper case alphabet op: lower case alphabet op: digit op: special symbol
Character ASCII Values
-----------------------------------------
A-Z 65-90
a-z 97-122
0-9 48-57
the sample code is:
char ch;
printf(“enter character :”);
scanf(“%c”, &ch):
if(ch>=’A’ && ch<=’Z’) or if(ch>=65 && ch<=90)
printf(“upper case alphabet”);
------
------
-----------------------------------------------------------------------------------------------------------------------------------------------
27) Write a program to scan an alphabet from keyboard and print its opposite case, if alphabet is not given
then print such character as it is.
ip: A ip: a ip: 8
op: a op: A op: 8

The ASCII values for A-Z is 65-90, a-z is 97-122, so the difference is 32.
‘A’+32’a’ and also ‘A’+1 ’B’
‘a’-32’A’ and also ‘B’+1’C’
-----------------------------------------------------------------------------------------------------------------------------------------------
*28) Write a program to accept 4 values from keyboard and print biggest.
method1: solve in normal nested-if style.
method2: solve in if-else-if ladder style.
method3: solve in selection style ( use following steps )
1) Let us take four variables A,B,C,D for input, also take X to store output of big value.
2) Let us assume A is big, so store A value to X
3) Now compare X with B, if B is bigger than X, then store B value to X ( replace A value )
4) Now compare X with C, if C is bigger than X, then store C value to X ( later with D)
5) Finally, the big value in X, so print it
----------------------------------------------------------------------------------------------------------------------------------------------
16 C-Family | if-else

29) If N is input through keyboard (the input b/w 0 to 99999), write a program to find how many digits exist.
ip: 234 ip: 3456 ip: 12234 ip: 3
op: 3 op: 4 op: 5 op: 1
method1: using ladder-style, for example,
if(N<10) count=1;
else if(N<100) count=2;
….
method2: without using ‘else’ keyword (use logical operators, we get 5 independent if-statements)
----------------------------------------------------------------------------------------------------------------------------------------------
30) A shop keeper sell each pen for 3/- cost and giving discount, calculate bill amount after discount.
input is number of pens(N) purchased by customer and bill calculated as “bill=N*3”
if( bill<=100) discount is 0%
if( bill>100 && bill <=200) discount is 10%
if( bill>200 && bill <=500) discount is 20%
if( bill>500) discount is 30%
finally bill is bill-discount;
-----------------------------------------------------------------------------------------------------------------------------------------------
*31) If two dates are input from keyboard, write a program to find latest date among them.
Take input dates as 6 values (d1,m1,y1 as date1 ) and (d2,m2,y2 as date2)
ip: 29-2-2012
30-2-2010
op: date-1 is latest
Method1: first compare years, if( y1>y2) then say date-1 is latest,
else if(y1<y2) then say date-2 is latest,
if y1==y2 then compare months, if months equal then compare days.
Method2: Compose date1 and date2 (3-values) into single value. (eg: k1=y1*10000+m1*100+d1)
Now compare k1 and k2 and find latest (this is simple than method1)
----------------------------------------------------------------------------------------------------------------------------------------------
32) The C-Family library charges a fine for every book late returned.
For first 10 days the fine is 5/-
For 11-20 days the fine is 15/-
For 21-30 days the fine is 25/-
For above 30days, the fine is 1/- per a day
ip: 16 ip: 45 ip:6 ip: 22
op: 15rs op: 45rs op:5rs op: 25rs
----------------------------------------------------------------------------------------------------------------------------------------------
*33) If the number of units scanned from keyboard, find electricity bill as given below tariff
tariff 1: If units <= 100
bill is 3.50/- per unit
tariff 2: if units>100 and units<=200
Upto 100 as above said, For remaining 5.00/- per unit
tariff 3: if units >200
Upto 200 as above said, For remaining 8.00/- per unit
For example:
ip: units: 78 ip: units: 123
op: bill=78*3.50  273 op: 100*3.50 + (123-100) * 5.00  465
---------------------------------------------------------------------------------------------------------------------------------------------
17 C-Family | if-else

34) Write a program to display the type of the roots of a quadratic equation given by its coefficients say a, b
and c. Here a, b and c are input numbers.
Logic: To know the type of roots of an equation, first of all evaluate the value of (b^2-4ac), let it is x
If x < 0 then print "roots are imaginary"
If x == 0 then print "roots are equal" and root1 & root2 value is -b/(2*a)
If x > 0 then print root1, root2 values are (-b+sqrt(x))/(2*a), (b+sqrt(x))/(2*a)
Note: here sqrt() is a library function, so use #include<math.h>
ip: enter a, b, c values: 2 4 2 ip: enter a, b, c values: 2 3 4
op: two roots are equal and value is -1.00 op: roots are imaginary
ip: enter a, b, c values: 2 8 3
op: root1= -0.42 and root2=-3.58
----------------------------------------------------------------------------------------------------------------------------------------------
35) Write a program to accept 3 numbers from keyboard and find any two numbers difference, the
difference must be maximum value.
ip: 10 20 50
op: maximum difference is 40
----------------------------------------------------------------------------------------------------------------------------------------------
36) If three integers are input from keyboard, write a program to print in ascending order
ip: 12 5 65
op: 5 12 65
---------------------------------------------------------------------------------------------------------------------------------------------
37) Write a program to check whether given triangle is equilateral (all sides 60^), isosceles (two sides equal),
scalene (all sides diff).
Note: sum all angles before checking, the sum should be 180, if not then show an error message.
ip: 100 80 40 ip: 50 100 30 ip: 60 60 60 ip: 50 50 80
op: invalid input op: scalene op: equilateral op: isosceles
-----------------------------------------------------------------------------------------------------------------------------------------------
38) Write a program to check whether given triangle is
case 1) equilateral
case 2) isosceles
case 3) isosceles & right angle
case 4) scalene
case 5) scalene & right angle.
ip: 50 100 30 ip: 90 30 60 ip: 60 60 60 ip: 50 50 80 ip: 45 90 45
op: scalene op: scalene+right angle op: equilateral op: isosceles op: isosceles+right angle
-----------------------------------------------------------------------------------------------------------------------------------------------
39) If date(month, year) is input through keyboard, write a program to print how many days exist in that
month. (Let us say, the input date entered by the user is a valid-date)
*February with leap year has 29 days, eg: if(month==2 && year%4==0) days=29;
*the months such as 4, 6, 9, 11 have 30-days (april, june,….etc) and all remaining are 31-days.
ip: 2 2010 ip: 2 2000 ip: 4 2000 ip: 5 2001
op: 28 days ip: 29 days ip: 30 days ip: 31 days
----------------------------------------------------------------------------------------------------------------------------------------------
18 C-Family | if-else

40) If date(d,m,y) is input through keyboard, write a program to find whether it is valid date or not
Logic: * February month has 28/29 days based on leap-year.
* the months such as 4, 6, 9, 11 have 30-days (april, june,….etc) and all remaining are 31-days.
ip: 30-2-2010 ip: 31-4-2000 ip: 30-4-2000
op: invalid date op: invalid date op: valid date
----------------------------------------------------------------------------------------------------------------------------------------------
41) If date (d, m, y) is input through keyboard, write a program to increment it by one day
(let assume input date is valid, so do not check for validity)
ip: 29-2-2012 ip: 31-12-2012 ip: 28-2-2010 ip: 2-2-2012
op: 1-3-2012 op: 1-1-2013 op: 1-3-2012 op: 3-2-2012
-------------------------------------------------------------------------------------------------------------------------------------------
42) If valid date (d, m, y) is input through keyboard, write a program to decrement it by one day
ip: 1-3-2012
op: 29-2-2012
-------------------------------------------------------------------------------------------------------------------------------------------
43) find given input date lies between 4-5-2002, 7-5-2010 or not?
ip: 1-6-2002 ip: 1-3-2002 ip: 3-4-2010 ip: 8-5-2010
op: yes op: no op: yes op: no
------------------------------------------------------------------------------------------------------------------------------------------
-44) By using following program, write a program to accept price of an item from keyboard and print in
English worlds. The price is combination of rupees & paisa. The rupees value is in 0-100 limits and paisa is in
0-99 limits.
ip: 345.67 ip: 14.67
op: three hundred twelve rupees and seven paisa. op: fourteen rupees and sixty seven paisa.

ip: 312.07
op: three hundred forty five rupees and sixty seven paisa.

//Sample program with price value : 546.78, modify this program according to your input value
void main()
{ char *a[20] = {" ", "one","two","three","four","five","six","seven","eight","nine",“ten","eleven", \
"twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen", "ninteen"};

char *b[10] = {" "," " , "twenty", "thirty", "forty","fifty","sixty","seventy","eighty","ninty"};


printf("%s hundrend", a[5]);
printf(" %s %s rupees", b[4], a[6]);
printf(" and %s %s paisa", b[7], a[8]);
}

Output of this program is: five hundred forty six rupees and seventy eight paisa
19 C-Family | Loops

Loops
Write all following programs using while-loop but not with for-loop, it improves your logic skills quickly.
Generally, when loop needs to be repeated certain number of times such as 10-times or N-times then
for-loop is recommended otherwise while loop is the choice. You can choose any loop as per your
convenient, because the compiler generates same code for all loops. After solving all programs using while-
loop, it is better to rewrite some programs in for-loop for practice. Remember, to solve these programs
nested-looping is not required.
----------------------------------------------------------------------------------------------------------------------------------------------
01) Code to print numbers from 10 to 20, here no scanf() is required, because output is fixed limits.
op: 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20
----------------------------------------------------------------------------------------------------------------------------------------------
02) Code to print N-3 to N+3, here N is input value, take from keyboard.
ip: N=10
op: 7, 8, 9, 10, 11, 12, 13
----------------------------------------------------------------------------------------------------------------------------------------------
03) Code to print “Hello” for 10 times
op: Hello Hello Hello Hello … 10 times
----------------------------------------------------------------------------------------------------------------------------------------------
04) Code to print numbers 1, 10, 100, 1000, 10000, 100000. (6 numbers)
----------------------------------------------------------------------------------------------------------------------------------------------
05) Code to print numbers 100000, 10000, 1000, 100, 10, 1. (6 numbers)
-----------------------------------------------------------------------------------------------------------------------------------------------
06) Code to accept N from keyboard and print numbers from 1 to N
Here the last value (N) should be prefixed with the word ‘and’
ip: enter n value: 14
op: 1 2 3 4 5 …….13 and 14.
----------------------------------------------------------------------------------------------------------------------------------------------
*07) Code to print N, N/2, N/4, N/8,….1, here N is input from keyboard
ip: N=100
op: 100, 50, 25, 12,6, 3, 1
-----------------------------------------------------------------------------------------------------------------------------------------------
08) Code to print 1, 2, 4, 8, ……<N, where N is input from keyboard
ip: N=200
op: 1 2 4 8 16 32 64 128
----------------------------------------------------------------------------------------------------------------------------------------------
09) Code to print 1, 2, 4, 8, ……<N & one extra value beyond N), where N is input. For example,
ip: N=100
op: 1 2 4 8 16 32 64 and 128 ( 128 extra value beyond input 100 )
---------------------------------------------------------------------------------------------------------------------------------------------
*10) Code to print 1, 2, 4, 8, ……N times, where N is input. For example,
ip: N=5
op: 1 2 4 8 16 ( N terms where N is 5)
---------------------------------------------------------------------------------------------------------------------------------------------
11) Code to accept N from keyboard and print 10 numbers before & after of a given number
ip: enter N value: 45
op: 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55
20 C-Family | Loops

--------------------------------------------------------------------------------------------------------------------------------------------
12) Code to print 1, 2, 3, 4, 5, ...10 and also print 10, 9, 8, 7, , …,3, 2, 1
Here no input statement is required, i.e, scanf() is not required as we need to print 10 fixed no.of times.
Here the two series values should be separated with the word ‘and’

logic: Write two loops, loop after loop, the first loop prints 1-to-10, whereas second loop prints 10-to-1.
op: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, and 10, 9, 8, 7, 6, 5, 4, 3, 2, 1
----------------------------------------------------------------------------------------------------------------------------------------------
13) Code to accept N from keyboard and print odd numbers from 1 to N
ip: enter n value: 15
op: 1 3 5 7 9 11 13 15
Method1: take loop variable as ‘i’ and increment it by 2 in every cycle to get next value
Method2: take loop variable as ‘i’ and increment it by 1 in every cycle, but print ‘i’ value when it is odd
for example: if(i%2==1) // write this code inside while-loop
{ printf(“%d “, i);
}
---------------------------------------------------------------------------------------------------------------------------------------------
14) Code to print 1, 2, 3, 4, 5, ...N and also print odd numbers 1, 3, 5, 7, …(2*N-1)
ip: N=10
op: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
1, 3, 5, 7, 9, 11, 13, 15, 17, 19
---------------------------------------------------------------------------------------------------------------------------------------------
15) Code to accept N from keyboard and print odd numbers from 1 to N and also print from N to 1.
ip: N=16
op: 1 3 5 7 9 11 13 15 15 13 11 9 7 5 3 1
loop: take ‘i’ as loop variable and increment it by 2 in every cycle, the loop stops when ‘i’ crossed ‘N’ and it
would be odd. if N=16 then ‘i’ stops at 17, now print odds from ‘i-2’ to 1.
or if N=15 then also ‘i’ stops at 17, so print odds from ‘i-2’ to 1.
---------------------------------------------------------------------------------------------------------------------------------------------
16) If any value N taken from keyboard, write a program to print odd numbers from N to 1.
The input value N may be odd/even entered by user.
ip: enter N value:15 ip: enter N value:16
op: 15, 13, 11, 9, 7, 5, 3, 1 op: 15, 13, 11, 9, 7, 5, 3, 1
Method1: Decrement N-- upto 0 using loop, but print N when it is odd.
Method2: 1) check N value, if N is even then do N=N-1 (to change N from even to odd).
2) Now take loop and print odds from ‘N’ to 1 by decrementing N by 2 every time
---------------------------------------------------------------------------------------------------------------------------------------------
17) Generate and print list of numbers from N to 1, Here N is input from keyboard and print list of
numbers as long as the value of N >1.
if N is even then next number of N is → N/2 (half), if N is odd then next number of N is → 3N + 1
if input N is 13, then we have to print like: 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1
the skeleton of loop as follows
while(N>1)
{ -----
if(n%2==0) ----
else -----
}
----------------------------------------------------------------------------------------------------------------------------------------------
21 C-Family | Loops

18) Code to print 1-4 , 3-7 , 5-10 , 7-13 , 9-16 , 11-19,…. for 10 times
Logic: write printf() statement as printf(“%d-%d , ”, x , y); where ‘x’ increments by 2 and ‘y’ increments by 3.
take ‘i’ for looping 10 times, starting values of x is 1, y is 4
---------------------------------------------------------------------------------------------------------------------------------------------
*19) If N is input through the keyboard, write a program to print following output.
ip: N=18
op: 1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18
logic: print new line(‘\n’) for every 5 values, for example, if(i%5==0) printf(“\n”);
-----------------------------------------------------------------------------------------------------------------------------------------------
*20) Code to print all multiples of N, which is as given below
ip: N=7
op: 7, 14, 21, 28, 35, 42, …. Up to 10 times
----------------------------------------------------------------------------------------------------------------------------------------------
21) Code to print multiplication table N, which is entered by user, the table should be displayed in the
following format
ip: enter table number: 9
op: 9*1=9
9*2=18
....
9*10=90
Hint: write printf() statement as printf(“\n %d * %d = %d”, n, i, n*i);
-----------------------------------------------------------------------------------------------------------------------------------------------
22) If two input values taken from keyboard as lower and upper limits, write a program to print numbers
from lower to upper, for example,
ip: enter lower & upper limits: 14 23
op: 14 15 16 18 19 20 21 22 23
Sometimes the input values may entered in reverse order, for example 23, 14 ( here lower>upper)
In this case, swap lower & upper before printing. (before loop)
ip: enter lower & upper limits: 30 14
op: 14 15 16 17 18 19 20 21 22 23 25 27 29
-----------------------------------------------------------------------------------------------------------------------------------------------
23) If two input values taken from keyboard as lower and upper limits, write a program to print odd
numbers between them. Sometimes the input values may entered in reverse order, for example 23, 14
(lower>upper) anyway print them in ascending order.
ip: 15 32
op: 15 17 19 21 23 25 27 29 31

ip: 14 31
op: 15 17 19 21 23 25 27 29 31

ip: 30 14
op: 15 17 19 21 23 25 27 29
----------------------------------------------------------------------------------------------------------------------------------------------
22 C-Family | Loops

24) Code to accept two limits as lower and upper ( l, u ) from keyboard and print numbers between them.
If user entered l<u then print in ascending order, but if user entered l>u then print in descending order.
ip: 15 32
op: 15 16 17 18 19 21 22 23 24 25 26 27 28 29 30 31 32

ip: 32 15
op: 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15

logic: if l<u then print numbers using increment loop, if l>u then print numbers using decrement loop. Here
we need to write two loops but need to be executed only one, which is based on l & u values.
so write first loop in if-block and second loop in else-block.
----------------------------------------------------------------------------------------------------------------------------------------------
25) Code to print 1 to 20 numbers by skipping 5, 10 and 11 numbers
For this program, the scanf() is not required, because the target number N is 20, it is fixed value.
op: 1 2 3 4 6 7 8 9 12 13 14 15 16 17 18 19 20.
Logic: it is better to use if-statement inside while-loop to skip these values.
for example: If( ! (i==5 || i==10 || i==11) ) then print(i)
or if( i==5) then i++; and if(i==10) then i=i+2;
---------------------------------------------------------------------------------------------------------------------------------------------
26) Code to print 1 to 100 numbers by skipping from 50 to 60. (No input is required)
op: 1 2 3….46 47 48 49 61 62 63 ….99 100
---------------------------------------------------------------------------------------------------------------------------------------------
27) Code to accept numbers one by one until last input value is zero, when zero is entered then stop
scanning and print sum of all values.
Ip: 12
10
4
2
0 (stop)
op: sum=12+10+4+2 28
Logic: here the scanf() statement need to be written inside while loop, because we need to scan
continuously until last input is zero. Here take while loop as infinite loop while(1) , … -, and also use ‘break’
statement to stop the loop when input is zero. Here the value ‘1’ as loop condition represents infinite loop,
off course the loop stops with ‘break’. The code as given below
void main()
{ int n, sum=0;
while(1<2) or while(1)  this loop is said to be always true, or infinite loop, but stops by ‘break’
, printf(“enter n value :”);
scanf(“%d”, &n);
if(n==0)
break; // break throws the control out of loop, i.e., it stops the loop
----
}
----
}
--------------------------------------------------------------------------------------------------------------------------------------------
23 C-Family | Loops

28) Code to accept a value ‘N’ from keyboard and the N must be between 1 to 20; if user entered mistakenly
N<1 or N>20 then show an error message called “wrong input“. (It is much like scanning passwords)
Then scan again and again until N is 1 to 20; later print multiplication table for N.
ip: enter N value:50
op: wrong input, it must be in 1 to 20, try again

ip: enter N value:22


op: wrong input, it must be in 1to 20 , try again
ip: enter N value:8 ( input is right )
op: 8*1=8
8*2=16
8*3=24 …
Method: Write 2 loops, loop after loop (not nested loop), the first loop to scan proper value (for 1-20) and
second loop to print ‘multiplication’ table.
---------------------------------------------------------------------------------------------------------------------------------------------
-29) Code to accept numbers one by one from keyboard until last input value is 0, when zero is entered then
stop scanning, later print count of -ve numbers.
ip: enter value1: 11
enter value2: -3
enter value3: 44
enter value4: 30
enter value5: 55
enter value6: -6
enter value7: -2
enter value8: 0 [ 0 is end of input ]
op: -ve count = 3
logic: 1) Use variable ‘count’ to count ‘–ve’ numbers
2) Increment ‘count’ when input(N) < 0
----------------------------------------------------------------------------------------------------------------------------------------------
30) In a school, every cricket player student have to play 6 balls, and school offering gold coins for every ball
hit, 2 coins for every run, but 10 coins for 4-boundary shot, 20 coins for six shot .
Now code to scan 6 values one by one as input and count no.of gold coins gained by student
Note: if input is -1 then player is out in the middle of 6 balls then stop scanning
Two extra cold coins if he scored more than 10 runs.
ip1: 2 ( 2 runs made for first ball, coins: 4) ip1: 2 ( 2 runs for first ball, coins:4)
ip2: 0 ( 0 runs made for second ball) ip2: 0 ( 0 runs for second ball)
ip3: 4 ( boundary shot, coins:10 ) ip3: 4 (coins:10)
ip4: 1 (single run, coins:2 ) ip4:-1 (player out)
ip5: 6 (six shot, coins:20 ) op: total runs are: 6
ip6: 0 gold coins gained: 14
op: total runs are: 13
gold coins gained: 36+2extra
---------------------------------------------------------------------------------------------------------------------------------------------
31) Code to find sum of 2+2+2+2+2+ ….N times. Here N is input value.
Condition: do not use multiplication operator (*) in the program.
ip: enter N value:5
op: output = 10
24 C-Family | Loops

---------------------------------------------------------------------------------------------------------------------------------------------
32) Code to find sum of X+X+X+X+X+ …. N times. Here X , N are input values.
Condition: do not use multiplication operator (*) in the program.
ip: enter X , N value: 3 5
op: output = 15
-----------------------------------------------------------------------------------------------------------------------------------------------
33) The sum of squares of the first ten natural numbers is, 12 + 22 + 32 + 42 ... +102 = 385
Write a program to prove it ( output is “yes” or “no”)
----------------------------------------------------------------------------------------------------------------------------------------------
34) Code to find product of 2*2*2*2*2….N times. Here N is input value.
Condition: do not use pow() function
ip: enter N value:5
op: output = 32
----------------------------------------------------------------------------------------------------------------------------------------------
35) If base(x) and exponent(y) are input through the keyboard, write a program to find x^y.
Hint: do not use pow() function.
ip: enter X,Y values: 2 3
op: output of 2^3=8
logic: multiply x*x*x … Y times
-----------------------------------------------------------------------------------------------------------------------------------------------
36) program to find sum & product of 1 to N [ 1+2+3+....+N, 1*2*3*....*N ]
logic: to find sum of 1+2+3+4+…+N, do not use formula like N*(N+1)/2
ip: N = 5
op: sum=15
product=120
-----------------------------------------------------------------------------------------------------------------------------------------------
37) program to find sum of odd numbers 1+3+5+7+9+ … N terms. (here Nth term is 2*N-1)
ip: N=5
op: 25 (1+3+5+7+9)
-----------------------------------------------------------------------------------------------------------------------------------------------
38) Code to print 1, 2, 4, 8, 16, 32, … N terms. The N is input taken from keyboard.
These values are nothing but power 2 series: 20, 21, 22, 23, 24, 25, …N times.
logic: take the variable ‘i’ for looping N times (increment ‘i’ every time by 1)
take the variable ‘p’ to produce and print 1, 2, 4, 8, 16, 32,… (multiply ‘p’ with 2 to get next value )
----------------------------------------------------------------------------------------------------------------------------------------------
39) Code to find sum of 1+2+4+8+16...N times. (20+21+22+23+ …. N times)
Hint: do not use pow() library function.
ip: enter N value : 5
op: sum=31
logic: 1. take ‘i’ for looping, where ‘i’ is 1, 2, 3, 4, 5, 6, ….N
2. take ‘p’ to generate 1, 2, 4, 8, 16, 32, ….. ( 20, 21, 22, 23, 24, 25 )
3. take ‘sum’ and add ‘p’ values to sum.
----------------------------------------------------------------------------------------------------------------------------------------------
40) Code to print X0, X1, X2, X3, X4, X5,… N times.
Here X, N are input numbers, If X is 2 then the output is like above program.
logic: take loop variable ‘i’ to repeat N times (Increment ‘i’ every time by 1)
take variable ‘p’ to produce X0, X1, X2, X3,X4, … (multiply ‘p’ with by p*x to get next value)
25 C-Family | Loops

----------------------------------------------------------------------------------------------------------------------------------------------
41) Code to find sum of X0 + X1 + X2 + X3 + ….. 5 times. Hint: do not use pow() function.
ip: enter X value : 2
op: sum=31
----------------------------------------------------------------------------------------------------------------------------------------------
42) Program to print 7, -7, 7,-7, 7, -7, …N times
logic: take ‘i’ for looping N times, increment it by 1 for N times.
take ‘V’ with 7 and print in the loop, multiply ‘V’ with -1 to change its sign for next cycle in the loop.
the sign of V alternatively changes to +ve to -ve and –ve to +ve.
----------------------------------------------------------------------------------------------------------------------------------------------
43) Program to add all these values (7) + (-7) + (7) + (-7) + …for 10 times;
if the output sum value is zero then display “program is good”
if not then display “program has some logical mistake”
----------------------------------------------------------------------------------------------------------------------------------------------
44) Program to print 1, -2, 3, -4, 5, -6, 7, …N times
logic: take a variable ‘s’ and change its value alternatively to +1, –1, +1, –1, +1, –1, …etc.
For this multiply ‘s’ with –1 in the loop, so that sign changes alternatively.
take a variable ‘i’ for looping N times, here it increments by 1.
print ‘s*i’ as output : printf(“%d “, s*i);
in the loop, the values changes as given below
‘i’  1, 2, 3, 4, 5, 6, …etc
s  +1, –1, +1, –1, +1, –1, …et
s*i  1, –2, +3, –4, +5, –6, …etc
---------------------------------------------------------------------------------------------------------------------------------------------
45) Program to print find of (1) + (-2) + (3) + (-4) + (5) + (-6) + (7) … N times
ip: enter N value: 5
op: output = 3
---------------------------------------------------------------------------------------------------------------------------------------------
46) Program to print value of each term 1/1, 1/2, 1/3, 1/4, …N times. // print(1/i)
output as : 1 0.5 .33 .25 0.2 0.16 ….
---------------------------------------------------------------------------------------------------------------------------------------------
47) Program to find sum of 1/1 + 1/2 + 1/3 + 1/4, …1/N times.
ip: N=5
op: 2.28
---------------------------------------------------------------------------------------------------------------------------------------------
48) Program to print value of each term 1/2, 2/3, 3/4, 4/5 …N times // print(i/(i+1))
output as : 0.5 .66 .75 0.8 ….
---------------------------------------------------------------------------------------------------------------------------------------------
49) 1/2 + 2/3 + 3/4 +.....+ N/(N+1) [ 0.5 + 0.66 + 0.75 + 0.8 + 0.83 + …N times ]
ip: n=5
op: sum=3.55 [ 0.5 + 0.66 + 0.75 + 0.8 + 0.83  3.55 ]
----------------------------------------------------------------------------------------------------------------------------------------------
50) Program to print value of each term 1/2, 3/4, 5/6, 7/8, … N times // print( i/(i+1) )
output: 0.5 0.75 0.83 0.87 ….
---------------------------------------------------------------------------------------------------------------------------------------------
26 C-Family | Loops

51) 1/2 + 3/4 + 5/6 + 7/8 + ..... N times [ 0.5 + 0.75 + 0.83 + 0.87 + 0.9+ …N times +
ip: N=5
op: sum=3.85 [ 0.5 + 0.75 + 0.83 + 0.87 + 0.9  3.85]
----------------------------------------------------------------------------------------------------------------------------------------------
52) 2/9 - 5/13 + 8/17 - 11/21 …. N times [ 0.2222 + -0.3846 + 0.4705 + -0.5238 + 0.5600 + …. N times ]
ip: N=5
op: sum=0.34 43 [ 0.2222 + -0.3846 + 0.4705 + -0.5238 + 0.5600  0.3443 ]
----------------------------------------------------------------------------------------------------------------------------------------------
53) One monthly creditor lends money to the customer and he wants to repay within one month,
if customer failed to repay back then he adds interest to the principle for next month. This is simple interest
for month wise but if customer failed for longer period then it goes like compound interest.
Any way show how simple interest is accumulated in every month.
for simple interest(si), the formula is : si = p*t*r/100, pprinciple, ttime, rrate of interest
Write a program to accept only principle (p) from keyboard and show how simple interest(si) is accumulated
in every month. (Show for 5 months). Let us take interest rate as 2/- and time as 1 month (do not scan r & t)
ip: principle=100000
op: after month-1 , principle=100000, interest=2000, repayment(p+si)=102000
after month-2 , principle=102000, interest=2040, repayment=104040
after month-3 , principle=104040, interest=2081, repayment=106121
after month-4 , principle=106120, interest=2122, repayment=108243
after month-5 , principle=108243, interest=2165, repayment=110408
-----------------------------------------------------------------------------------------------------------------------------------------------
54) Program to print sum of each term value 1, 1+2, 1+2+3, 1+2+3+4, 1+2+3+4+5, … N times
ip: enter N value : 7
op: 1, 3, 6, 10, 15, 21,28
Note: do not use nested-loop (using single loop we can solve it)
hint: print ‘sum’ value inside loop
-----------------------------------------------------------------------------------------------------------------------------------------------
55) find sum of (1) + (1+2) + (1+2+3) + (1+2+3+4) + .............N times ( do not use any formula or nested loop)
(1) + (3) + (6) + (10) +……………...N times
ip: N=5
op: sum=35
-----------------------------------------------------------------------------------------------------------------------------------------------
56) program to print product of each term 1, 1*2, 1*2*3, 1*2*3*4, 1*2*3*4*5, …N times
in mathematics, this sum is expressed as: 1!, 2!, 3!, 4!, 5!, 6!, …. N times
ip: enter N value : 7
op: 1, 2, 6, 24, 120, 720, 5040
Note: Do not use nested-loop (using single loop we can solve it)
-----------------------------------------------------------------------------------------------------------------------------------------------
57) program to find (1)+(1*2)+(1*2*3)+(1*2*3*4)+ (1*2*3*4*5) .............N times (1!+2!+3!+ …..N!)
1 + 2 + 6 + 24 + 120 + ………………..N times
ip: N=5
op: sum=153
-----------------------------------------------------------------------------------------------------------------------------------------------
27 C-Family | Loops

58) Program to print product of each term 1, 1*2*3, 1*2*3*4*5,…N times


ip: enter N value : 7
op: 1, 6, 120, 5040
Note: Do not use nested-loop and do not use ‘if-statement’ in the loop to check odd number.
logic: take ‘p’ to generate odd factorials, here multiply ‘p’ with (i)*(i+1) to get next fact value.
Increment loop variable ‘i’ by 2 every time to get next odd number in the loop.
----------------------------------------------------------------------------------------------------------------------------------------------
59) 1!+3!+5!+7! ......+2N-1!
ip: N=4
op: sum=5167 ( 1 + 6 + 120 + 5040 )
----------------------------------------------------------------------------------------------------------------------------------------------
60) X1/1! + X2/2! + X3/3!..... N times [ do not use pow() fn ]
ip: x=3, N=5
op: sum= 17.4 [3.0 + 4.5 + 4.5 + 3.375 + 2.025  17.4]
----------------------------------------------------------------------------------------------------------------------------------------------
**61) X1/1! - X3/3! + X5/5! - X7/7! ..... 5 times. [ sine series ]
ip: x=3, N=5
op: sum=0.1453 [ (3.0) + (-4.5) + (2.025) + (-0.4339) + (0.05424) ]
-----------------------------------------------------------------------------------------------------------------------------------------------
62) Program to accept a number ‘N’ through keyboard and find whether it is power of 2 or not?
ip: 8 ip: 18
3
op: yes (2 ==8) op: no

Logic1: 1) cut down N=N/2 as long as N is even


2) finally, after loop, if N==1 then say “yes”, or else, say “no”
for example, if N=20 then N=N/2 is 20, 10, 5 ( here N==1 is false so print “no”)
for example, if N=16 then N=N/2 is 16, 8, 4, 2, 1 ( here N==1 is true so print “yes ”)

Logic2: Repeatedly Compare N with 20, 21, 22, 23, 24, 25 ... Until 2i<N
Finally if N==2 i then say “yes”, if not then say “no”.
-----------------------------------------------------------------------------------------------------------------------------------------------
63) Program to accept a number ‘N’ from keyboard and find whether it has perfect square root or not?
ip: 16 ip: 15
op: yes (4^2) op: no
2
Logic: 1) Repeat the loop until i <N where i=1, 2, 3, 4, 5,…
2) after completion of loop, if N==i2 then say “yes” or else “no”
-----------------------------------------------------------------------------------------------------------------------------------------------
64) If the number 'N' is input through the keyboard, write a program to print all factors of N and also count
total number of factors.
Logic: to find factors of N, check N by dividing with all possibility from 1, 2, 3, 4 ... N.
if N%i==0 then ‘i’ is a factor of N. the loop repeats as given below
if(N%1==0) then ‘1’ is factor of N
if(n%2==0) then ‘2’ is factor of N
if(n%3==0) then ‘3’ is factor of N
in this way check with all possibilities from 1 to N.
ip: enter n value:18
op: 1, 2, 3, 6, 9, 18
Count of factors= 6
28 C-Family | Loops

---------------------------------------------------------------------------------------------------------------------------------------------
65) program to accept a number ‘N’ and find whether it is perfect or not?
Perfect: if sum of all factors is equal to given ‘N’ then it is said to be perfect. (don’t take ‘N’ as factor)
Logic: Check for factors from 1 to N/2 and add all divisible to variable ‘sum’.
For example: 6 (1+2+36), 28(1+2+4+7+1428)
ip: enter N value: 6 ip: enter N value: 7 ip: enter N value: 28
op: yes op: no op: yes
----------------------------------------------------------------------------------------------------------------------------------------------
66) if we list all natural numbers below 10 that are multiples of 3 and 5, we get 3, 5, 6 and 9.
The sum of these multiples is 23, prove it by program. Output: yes/no
----------------------------------------------------------------------------------------------------------------------------------------------
67) program to print how many ways the input ‘N’ can be written in multiples
ip: N=100
op: 100 * 1 =100
50 * 2 = 100
25 * 4 = 100
20 * 5 = 100
10 * 10 = 100
Method: Check for factors of N from 1, 2, 3, 4, 5,… until i<=N/i, and print output as above shown.
use printf() statement as printf(“\n %d * %d = %d”, n/i, i, n);
----------------------------------------------------------------------------------------------------------------------------------------------
68) If N is input through the keyboard, write a program to print small factor other than 1.
ip: enter N value:18 ip: enter N value:15 ip: enter N value:35
op: output is :2 op: output is :3 op: output is :5
logic: for small factor, divide N with 2,3,4,5,…N, that is check with all possibilities from 2 to N, which ever
divides first then it is small factor and stop the loop.
-----------------------------------------------------------------------------------------------------------------------------------------------
69) If N is scanned through the keyboard, write a program to print big factor other than N.
logic: divide N with N/2 to 1, that is check with all possibilities from N/2 to 1 in reverse order, which ever
divides first then it is big factor.
Hint: Generally, for any number, the possible factors lies in range 1,2,3,…N/2, N/2+1, N/2+2……N-1,N. That
is , there should not be factors after N/2 except N.
for example, if we take 100 then possible factors are 1,2,3,4,5,…48,49,50,51,52,53,…98,99,100.
The value 100 never divides with 51, 52, 53,…97, 98, 99 so it is useless to check with these numbers.
Here we need to find big factor other than N, so it is wise to check from N/2 to 1.
----------------------------------------------------------------------------------------------------------------------------------------------
29 C-Family | Loops

**70) In examinations, interviews, viva,…etc there always one program being asked, that is, none other
than “prime number logic”. Write a program to find the given number N is prime or not.
Prime numbers divide only with 1 & itself (ie., they do not divide with any other number except 1 & N )
ip: n = 17 ip: n = 18
op: yes, it is prime op: no, it is not prime
Logic1: As we discussed earlier, for any number, factors lie between 2 to N/2 (by excluding 1 & itself).
There should not be factors after N/2, so it is wise to check prime-ness from 2 to N/2 instead of all. During
checking process, if N is divided then stop the loop and say “not prime”. If not divided till end then say
“prime” A beginner write prime number logic wrongly as
i=2;
while( i <= N/2 )
{ if(N%i==0)
printf(“\n not prime”);
else
printf(“\n prime”);
i++;
}
ip: N=15 ( many outputs )
op: prime // when 15%2==0 is false
not prime // when 15%3==0 is true
prime // when 15%4==0 is false
not prime // when 15%5==0 is true
prime // when 15%6==0 is false
prime // when 15%7==0 is false
Note: to solve this problem properly, better to use boolean logic, there several other logics to find prime-
ness, but this Boolean logic is standard and best, the code as given below
i=2;
bool=1; // assume ‘N’ is prime, so take bool as 1 (true).
while(i<=N/2)
{ if(N%i==0)
{ bool=0; // here N is divided, therefore N is not prime, so set bool to 0 (false)
break;
}
i++; // if N is divided then check with next ‘i’ value
}
}
Logic2: Count all factors of N, i.e., divide N with all numbers from 1 to N and count them
if factors count==2 then say it is “prime” or else “not prime”. (This is simple logic but takes much
time)
--------------------------------------------------------------------------------------------------------------------------------------------
30 C-Family | Loops

71) program to find the digit '5' exist in a given number or not?
ip: 4356 ip: 346 ip: 4455
op: 5 is exist op: 5 is not exist op: 5 is exist
logic: Extract digit by digit from N and check whether it is ‘5’ or not, for that divide N continuously with 10
and collect remainders one by one, the remainders are nothing but digit after digit from last to first in N, and
check this digits with 5, this is easiest method compared to all other methods.

A beginner write logic wrongly as


while(N>0)
{ rem=N%10; // get last digit in N.
if(rem==5) // check it is 5 or not
printf(“\n5 is exist “);
else
printf(“\n5 is not exist”);
N=N/10; // remove last digit from N, this is to get next digit in next cycle
}
If input N is 2356, then above program shows wrong output as ( we want only single output )
output is: 5 is not exist ( for 6)
5 is exist ( for 5 )
5 is not exist ( for 3 )
5 is not exist ( for 2 )
use ‘boolean’ or ‘count’ logic to solve this problem, this is as said in above program.
----------------------------------------------------------------------------------------------------------------------------------------------
72) Write a program to find sum of all digits in a given number.
ip: 2345 ip: 456 ip: 23456
op: 14 (2+3+4+5) op: 15 (4+5+6) ip: 20 (2+3+4+5+6)
logic: Like above program, extract digits one by one from N, and add them to variable ‘sum’
1. R=N%10
2. sum=sum+R
3. N=N/10
4. Repeat these 3 steps until N>0
-----------------------------------------------------------------------------------------------------------------------------------------------
73) Write a program to find sum of even & odd digits separately in a given number.
ip: 12453
op: even digits sum = 6 (2+4)
odd digits sum = 9 (1+5+3)
logic: Take two variable to sum up separately, for example, sumOfEvens, sumOfOdds
-----------------------------------------------------------------------------------------------------------------------------------------------
74) Code to find sum of even & odd positions digits in a given number (right to left). Let N is: 789453

7 8 9 4 5 3
6 5 4 3 2 1
(even place) (odd place) (even place) (odd place) (even place) (odd place)
ip: 789453
op: even place digits sum = 7 (5+9+7)
odd place digits sum = 9 (3+4+8)
----------------------------------------------------------------------------------------------------------------------------------------------
31 C-Family | Loops

75) Write a program to print first digit of given number.


ip: 2345 ip: 456
op: 2 op: 4
logic: repeatedly divide N=N/10 until N>9, finally N contains first digit.
----------------------------------------------------------------------------------------------------------------------------------------------
76) Write a program to print sum of first and last digits of a given number.
ip: 2345 ip: 43 ip: 7
op: sum=7 (2+5) op: 7 (4+3) op: 7
step1: assign last digit to variable ‘sum’ * sum=n%10+
step2: now remove all digits except first digit from N, like above said.
step3: at this moment N contains first digit, now add N to ‘sum’
step4: print(sum)
-----------------------------------------------------------------------------------------------------------------------------------------------
77) Write a program to print first odd digit in a given number (take right to left), if odd digit not exist then
print the message “odd not found”.
ip: 23456 ip: 2468
op: 5 op: odd digit not found
-----------------------------------------------------------------------------------------------------------------------------------------------
78) Write a program to print last odd digit in a given number (take right to left), if no odd digit exist then
print message “no odd digit found”.
ip: 23451 ip: 2468
op: 3 op: odd digit not found
-----------------------------------------------------------------------------------------------------------------------------------------------
79) Write a program to find big & small digit of a given number.
ip: 2715
op: big=7 , small=1
logic: take variable called ‘big’ with value zero, now compare each digit(D) with ‘big’ , if big<D then take D
into ‘big’, finally ‘big’ contains bigger value. Likewise find ‘small’ also.
----------------------------------------------------------------------------------------------------------------------------------------------
-80) Write a program to find second big digit in a given number.
ip: 2751 ip: 5555
op: 5 op: 5
---------------------------------------------------------------------------------------------------------------------------------------------
81) Write a program to find reverse of given number
ip: 2345
op: 5432
step1: Let N is input number, take REV to store reverse value. Initially set REV to zero.
step2: get last digit(D) from N and insert it into REV by doing REV=REV*10+D
step3: to get next digit from N, now remove current last digit from N by doing N=N/10
step4: repeat step2, step3 until N>0
REV = REV * 10 + n%10 ( here D=N%10)
= 0 * 10 + 5  5
= 5 * 10 + 4  54
= 54 * 10 + 3  543
= 543 * 10 + 2  5432
= 5432
----------------------------------------------------------------------------------------------------------------------------------------------
32 C-Family | Loops

*82) Write a program to find whether the given number is palindrome or not. If the number and its reverse
are equal then it is said to be palindrome
ip: 1221 ip: 1234
op: palin-drome. op: not palin-drome
Logic: After finding reverse of a given number like above said, the value of N becomes 0, because in the loop
the instruction N=N/10 makes the N value to zero. So before looping, store N value into some variable like
‘temp’, after finding reverse of N, compare reverse(REV) with ‘temp’ to check palindrome.
----------------------------------------------------------------------------------------------------------------------------------------------
*83) If a number is input through the keyboard, write a program to find Armstrong or not
Logic: If sum of cubes of each digit of given number is equal to the number itself,
Then it is called Armstrong number. eg: 153= (1*1*1)+(5*5*5)+(3*3*3)
ip: 153 ip: 445
op: "yes, the number is an Armstrong" op: “no, the number is not Armstrong”
----------------------------------------------------------------------------------------------------------------------------------------------
84) Write a program to print given number in English words.
ip: 2345 ip: 415
op: two three four five op: four one five
step 1: take ‘p’ and generate its value to 10C-1, where ‘C’ is no.of digits in input N.
if N=123, then p=100
if N=4567 then p=1000
the code to generate ‘p’ value as
p=1;
while(N/p>9)
{ p=p*10;
}
step 2: extract digit by digit in N from left to right, for that divide N with ‘p’ and collect the quotient.
q=N/p [ if N=2345, q=2345/1000, then q=2 ]
step 3: print ‘q’ in English words
if(q==0) printf(“zero”)
else if(q==1) printf(“one”)
else if(q==2) printf(“two”)
else if(q==3) printf(“three”) …
step 4: remove first digit from N, for that divide N with ‘p’ and collect the remainder to N itself.
N=N%p [ N=2345%1000  N=345 ]
step 5: down the p value to p=p/10; because N contains 3-digits now
step 6: repeat step-2 to step-5 until p>0
---------------------------------------------------------------------------------------------------------------------------------------------
85) Write a program to subtract ‘1’ from all digits. If input is: 4056, then output is: 2945
step1: take ‘p’ and generate its value based on input N. for example,
if N=123 then generate ‘p’ to 111 * here N has 3 digits +
if N=1234 then generate ‘p’ to 1111 [ here N has 4 digits ]
step2: now subtract ‘p’ from N [ 4056-1111  2945]
step3: print N value.
----------------------------------------------------------------------------------------------------------------------------------------------
-86) Write a program to accept a number and print after swapping first and last digit of a number.
ip: 2345
op: 5342
33 C-Family | Loops

---------------------------------------------------------------------------------------------------------------------------------------------
*87) Write a program to find given number is valid binary or not?
ip: 1101 ip: 1201
op: yes, valid binary op: no, not valid binary
logic: extract each digit from N like above said problems, if any digit>1 then stop the loop and say “it is not
valid”. (use bool logic)
---------------------------------------------------------------------------------------------------------------------------------------------
**88) Write a program to find decimal number from given binary number
ip: 1101
op: 13
step1: multiply all digits of N with 20, 21 , 22 , 23 , 24… from right-to-left
step2: The sum of all such products forms a decimal number.
step3: to get values of 20 , 21 , 22 , 23… do not use pow() function, use ‘p’ and multiply it with 2.

1 1 0 1  1*23 + 1*22 + 0*21 + 1*20  13


23 22 21 20 8 + 4 + 0 + 1
---------------------------------------------------------------------------------------------------------------------------------------------
**89) Write a program to find binary number of a given decimal number
ip: 13
op: 1101
2 13
2 6- 1
2 3- 0
2 1- 1
0- 1
103*1 + 1 02*1 + 101*0 + 100*1
L  R

Logic: divide continuously N with 2, and collect remainders(R), after getting each R, multiply with 10 i and add
to ‘sum’ variable. [ here i=0,1,2,3,4,5,…+. Do not use pow() fn.
---------------------------------------------------------------------------------------------------------------------------------------------
90) Write a program to find hexadecimal number(N) from a given binary number
ip: 370359 ip: 159
op : 5A6B7 op: 9F

Repeatedly divide the N with 16, and collect(add) the remainders into variable ‘sum’
1. Remainder is N%16
2. Add Remainder to sum, like sum=sum*100+remainder
3. cut N to N/16
4. Repeat these steps until N>0
Let N=370359

16 370359
16 23147  7 0*100+7  7
16 1446  11 (B) 7*100+11  711
16 90  6 711*100+6  71106
16 5  10(A) 71106*100+10  7110610
 5 7110610*100+5  07 11 06 10 05
The hexadecimal value collected in ‘sum’ in as  07 11 06 10 05 (7B6A5)
but output should be displayed as  5A6B7 (extract 2-digit at a time right-to-left from ‘sum‘ and print)
use two loops, one to generate ‘sum’ and second to print in hexadecimal form.
----------------------------------------------------------------------------------------------------------------------------------------------
34 C-Family | Loops

*91) Write a program to print Fibonacci series up to 10 terms.


process: The first two terms in this series are 0, 1 and remaining values generated by adding previous two
values: 0 1 1 2 3 5 8.....
step1: Let us take first two terms are x=0, y=1;
step2: Print the term ‘x’.
step3: Generate next term by adding ‘x+y’ to ‘new’
step4: Now advance ‘x’ to ‘y’ and ‘y’ to ‘new’ for next cycle
step5: Repeat this process for ‘N’ times
Let us see how the x, y are advancing in every iteration of loop

Iteration-1 0 1 1 2 3 5 8…
X Y new=x+y

Iteration-2 0 1 1 2 3 5 8…
X y new=x+y

Iteration-3 0 1 1 2 3 5 8…
x Y new=x+y

----------------------------------------------------------------------------------------------------------------------------------------------
92) Write a program to print Fibonacci series values which are in between two given limits.
ip: n=10 150
op: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 84, 139, 223, 362, 585
----------------------------------------------------------------------------------------------------------------------------------------------
93) Program to print given number is in Fibonacci series or not?
ip: n=13 ip: 14
op: yes, it is in series op: no, not in series
----------------------------------------------------------------------------------------------------------------------------------------------
94) Write a program to find GCD of two numbers. (GCD/HCF  Greatest Common Divisor)
ip: 12, 18
op: 6
1.let x, y are input values
2.divide ‘y’ with ‘x’ (irrespective of which is big and which is small)
3.if remainder(R) is zero then stop and print ‘x’ as GCD
4.if R is not zero then take ‘x’ as ‘y’ and ‘R’ as ‘x’ and continue this process until R is zero.

---------------------------------------------------------------------------------------------------------------------------------------------
35 C-Family | Loops

95) Write a program to find LCM of 3 numbers


ip: 12 18 45
op: 180
1. Let x, y, z are three input numbers
2. Start finding LCM of three with first factor 2
3. Now divide each x, y, z with 2, and decrement all divisible numbers to quotient obtained in the division.
For example, if x is divided with 2 then decrement x=x/2
4. If any x, y, z is divided in step3 then take 2 as factor in LCM. (LCM=LCM*2)
5. Now repeat step-3, step-4 as long as 2 divide any x, y, z
6. if 2 no longer divided, then next try with next factors 3, 4, 5…etc,
repeat this process until any of these (x, y, z) > 1. for example, while(x>1 || y>1 || z>1) ,….-
Let the numbers are 20, 15, 35 and following table shows how …

2 20 15 35

2 10 15 35
5 15 35
2, 3

3,4,5 5 5 35

5,6,7 1 1 7
1 1 1

----------------------------------------------------------------------------------------------------------------------------------------------
96) Program to print prime factors of given N. (The product of factors should be equal to N)
ip: N=100
op: 2 2 5 5
step1: divide N with first factor 2, the number 2 is prime.
if N is divided with 2 then print(2) as prime factor and decrement N to N/2.
step2: repeat step1 as long as ‘2’ divides the N.
step3: Now take 3 and proceed as long as 3 divides the N, as said in step1. Of course ‘3’ is also prime.
step4: Now take 4, we know 4 is not prime, but 4 will not be divided the N because we already did with 2
before, so there should not be 2 multiples left behind in N. [you may ask one question, why to divide with
4 when it is not prime, because it is difficult to take only primes, taking only primes is another problem.
So continuously/blindly divide the N with 2,3,4,5,6,7,8,9 ….]
step5: repeat this process until N>1
----------------------------------------------------------------------------------------------------------------------------------------------
97) Program to print prime factors of given N. The process is same as above program but don’t repeat
factors more than once. ( not like 2, 2, 5, 5)
ip: N=100
op: 2 5
logic: Here take extra variable ‘prev’ to store previous value of ‘i’ in the loop(for first time, take prev=1 )
if(n%i==0) {
if(prev!=i) // if previous printed factor is not equal to current factor then print
{ printf(“ i as factor “);
prev=i; // take this current ‘i’ value as ‘prev’ for next cycle
}
n=n/i ;
}
----------------------------------------------------------------------------------------------------------------------------------------------
36 C-Family | Loops

98) Write a program to find square root of a given number


Use Babylonian method of guess and divide, and it truly is faster. (Scientist name)
It is also the same as you would get applying Newton's method.
See for an example, how to find it
The square root of 20 using 10 as the initial guess (n/2)
Guess Divide Find average
• 10 20/10 = 2 average 10 and 2 to give new guess of 6
• 6 20/6 = 3.333 average 3.333 and 6 gives 4.6666
• 4.666 20/4.666= 4.1414 average 4.666,4.1414= 4.4048
• 4.4048 20/4.4048=4.5454 average = 4.4700
• 4.4700 20/4.4700=4.4742 average = 4.4721
• 4.4721 20/4.4721=4.47217 average = 4.47214
repeat this process until previous & current guess values are same in the looping.
-----------------------------------------------------------------------------------------------------------------------------------------------
99) Write a program to accept date from keyboard and check whether it is valid or not, if not then scan
again & again till user entered a valid date, finally print the date.
ip: 31-2-2001 ip: 21-2-2001
op: invalid date, try again op: yes, valid date
-----------------------------------------------------------------------------------------------------------------------------------------------
100) Write a program to accept a valid date from keyboard and increment it by N days.
ip: 1-1-2009 and 366
op: 2-1-2010
logic: step1: take loop for N times
step2: increment date by 1-day every cycle in the loop.
step3: after looping, print date.
----------------------------------------------------------------------------------------------------------------------------------------------
-101) Write a program to accept a valid date from keyboard and decrement it by N days.
ip: 1-3-2010 and 366
op: 28-2-2009
----------------------------------------------------------------------------------------------------------------------------------------------
102) Accept two-dates from keyboard and print their difference in days, let the two dates are valid.
Algorithm:
step1: let two dates are date1, date2 [ take date1 as  d1, m1, y1 ; take date2 as  d2, m2, y2 ]
step2: Let date1 < date2, if not then swap them
step2: take loop and repeatedly increment date1 by 1 day until it reached to date2, the logic as
while(d1<d2 || m1<m2 || y1<y2)
{ count++; // to count diff in days
d1++;
-----
-----
}
ip: date1 = 1-1-2009
date2 = 2-1-2010
op: difference = 366
----------------------------------------------------------------------------------------------------------------------------------------------
37 C-Family | Loops

-103) Write a program to accept a date from keyboard and find day of the week.
simple logic: Take one fixed date like your birth day; find diff between your birth date and given input date,
after finding difference in days, divide it with 7, if remainder is zero then that day is exact day of your birth
day, if remainder is 1, that day is next day to your birth day, in this way you can find day of the week. Ensure
that your input-date should be greater than birth-date.
ip: 10-5-1973
op: "Thursday"
logic: there is a scientific formula to solve this problem in simple way, google it.
---------------------------------------------------------------------------------------------------------------------------------------------
-104) Write a program to accept month and year from keyboard and print calendar of that month.
Logic: Using previous program we can solve easily.
--------------------------------------------------------------------------------------------------------------------------------------------
38 C-Family | Nested Loops

Nested Loops
Solving the following patterns makes the programmer command over the nested loops, thereafter we
can easily handle complex data like 2D arrays such as matrices, strings, files, calendar, networks routing
for shortest path, etc.
1) produce the following output pattern 2)

3456789 9876543
3456789 9876543
3456789 9876543
----------- -----------
----------- -----------
8 rows 8 rows

3) 4)

12345678 123456789
2345678 12345678
345678 1234567
------- -------
78 12
8 1

5) 6)

987654321 987654321
98765432 87654321
9876543 7654321
987654 654321
------- -------
------- -------

7) 8)

9 9
98 89
987 789
9876 6789
98765 56789
----------- ----------
987654321 123456789

9) 10)

1 1
12 21
123 321
1234 4321
12345 54321
---------- -------
8 rows 8 rows
39 C-Family | Nested Loops

11) 12)

1111111 8888888
2222222 7777777
3333333 6666666
4444444 5555555
----------- -----------
8 rows 1111111
13) 14)

1 88888888
22 7777777
333 666666
4444 55555
55555 -------
--------- 22
8 rows 1
15) 16)

1234554321 1234567887654321
1234554321 12345677654321
1234554321 123456654321
1234554321 12345554321
1234554321 12344321
---------------- 123321
8 rows 1221
11
17) 18)

11 1
1221 121
123321 12321
12344321 1234321
1234554321 123454321
123456654321 12345654321
--------------------- ---------------
--------------------- ---------------
8 rows 8 rows
19) 20)

A 1 2 3 4 5
AB 6 7 8 9 10
ABC 11 12 13 14 15
ABCD 16 17 18 19 20
ABCDE ----------------
------------- ----------------
------------- 8 rows
8 rows
40 C-Family | Nested Loops

21) 22)

1 *
2 3 **
4 5 6 ***
7 8 9 10 ****
------------- ---------
8 rows 8 rows
23) 24)

1 9 9 9 9 9 9 9 9 9
2 2 8 8 8 8 8 8 8 8
3 3 3 7 7 7 7 7 7 7
4 4 4 4 6 6 6 6 6 6
5 5 5 5 5 5 5 5 5 5
----------------- …..…
------------------ ……
8 rows
25) 26)

1 1
222 222
33333 33333
4444444 4444444
555555555 555555555
---------------- 4444444
8 rows 33333
222
1
27) 28) ip: n=5

555555555 1 1 1 1 1
4444444 2 2
33333 3 3
222 4 4
1 5 5 5 5 5
222
33333
4444444
555555555

29) 30)

ABCDEFGFEDCB A ip: 4315


ABCDEF FEDCB A op: *****
ABCDE EDCBA *
AB C D DCB A ***
ABC CBA ****
AB BA
A A
41 C-Family | Nested Loops

31) 32)
ip:5263 1
op: ***** 01
** 010
****** 1010
*** 10101
010101
0101010
----------
8 rows
33) Pascal triangle 34)
1 1 2 3 4 5
1 1 10 9 8 7 6
1 2 1 11 12 13 14 15
1 3 3 1 20 19 18 17 16
1 4 6 4 1 21 22 23 24 25
1 5 10 10 5 1 ….
1 6 15 20 15 6 1 N rows
35) 36)
Write a program to generate all combinations
of 1, 2, 3 using three nested loops.
Output:
123
132
213
231
321
312
37) Write a program to print multiplication tables from 1 to 20 and each table with 10 terms

38) Write a program to print multiplication tables from 1 to 20 by skipping 5,10,11 and 15 tables
[use continue statement]

39) write a program to print multiplication tables from 1 to 20 by skipping 5 th term in each table
and also skip 5,10,11 and 15 tables;

40) Write a program to print sum of factorials of each digit in a given number
ip: 241
op: 2!+4!+1!=>2+24+1=>27

41) Write a program to print factors of prime numbers from 50 to 100


Output should be printed as given below

42) Write program to print palindrome numbers in between 100 to 1000


op:101, 111, 121, 131, … 1001

43) By listing the first six prime numbers 2,3,5,7,11, and 13, we can see that the 6th prime is 13.
What is the 27th prime number?

44) Write a program to print twin-prime numbers from 2 to 100


Twin means 3-5, 5-7, 11-13, … (difference is 2)
42 C-Family | Nested Loops

45) Write a program to accept a number and add up all digits until the number gets single digit;
for example
19999=>1+9+9+9+9=>37
37=>3+7=>10
10=>1+0=>1
46) Write a menu driven program to find given number is odd/even, Palindrome, Prime, Armstrong,
and perfect or not;
Even: The number is divisible by 2 (remainder is zero)
Palindrome: If ‘n’ and its reverse are equal then it is called palindrome
Prime: The number has no divisible other than 1 and itself
Armstrong: sum of cubes of digits equal to given number (153  1^3+5^3+3^3  153)
Perfect: sum of factors equal to given number like 6 (1+2+36)
While executing the program, the menu appeared as given below
Menu run
==========================
1. Even/add
2. Palindrome
3.Prime or not
4.Armstrong
5. Perfect
0.exit
Enter choice [1,2,3,4,5,0]:

47) The prime factors of 13195 are 5, 7, 13 and 29.


What is the largest prime factor of the number 50001?

48) A palindromic number reads the same both ways. The largest palindrome made from the
product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers.

49) A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
a2 + b2 = c2
For example, 32 + 42 = 9 + 16 = 25 = 52. ( 32 + 42 = 52 )
There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product a,b,c.
43 C-Family | Arrays

1D-Arrays
01) Code to accept 5 values from keyboard and find at least one value is –ve or not?
ip: 4 6 -13 11 -5 ip: 4 6 13 11 5
op: yes, -ve exist op: no, -ve not exist
Logic: if any value a[i]<0 then –ve exist, or else not.
----------------------------------------------------------------------------------------------------------------------------------------------
02) Code to read 5 values to array, and find whether they are in ascending or not?
ip: 12 15 19 22 31 ip: 12 15 22 19 31
op: yes, in ascending order op: no, not in ascending order
Logic: compare a[i] with a[i+1] for all i=0,1,2,3. If any a[i]>a[i+1] then not in ascending order.
---------------------------------------------------------------------------------------------------------------------------------------------
03) Code to fill array with Fibonacci series for 20 values, let initialize array with first two values of Fibonacci
series and remaining numbers generate using loop by adding like a[2]=a[0]+a[1], a*3+=a*1++a*2+,… Finally
print all 20 Fibonacci numbers.
void main()
{ int a[20]={0,1}; // first two values of series are initialized
----------
}
op: a[ ] ={0,1,1,2,3,5,8,13,21, 34, 55,84,...};
---------------------------------------------------------------------------------------------------------------------------------------------
-04) Code to accept 5 values from keyboard and change even numbers to next odd in the array
ip: 4 7 12 17 10
op: 5 7 13 17 11
---------------------------------------------------------------------------------------------------------------------------------------------
05) Code to accept 5 values from keyboard and count number of 3 divisible
ip: 4 6 11 12 5 ip: 4 16 13 11 5
op: count=2 op: count=0
---------------------------------------------------------------------------------------------------------------------------------------------
06) Code to accept N values from keyboard and print sum, average and big of them.
ip: 4 6 3 1 5
op: sum = 16 ( 4+6+3+1+5)
average = 3.2
big = 6
---------------------------------------------------------------------------------------------------------------------------------------------
07) Code to accept N values from keyboard and count pair of adjacent elements
ip: 14, 10, 9, 10, 10, 8, 8, 8, 11, 10, 17, 17, 17, 17, 17, 20.
op: count=4
note: if 3 pair of elements found in adjacent places then take them as one pair, for example the value 8.
--------------------------------------------------------------------------------------------------------------------------------------------
08) Code to accept N values from keyboard and check whether one number divides with any other number
in the array or not? Finally count such divisible numbers ( use nested loop )
ip: 5 15 4 28 11 // 15 divides with 5, 28 divides with 4
op: count = 2 ( the numbers are 15, 28)
---------------------------------------------------------------------------------------------------------------------------------------------
44 C-Family | Arrays

09) Code to accept 5 values one by one from keyboard, while scanning values, the next input should not be
less than previous value, if user entered by mistake then reject it. Observe following ip/op
input: enter value 1: 12
enter value 2: 16
enter value 3: 7
the input value ‘7’ is rejected (because it is less than previous value)
enter value 3: 19
enter value 4: 23
enter value 5: 31
output: 12 16 19 23 31 [ try: try this program with single scanf() statement.]
---------------------------------------------------------------------------------------------------------------------------------------------
10) Code to accept 5 values one by one from keyboard, do not allow duplicate values.
input: enter value 1: 12
enter value 2: 16
enter value 3: 12
the input value ‘12’ is duplicate (already entered), rejected
enter value 3: 19
enter value 4: 23
enter value 5: 30
output: 12 16 19 23 30
---------------------------------------------------------------------------------------------------------------------------------------------
11) Code to accept N values from kb and print each number multiples as shown below (use nested-loop)
ip: 14 16 13 11
op: 14 => 1, 2, 7, 14
16 => 1, 2, 4, 8, 16
13 => 1, 13
--------------------------------------------------------------------------------------------------------------------------------------------
12) Code to accept 5 values to array and print only primes ( Nested loop required )
ip: 11 17 21 31 15
op: the primes are: 11, 17, 31
---------------------------------------------------------------------------------------------------------------------------------------------
13) Code to accept 5 values to array and print reverse of each number ( use nested loop )
ip: 123 21 529 1312 6578
op: 321 12 925 2131 8756
---------------------------------------------------------------------------------------------------------------------------------------------
14) A shop keeper sells 10 items from his stock inventory, item’s code ranges from 1 to 10, and customer
buy items by asking item-code and quantity, this is as given below, finally calculate bill amount
Input: Enter item-code & quantity: 2 5
Enter item-code & quantity: 4 2
Enter item-code & quantity: 1 1
Enter item-code & quantity: 0 (stop when item code zero)
output: total bill calculated as 5*10.30 + 2*9.20 + 1*44.50
Note: The sample price list of each item already stored in the array as given below, use array to find bill

Price[0] Price[1] Price[2] Price[3] Price[4] Price[5] Price[6] Price[7] Price[10]


Dummy 44.50 10.30 14.50 9.20 14.50 34.80 10.00 …. 90.00
No item Item1 Item2 Item3 Item4 Item5 Item6 Item7 …. Item10
--------------------------------------------------------------------------------------------------------------------------------------------
45 C-Family | Arrays

15) A quiz participating by 10 players, for every answer they get 1 point, during quiz play we have to record
each player score, and finally print their scores; Let player numbers are 1, 2, … 10.
The input is players number one by one who answered the questions during play,( last input 0 to stop game)
and finally print each player score who answered.
input : 4 ( player-4 answered the question-1)
7 ( player-7 answered the question-2)
9 ( player-9 answered the question-3)
4 ( player-4 answered the question-4)
7 ( player-7 answered the question-5)
7 ( player-7 answered the question-6)
0 ( end of game)
output: player-4 answered 2 questions and score is 2
player-7 answered 3 questions and score is 3
player-9 answered 1 questions and score is 1
Process: take array called score[] with size 10 and initialize with zero for every cell, later increment cell’s of
score[] where its index is player-no, for example, score[ player-no ]++. Later print all such incremented cells.
This is as given below

dummy 0 0 0 2 0 0 3 0 1 0
score[0] score[1] score[2] score[3] score[4] score[5] score[6] score[7] score[8] score[9] score[10]
----------------------------------------------------------------------------------------------------------------------------------------------
16) If marks are collected from <=100 students for an exam, maximum marks can be obtained by student is
10, write a program to scan N students marks to an array, and count how many students obtained 10 marks,
9 marks, 8 marks,… 0 marks.
let us initialize array with sample values(marks) instead of scanning from Keyboard (here 16 values)
int marks[100]={3 , 4 , 9 , 10 , 4 , 2 , 3 , 0 , 5 , 7, 8 , 7, 8, 0, 9, 9 };
10 – marks obtained by 1 students
9 – marks obtained by 3 students
8 – marks obtained by 2 students …
Process: take array count[] with size 10 and initialize with zero in every cell, later increment cell’s of count[ ]
where its index is input marks, for example count[ marks[i] ]++

2 0 1 4 …
count[0] count[1] count[2] count[3] count[4] count[5] count[6] count[7] count[8] count[9]

---------------------------------------------------------------------------------------------------------------------------------------------
17) In a C-Family college, marks are collected from <=100 students for an exam, the maximum marks is 100
and collected marks of each student and stored in an array, (here initialized to array), now count how many
students obtained in limits of 0-9 marks, 10-19 marks, 20-29 marks, … 99-100 marks. For example,
int marks[100]={3 , 41 , 29 , 31 , 11, 17, 43 , 20 ,13 , 0 , 5 , 7, 8 };
0 to 9 : marks obtained by 5 students
10 to 19 : marks obtained by 3 students
20 to 29 : marks obtained by 2 students …
process: Like above example, but increment count*+ as “count[ marks[i]/10 ] ++”
---------------------------------------------------------------------------------------------------------------------------------------------
46 C-Family | Arrays

18) for Carona epidemic, the money rs:100/- is collected from interested students in a college, the student’s
idno is noted those who donated, but their idno might not have recorded in ascending order while collecting
money. Now our program is to simulate such process, here we need to scan idno from keyboard one by one
until last input is zero, and finally have to print in ascending order. Here the idno ranges in between 1-100.
ip: 42
23
10
20
67
8
0 (stop)
op: 8 , 10 , 20 , 23 , 42 , 67
Note: do not use any sorting technique, take array a[] with size 100 and initialize with zero in all cells of a[],
now fill the value ‘1’ in a[ ] where its index is idno ( a[idno]=1) now print all such cells index(i) where a[i]==1.
The output of this process is automatically in ascending order of all idno’s.
---------------------------------------------------------------------------------------------------------------------------------------------
19) A movie rating data is collected from audience at theater, the rating values ranges from 0 to 9, collected
from <50 peoples, now our job is to sort all ratings and print as given below.
ip: 2 4 6 2 5 8 9 3 3 2 1 0 9 0 0 1 1
op: 0 0 0 1 1 1 2 2 2 3 3 4 5 6 8 9 9
Note: do not use any sorting technique, take array a[] with size 10 and initialize with zero in every cell of a[],
now increment a cell where its index is rating, later print all of them.
--------------------------------------------------------------------------------------------------------------------------------------------
20) Code to accept N numbers from keyboard and then reverses the elements of the array
To reverse the elements, swap elements in opposite ends i.e., replace the first element with the last
element, second element with the previous of last, and so on. (Note: Nested loop not required)

23 34 56 32 78 89 53 89 78 86
A[0] A[1] A[2] A[3] A[4] A[5] A[6] A[7] A[8] A[9]

Take ‘ i & j ’, ‘i’ for forward direction and ‘j’ for backward direction and swap every pair (a[i],a[j]) until i<j
The loop to swap is: for(i=0, j=n-1; i<j; i++, j--) { swap a[i], a[j] }
---------------------------------------------------------------------------------------------------------------------------------------------
21) Code to accept N values from keyboard and count frequency of each number
ip: 14, 10, 9, 10, 10, 8, 8, 8, 11, 10, 17, 17, 17, 17, 17, 20.
op: 14  1 time
10  4 time
9  1 time ….
-------------------------------------------------------------------------------------------------------------------------------------------
22) Write a program to accept two array of elements and each contained N1, N2 values respectively, let the
array names are A[], B[], now print
1) print A[] U B[] ( A union B )
2) print A[] – B[]
3) print A*+ Ω B*+ ( A intersection B )
----------------------------------------------------------------------------------------------------------------------------------------------
47 C-Family | Arrays

23) Code to accept two array of N elements, find both array have same values or not?
(Let us take both arrays have same number of N values, and no duplicate exist and also order is ignored)
ip: a[ ] = {10, 17, 20, 31, 23, 98 }; ip: a[ ] = {10, 17, 20, 31, 23, 98};
b[ ] = {17, 20, 10, 98, 23, 31 }; b[ ] = {17, 29, 13, 98, 23, 31 };
op: equal op: not equal
the comparison as given below figure

10 17 20 31 23 98 10 17 20 31 23 98
A[0] A[1] A[2] A[3] A[4] A[0] A[1] A[2] A[3] A[4]

17 20 10 98 23 31 17 29 13 98 23 31
B[0] Bb[1] B[2] B[3] B[4] B[5] B[0] Bb[1] B[2] B[3] B[4] B[5]

----------------------------------------------------------------------------------------------------------------------------------------------
24) Write a program to check given date is valid or not
1. initialize all month's days in an array like arr[13]={0,31,28,31,30,31,....}; // the first value ‘0’ is dummy
2. based on year input in a date, replace a[2] by 29 for leap year. // arr[2]=28+(y%4==0)
3. find date is valid or not, like given below
step1: scan(d,m,y)
step2: arr[2]=28+(y%4==0)
step3: if( m<1 || m>12 || d<1 || d>a[m] )
printf("valid date");
else
printf("invalid date");
----------------------------------------------------------------------------------------------------------------------------------------------
25) Write a program to increment given date by 'n' days
ip: enter date: 31 12 2019 ⤶
no.of days to increment: 365⤶
op: 31 12 2020
step 1: Let, date is scanned to ( d, m, y)
step 2: fill (initialize) all month's days in an array like
step 3: a[13]={0,31,28,31,30,31,....}
step 4: a[2]=28+(y%4==0); // if leap year, then 28+1
step 5: take loop, repeat n times;
step 6: for(i=0; i<n; i++) // loop increments date by one day in every iteration;
{ d++; // increment day by one-day
if( d== a[m] ) // if 'day' reached to end of month, then
{ d=1; // shift to next month
m++;
if(m==13) // if month is reached to end of year
{ m=1;
y++;
a[2]=28+(y%4==0); // if leap year 28+1; otherwise 28+0
}
}
}
---------------------------------------------------------------------------------------------------------------------------------------------
48 C-Family | Arrays

26) Code to fill array with prime numbers from 2 to 1000.


The array filled as: a[ ] = {2,3,5,7,11,13,17,19, …};
Hint: for example, to find prime ness of ‘N=35’ , then check by dividing with previous primes which are in the
array, calculated by previous iterations of loop, for example 2, 3, 5, 7, 11,…<=35/2
Initialize array with first prime(2) and start loop from 3.
void main()
{ int a[100]={2} , count=1; // first prime(2) is initialized with array so take count with 1.
-----
for(i=3; i<100; i++)
{ -----
-----
}
}
this is fastest technique to check prime ness of one number with previous primes.
---------------------------------------------------------------------------------------------------------------------------------------------
27) Deleting kth element in the array
the following array contained 10 values, and it gives demo how to delete 5th element.
The code to delete 5th is as follows
for(i=5; i<10; i++)
a[i-1] = a[i]; // it replaces a*4+ by a*5+, a*5+ by a*6+, …etc.

45 56 77 60 99 87 43 34 17 22
A[0] A[1] A[2] A[3] A[4] A[5] A[6] A[7] A[8] A[9] A[10] A[11] A[12]

99 87 43 34 17
45 56 77 60 22
87 43 34 44 22
A[0] A[1] A[2] A[3] A[4] A[5] A[6] A[7] A[8] A[9] A[10] A[11] A[12]

Now write a program, where accept N values from keyboard and delete kth element in the array (k<N)
later print all elements after deleting kth element.
----------------------------------------------------------------------------------------------------------------------------------------------
28) Inserting a new element at kth position
Code to insert a new element at kth position in an existing array of N elements where k<N
To insert a new element at A[k], shift all existing elements of A[k], A[k+1], A[k+2]...A[N-1] to the right side by
one position. So that we get a gap at A[k], where new element can be inserted.

45 56 77 60 99 87 43 34 44 22
A[0] A[1] A[2] A[3] A[4] A[5] A[6] A[7] A[8] A[9] A[10] A[11] A[12]

For example, to insert a new element 11 at A[4], shift all elements 22,44,34, 43, 87, 99 to the right side by
one position, so that we get a gap at 99, where 11 can be inserted.
----------------------------------------------------------------------------------------------------------------------------------------------
49 C-Family | Arrays

29) Code to accept ‘N’ values from keyboard and remove all occurrences of ‘8’ in the array
(the value ‘8’ can be input)
ip: 14, 10, 9, 8, 10, 8, 8, 8, 11.
op: 14, 10, 9, 10, 11.
----------------------------------------------------------------------------------------------------------------------------------------------
30) Code to accept ‘N’ values from keyboard and remove all duplicates in the array
ip: 14, 10, 9, 10, 10, 8, 8, 8, 11, 10, 17, 17, 17, 17, 17, 20.
op: 14, 10, 9, 8, 11, 17, 20.
----------------------------------------------------------------------------------------------------------------------------------------------
31) Code to generate 10 random numbers, these must be distinct and must lie in between 100-200.
Logic: the library function “rand()” generates the numbers in between 1-65535 and use header file “stdlib.h”
for rand() function. for example: k=rand()%100+100;  generates a number in between 100-200.
note: rand() function may generate duplicate values, avoid while collecting numbers into array.
--------------------------------------------------------------------------------------------------------------------------------------------
32) For the following set of sample data, compute the standard deviation(sd) and the mean.
ip: A[] = { 7 , 1 , -6 , -2 }
op: result=4.74
The formula for standard deviation is sqrt ( ∑(A[i]–mean A[])2/n )
let the average(mean) of all values are M, the formula as given below
sd = sqrt [ (A0-M)2 + (A1-M)2 + (A2-M)2 + (A3-M)2 + … + (An-M)2 / N ]
---------------------------------------------------------------------------------------------------------------------------------------------
*33) Code to merge two sorted array elements into one output array, the output remain in sorted order
ip: A[ ] = {10, 27, 35, 39, 59, 98 };
B[ ] = {28, 32, 40, 68 };
op: C[ ] = {10, 27, 28, 32, 35, 39, 40, 59, 68, 98 }

10 27 35 39 59 98 28 32 40 68
A[0] A[1] A[2] A[3] A[4] B[0] B[1] B[2] B[3]

10 27 28 32 35 39 …
C[0] C[1] C[2] C[3] C[4] C[5] ….

step1: let array A[] contained n1 elements already in sorted order ( input in sorted order)
step2: let array B[] contained n2 elements already in sorted order ( input is sorted order)
step3: take index variables with i=0, j=0, k=0
step4: while( i<n1 && j<n2 )
if( A[i] < B[j] )
C[k++]=A[i++];
else
C[k++]=B[j++];

after above loop, some elements remain in A[] or B[], thereafter copying them to C[], as given below
while(i<n1) // after above loop, still if i < n1 means some elements left in A[], so copying to C[]
C[k++]=A[i++];
while(j<n2) // after above loop, still if j < n2 means some elements left in B[], so copying to C[]
C[k++]=B[j++];
---------------------------------------------------------------------------------------------------------------------------------------------
50 C-Family | Arrays

34) Code to accept 5 values one by one from keyboard, while scanning values, automatically arrange in
ascending order (do not use sorting technique).
After scanning a value, compare with previous values, if they are bigger then shift to right side
ip: enter value 1: 12 [ 12, ]
enter value 2: 19 [ 12, 19, ]
enter value 3: 15 [ 10, 15, 19, ]
// here shift 19 to next positions(right side), so that, we get a gap at A[1], where insert 15
enter value 4: 24 [ 10, 12, 19, 24, ]
enter value 5: 31 [ 10, 12, 19,24, 31 ]
---------------------------------------------------------------------------------------------------------------------------------------------
*35) Program to accept two polynomials and find addition and multiplication of them.
For example, the polynomials represented using arrays as given below.
f(x) = 7x5 + 4x3+2x+9
In array representation, the array index itself is taken as exponent of polynomial terms whereas coefficients
are stored as array values. ( this is as given picture )
int a[10]; // say, maximum degree of polynomial is 10

0 1 2 3 4 5 6 7 8 9
x x x x x x x x x x
9 2 0 4 0 7 0 0 0 0
a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9]

---------------------------------------------------------------------------------------------------------------------------------------------
36) Write a program to simulate bus reservation; here repeatedly tickets are issued one by one to
passengers, at end, the seat number -1 is entered as end of session; finally print how many seats reserved
with its list.
step1: Let us take a[40];
step2: Initialize array with 0 values for all locations, as it indicates all seats are free at the beginning;
step2: scan the seat number to ‘x’;
step3: if( x== -1) stop the program, go to step5;
step4: if a[x]==1 then
display error message “seat already reserved”
else
a[x]=1; // reserving seat numbers; 0un-reserved, 1reserved
goto step2;
step5: print number of seats is reserved
step6: stop
input: enter seat no: 1
enter seat no: 3
enter seat no: 1 (error, already reserved)
enter seat no: 7
enter seat no: -1 (end of program)

Dummy Seat-1 Seat-2 Seat-3 Seat-4 Seat-5 Seat-6 Seat-7 Seat-8 Seat-9
1 0 1 0 0 0 1 0 0
a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9]
reserved reserved reserved

---------------------------------------------------------------------------------------------------------------------------------------------
51 C-Family | Arrays

-37) Code to exchange all odd number to beginning of array and even numbers to end of array
Process: take index variables i , j and set i=0, j=n-1, now look and select even & odd numbers in opposite side
and exchange for every pair of selection.
ip: a[ ] = { 10, 21, 30, 37, 40, 87, 44, 11 };
op: a[ ] = { 11, 21, 87, 37, 40, 44, 30, 10 }; // after exchange
exchanging elements is as follows
while(1)
{ while(i<j && a[ i ]%2==1) i++; // if odd then skip by i++, if even then selects by stopping loop
while(i<j && a[ j ]%2==0) j--; // if even then skip by j--, if odd then select by stopping loop.
if( i < j )
swap( &a[i], &a[j]); // exchange for every pair of selection
else
break; // all are exchanged.
}
---------------------------------------------------------------------------------------------------------------------------------------------
52 C-Family | Arrays
53 C-Family | C-Functions

Functions
1) Write a function(fn) called big(), which takes two integer arguments and return a big value, later write a
main() fn where scan 3 values (a, b, c) and find big of them. Function proto-type is: int big(int , int);
void main()
{ int a, b, c, k;
----
k=big(a,b);
k=big(k,c); // we can also call like: k=big( big(a,b), c )
-----
}
int big( int x, int y )
{ --------
}
----------------------------------------------------------------------------------------------------------------------------------------------
2) Suppose we have a fn called big3(), which takes three arguments and returns a big value, but we need to
find big of 2 values using such big3() fn, now explore how to call and find big of 2 values.
Note: Here in the main fn, we need to scan only 2 input values (little tricky question)
fn proto-type is: int big3(int , int , int);
void main()
{ int a, b, result;
printf(“enter any 2 values :”);
scan(“%d%d”, &a, &b);
---------
}
int big3( int x, int y, int z )
{ --------
--------
}
----------------------------------------------------------------------------------------------------------------------------------------------
3) Write a fn called findTax(), which takes salary as argument(input) and return tax.
fn proto-type is: float findTax( float salary );
tax calculation is: if( salary<=10000) tax is zero.
if( salary>10000 and salary<=20000) tax is 5% on salary.
if( salary>20000) tax is 8% on salary.
void main()
{ float salary, tax;
printf(“enter salary :”);
scanf(“%f”, &salary);
tax=findTax(salary); // function call
printf(“tax for salary %f is %f”, salary, area);
}
float findTax(float salary)
{ -------
-------
}
----------------------------------------------------------------------------------------------------------------------------------------------
54 C-Family | C-Functions

4) Write a fn to find factorial (4!  4*3*2*1) of a given number, later find nCr in main() fn.
nCr  n! / ( n-r! * r! )
the main() fn as given below
void main()
{ int n, r; // to store input values
int f1, f2, f3; // f1 to store n!, f2 to store r!, f3 to store n-r!
printf(“enter n , r values :”);
scanf(“%d%d”, &n, &r);
f1=fact(n); // call-1 for n!
f2=fact(r); // call-2 for r!
f3=fact(n-r); // call-3 for n-r!
f1=f1/(f2*f3);
printf(“\n ncr=%d”, f1);
}
int fact( int n )
{ ------
------
}
----------------------------------------------------------------------------------------------------------------------------------------------
5) Write a fn to calculate xy value, where the fn takes x, y as arguments and returns xy.
Later write a main() fn to find 23 and 32.
void main()
{ int k;
3
k=power(2,3); // call-1 for 2
printf(“2^3 = %d”, k);
2
k=power(3,2); // call-2 for 3
printf(“3^2 = %d”, k);
}
int power( int x, int y )
{ -------
-------
}
-----------------------------------------------------------------------------------------------------------------------------------------------
6) Write a fn called sumOfDivisors(), which returns sum of all divisors of given N.
the fn proto type is: int sumOfDivisors(int)
Later write a main() fn and check the given N is strong or not?.
Perfect: if sum of all divisors is equal to given N then it is said to be perfect. (don’t take N as divisor)
Logic: Check for all divisors from 1 to N/2 and add divisible to variable ‘sum’.
For example: 6 (1+2+36), 28(1+2+4+7+1428)
ip: enter N value: 6 ip: enter N value: 7 ip: enter N value: 28
op: yes op: no op: yes
----------------------------------------------------------------------------------------------------------------------------------------------
7) Write a fn called sumOfSquares1to10(), which returns sum of 12 + 22 + 32 + 42 ... + 102
the fn proto type is “int sumOfSquares1to10()”
this fn takes no arguments but returns sum of squares of all these 1-10 numbers.
Later write a main() fn and check this sum is equal to 385 or not?. (output is: yes/no)
-----------------------------------------------------------------------------------------------------------------------------------------------
55 C-Family | C-Functions

8) Write a fn reverse(), which returns reverse of given argument N, later write main() fn and check given
number is palindrome or not? fn proto-type is: int reverse(int);
ip: 2345 ip: 232
op: not a palindrome op: yes palindrome
to get reverse of N, the logic is
while(n>0)
{ r = n%10;
rev=rev*10+r;
n=n/10;
}
----------------------------------------------------------------------------------------------------------------------------------------------
9) Write a fn isPrime(), which returns given number is prime or not?
If N is prime then returns 1(true) or else returns 0(false).
Later write a main() fn and print all primes between 50 to 100.
fn proto-type is: int isPrime(int);
----------------------------------------------------------------------------------------------------------------------------------------------
10) Write a fn called digitSum(), this returns sum of all digits of a given number, later write a main fn where
scan N value, and repeatedly sum the digits until it reached to single digit.
19999=>1+9+9+9+9=>37
37=>3+7=>10
10=>1+0=>1
Here: here repeatedly call the digitSum(), Until sum of digits become < 10 (single digit)
----------------------------------------------------------------------------------------------------------------------------------------------
11) Write a fn called printTable() which prints multiplication table upto 10 terms.
If input is 8 then output is: 8*1=8, 8*2=16, 8*3=24,… 8*10=80.
In the main() fn, call printTable() for 3 times to print 8, 9 and 13 tables.
void main()
{ printTable(8);
-----
}
void printTable(int n)
{ --------
}
----------------------------------------------------------------------------------------------------------------------------------------------
12) Write a fn called printAllDivisibles(), which prints all divisible of given N.
Later write a main() fn, where repeatedly scan N value until N==0, here print divisible of each input N.
enter N value( 0 to stop): 15
output: 1, 3, 5, 15.
enter N value( 0 to stop): 8
output: 1, 2, 4, 8
enter N value( 0 to stop): 9
output: 1, 3, 9.
enter N value( 0 to stop): 0
( program stops)
fn proto-type is: void printAllDivisibles( int n );
----------------------------------------------------------------------------------------------------------------------------------------------
56 C-Family | C-Functions

13) Write a fn called getSumOrProduct(), which returns sum/product of 1 to N, the main() fn already given
int getSumOrProduct(int N, int flag) // if flag==0 then returns 1+2+3+….+N, or else returns 1*2*3* ….*N.
{ -------
-------
}
void main()
{ int N=5, sum, product ;
sum=getSumOrProduct(N, 0 );
product=getSumOrProduct(N, 1);
printf(“\n sum is %d, product is %d”, sum, product);
}
Note: we may get one doubt, can’t we return two values at a time?, in C, the functions are designed to
return only one value using return statement, so we can’t return two or more values at a time, but using
pointers we can return more values. We will see next chapter.
----------------------------------------------------------------------------------------------------------------------------------------------
14) Write a fn called getAreaOrPerimeter() which takes radius and flag as arguments and returns
area/perimeter of circle. (If flag is ‘A’ then it returns Area of circle, if flag ‘P’ returns Perimeter)
Function proto-type is: float getAreaOrPerimeter( float radius, char flag );
the main() fn already given with radius = 5
void main()
{ float area, radius, perimeter;
radius=5;
area=getAreaOrPerimeter(radius , ‘A’ ); // function call-1
printf(“\n area is : %f”, area);
perimeter=getAreaOrPerimeter(radius , ‘P’ ); // function call-2
printf(“\n perimeter is : %f”, area);
}
float getArea( float radius, char flag )
{ -------
-------
}
----------------------------------------------------------------------------------------------------------------------------------------------
15) Write 2 functions called fact() and nCr(); the function nCr() takes the help of fact() while calculating
factorial values. Later write a main() function to check nCr() is working properly or not?
void main()
{
// here call nCr() function to print nCr value
}
int nCr(int n, int r)
{
// here call fact() function for 3 times to calculate n!, r! and n-r! values.
}
int fact(int n)
{
// find factorial value here
}
----------------------------------------------------------------------------------------------------------------------------------------------
57 C-Family | C-Functions

16) Write a main() fn, where scan 10 values to array a[], and find count of primes in the array.
( for your easiness, here main() fn already given with 10 initialized values)
now yourself, write a fn called isPrime(), which finds given number is prime or not? ( returns 1/0)
void main()
{ int a[5]={10, 18, 11, 15, 17, 21, 23, 5, 30, 31};
int count=0, i;
for(i=0; i<5; i++)
{ k=isPrime( a[i] );
if(k==1)
{
count++;
}
}
printf(“\n count = %d”, count);
}
int isPrime( int n )
{ ---------
---------
}
---------------------------------------------------------------------------------------------------------------------------------------------
17) Write a fn called gcd(), which takes 2 numbers as arguments and returns greatest common factor.
Write main() fn, where scan 5 values to array a[], and find their gcd. For example
ip : arr[] = {2, 4, 6, 8, 16}
op : 2
ip : arr[] = {1, 2, 3}
op : 1
---------------------------------------------------------------------------------------------------------------------------------------------
18) Write getDaysInMonth() fn, which takes month, year as arguments and returns days in month.
the Fn proto-type is: int getDaysInMonth(int m , int y); // here ‘m’ is month, ‘y’ is year
1) if m==2 with non-leap-year has 28 days. (m==2 means February)
2) if m==2 with leap-year has 29 days.
3) if month==4 or 6 or 9 or 11) has 30 days. (April, June, September, November)
4) Other than above months has 31 days.
void main()
{ int m,y;
printf(“enter month & year :”);
scanf(“%d%d”, &m, &y);
days=getDaysInMonth(m,y);
printf(“days in the month %d is %d”,m, days);
}
int getDaysInMonth(int m, int y)
{
--------
}
----------------------------------------------------------------------------------------------------------------------------------------------
58 C-Family | C-Functions

19) Write a fn called readMarks(), which returns marks scanned from keyboard. The input marks must be in
between 0-100 or else scan again and again until user entered 0-100, later return the marks.
Now write main() fn, scan two subject marks and print pass/failed. If he got >=50 in 2 subjects then print
“pass” or else “fail”.
void main()
{ int m1,m2;
m1=readMarks();
m2=readMarks();
------
}
int readMarks()
{
-----
}
----------------------------------------------------------------------------------------------------------------------------------------------
20) Write a fn called convertToSeconds(), this fn takes hours, minutes and seconds as arguments and
returns time in seconds. For example N=convertToSeconds(2,3,10); then N value is 7390.

Write one more fn called getHMS(), this is opposite to above fn, this fn extracts hours/minutes/seconds
from given seconds time(N). For example, getHMS(N, ‘H’) returns hours in N, getHMS(N, ‘M’) returns
minutes in N (after taking hours), getHMS(N, ‘S’) returns seconds in N (remaining seconds after taking hours
& minutes). for example: time 2:3:10  N=7390 then
h=getHMS(7390 , ‘H’)  h=2
m=getHMS(7390 , ‘M’)  m=3
s=getHMS(7390 , ‘S’)  s=10

Now write a main() fn, scans two times from keyboard and print after adding two times, the code looks like
int h, m, s, n;
scan(h,m,s); // scanning time1
n=convertToSeconds(h,m,s);
scan(h,m,s); // scanning time 2
n = n+convertToSeconds(h,m,s); // adding two times
h=getHMS(n , ‘H’ ); // returns hours in n.
m=getHMS(n , ‘M’ ); // returns minutes in n.
s=getHMS(n , ‘S’ ); // returns seconds in n.
printf(h, m, s); // the addition of two times.
----------------------------------------------------------------------------------------------------------------------------------------------
21) Write a fn called scanDate(), which returns a valid date in 8-digit format.
Here while scanning date, if user entered invalid date then again and again scan until a valid date is entered.
Later return this date as 8-digit single number format.
For example if input date is “25-11-2009” then returns date as “20091125”.
For date validation, write one more fn called isValidDate(), this returns bool value.
Finally, write main() fn, where scan two dates and find they are equal or not?
void main()
{ int date1,date2;
date1=scanDate();
date2=scanDate();
59 C-Family | C-Functions

if(date1==date2)
printf(“equal”);
else
printf(“not equal”);
}
int scanDate()
{ ------ // call isValidDate() fn, here to check given date is valid or not?
------
}
int isValidDate()
{
------
}
----------------------------------------------------------------------------------------------------------------------------------------------
22) Write a fn called printDigit(int), which prints given digit in English words, later write a main() fn where
scan 4-digit number and print in English words.
input: 3456
output: three four five six.
logic:1. let N=3456, D=1000. [ take D value as 1000 because N is 4-digit number ]
2. divide 3456 with 1000 and get quotient, it is 3 [ q = N/D ]
3. print 3 in English words by calling function printDigit(q)
4. now remove 3 from 3456, for this do N=3456%1000  N=456 [ N=N%D ]
5. now N value is 456, and take D value as 100 [ D=D/10 ]
6. I think you got to know how to repeat this process.
---------------------------------------------------------------------------------------------------------------------------------------------
23) Write a fn called int getDigit(int N, int i), returns i’th digit in N ( from left-to-right ). For example,
if N=9637 & i=1 then returns 9,
if N=9637 & i=2 then returns 6,
if N=9637 & i=3 then returns 3,
if N=9637 & i=4 then returns 7,
if N=9637 & i=5 then returns -1 (stop)
Now write main fn, here print each digit of N in English words.(input ‘N’ can have any number of digits), to
print digit in English words use above fn printDigit(int)
The main() fn is as follows
void main()
{ int n , i ;
n=45672; // or scan N from keyboard.
for( i=1 ; ; i++ ) // infinite loop, but stops by break;
{ d=getDigit(N, i);
if(d==-1) break;
printDigit(d);
}
}
----------------------------------------------------------------------------------------------------------------------------------------------
60 C-Family | C-Functions
61 C-Family | Recursion

Recursion
(In the following examples don’t use any loop control structures)
1) Fill the body of recursive function show() to print 1 to 10 numbers.
void main()
{ show(1);
}
void show( int i )
{ -----
-----
}
----------------------------------------------------------------------------------------------------------------------------------------------
*2) Fill the body of recursive function show() to print 1 to N numbers, this function takes N as argument and
prints the numbers from 1 to N.
ip: N=13
op: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13.
void main()
{ int N=13; // or else scan ‘N’ value from keyboard using scanf() statement
show(N);
}
void show( int N )
{ -----
-----
}
-----------------------------------------------------------------------------------------------------------------------------------------------
3) Fill the body of recursive function show() to print 1 to 10 and 10 to 1 numbers.
op: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1
void main()
{ show(1);
}
void show( int i)
{ -----
-----
}
----------------------------------------------------------------------------------------------------------------------------------------------
4) Fill the body of recursive function show() to print 1 to 10 and 9 to 1 numbers.
op: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1
void main()
{ show(1);
}
void show( int i)
{ -----
-----
}
----------------------------------------------------------------------------------------------------------------------------------------------
62 C-Family | Recursion

5) Write a recursive function to print N to 1 and 1 to N numbers.


ip: N=13
op: 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13
void main()
{ int N=13; // or else scan ‘N’ value from keyboard using scanf() statement
show(N);
}
void show(int N)
{
-----
}
-----------------------------------------------------------------------------------------------------------------------------------------------
6) Write a function to print odd numbers 1, 3, 5, 7, 9, 11, 13, … < N
void main()
{ int N=16;
show(N);
}
void show(int N)
{ -----
----- // check N, whether it is odd or even, if odd then print(N)
}
-----------------------------------------------------------------------------------------------------------------------------------------------
7) Write a function to print 1, -2, 3, -4, 5, -6, 7, …N times
void main()
{ int N=13;
show(N);
}
void show(int N)
{
----- // check N, whether it is odd or even, if odd then print(–N) or else print(N)
}
-----------------------------------------------------------------------------------------------------------------------------------------------
8) Fill the body of recursive function show() to print following output N, N/2, N/4, N/8, N/16,... 1
This function takes N as argument and prints output from N to 1
ip: N=100
op: 100, 50, 25, 12, 6, 3, 1
void main()
{ int N=100; // or else scan ‘N’ value from keyboard using scanf() statement
show(N);
}
void show(int N)
{ ------
-----
}
-----------------------------------------------------------------------------------------------------------------------------------------------
63 C-Family | Recursion

9) Fill the body of recursive function show() to print following output from 1,…N/8, N/4, N/2, N (reverse
order of above program. This function takes N as argument and prints output from 1 to N.
input: N=100
output: 1, 3, 12, 25, 50, 100
void main()
{ int N=100;
show(N);
}
void show(int N)
{ ------
-----
}
-----------------------------------------------------------------------------------------------------------------------------------------------
10) Generate and print list of numbers from N to 1, Here N is input from keyboard and print list of numbers
as long as the value of N becomes 1.
if N is even then next number of N is → N/2 (half)
if N is odd then next number of N is → 3N + 1
if input N is 13, then we have to print as: 13, 40, 20, 10, 5, 16, 8, 4, 2, 1
void main()
{ int N=100;
show(N);
}
void show(int N)
{ ------
-----
}
-----------------------------------------------------------------------------------------------------------------------------------------------
11) Write a recursive function to print following output 1, 2, 4, 8, 16, 32, 64, up to N terms.
void main()
{ int N=10;
show(1, N); // ‘N’ is number of terms to print, where ‘1’ is starting value of series.
}
void show(int P, int N) // ‘N’ is to count down from ‘N’ to 1, where ‘P’ raises its value to 1, 2, 4, 8, ….
{ -------
-------
}
-----------------------------------------------------------------------------------------------------------------------------------------------
12) Write a recursive function to print multiplication table up to given number of terms
ip: 8
op: 8*1=8
8*2=16
8*3=24
……
8*10=80
64 C-Family | Recursion

void main()
{ int N =8;
show( N, 10 ); // ’N’ is table number, and 10 is number of terms to print
}
void show( int N, int i ) // ‘N’ represents which table to print, ‘i’ is like looping
{ ---------
printf(“\n %d * %d = %d”, N, i, N*i);
--------
}
-----------------------------------------------------------------------------------------------------------------------------------------------
13) Write a recursive function to print Fibonacci series up to N terms
ip: N=11 (11 terms)
op: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55
void main()
{
show(0, 1, 10 ); // 0,1 are first two terms in the fibo series, 10 is number of terms to print
}
void show( int x, int y, int N)
{ ---------
print(x);
show( y, x+y, N-1); // for next recursive call of fibo() function.
}
-----------------------------------------------------------------------------------------------------------------------------------------------
14) Write a recursive function printFibo(), to print fibonacci numbers in between 10 & 200
op: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 84, 139, 223, 362, 585,
this main() fn is as follows
void main()
{
show(0,1, 10, 200); // 0,1 are first two numbers in Fibonacci series, 10-200 are limits

}
void show( int x, int y, int lower, int upper)
{
----------
}
----------------------------------------------------------------------------------------------------------------------------------------------
15) Write a recursive function to print factors of a given number
ip: 18
op: 1, 2, 3, 6, 9, 18
void main()
{ int N=18;
show(N,1); // ‘1’ is starting value of ‘i’ like a loop variable, search for factors from 1 to N
}
void show(int N, int i)
{ -------
}
----------------------------------------------------------------------------------------------------------------------------------------------
65 C-Family | Recursion

16) Write a program to print smallest factor of N (exclude 1 as factor)


ip: 18 ip: 11 ip: 35
op: 2 op: 11 op: 5
void main()
{ int N=18;
show(N,2); // 2 is starting value of ‘i’ where find small by searching from 2 to N.
}
void show(int N, int i)
{ -------
}
----------------------------------------------------------------------------------------------------------------------------------------------
17) Write a function to print biggest factor of N (exclude N as factor)
ip: 18 ip: 17
op: 9 op: 1
void main()
{ int N=18;
show(N,N/2); // N/2 is starting value of ‘i’ where find big factor by searching from N/2 to 1.
}
void show(int N, int i)
{ -------
}
----------------------------------------------------------------------------------------------------------------------------------------------
18) Write a function to find given number N has perfect square root or not?
ip: 16 ip: 17
op: yes (4^2) op: No.
void main()
{ int N=16;
show(N,1);
}
void show(int N, int i) // compare every time by i*i==N, stop when i*i==N or i*i > N
{ -------
-------
}
----------------------------------------------------------------------------------------------------------------------------------------------
19) Write a function to find whether given N is power of 2 or not?
ip: 8 ip: 18
op: yes (2^3==8) op: no
void main()
{ int N=16;
show(N,1);
}
void show(int N, int p) // where p=1, 2, 4, 8, 16 ( p =2^0, 2^1, 2^2, 2^3, 2^4, …. )
{ ------- // repeat until p<N
}
-----------------------------------------------------------------------------------------------------------------------------------------------
66 C-Family | Recursion

20) Write a function to find whether the given 'N' is prime or not.
if 'N' is prime, it does not divide with any number, other than 1 & itself;
if input is 17, then output is "given number is prime"
if input is 18, then output is "given number is not a prime"
void main()
{ int N=17;
show(N,2); // start dividing N from 2 to N/2
}
void show(int N, int i) // where i= 2, 3, 4, 5,… N/2
{ -------
}
-----------------------------------------------------------------------------------------------------------------------------------------------
21) Write a recursive function to print binary number of given N.
ip: 13 ip: 9
op: 1101 op: 1001
void main()
{ int N=13;
2 13
show(N); 2 6- 1
} 2 3- 0
void show(int N) 2 1- 1
0- 1
{ -------
-------
}
Note: print remainder of ‘N’ from bottom to top: 1%2, 3%2, 6%2, 13%2 (1, 1, 0, 1)
-----------------------------------------------------------------------------------------------------------------------------------------------
22) Write a recursive function(s) to print following output (don’t use any loop)
12345678
1234567
------
12
1
void main()
{ int N=8; // no.of rows to print
show(N);
}
void show(int N)
{ ------
showRow( -- );
------
}
void showRow(int N)
{ ----- // prints each row here
-----
}
-----------------------------------------------------------------------------------------------------------------------------------------------
67 C-Family | Recursion

23) Write a recursive function to find sum of 2+2+2+2+2+ ….N times, here N is input value.
note: do not use multiplication operator(*) in the program
ip: enter N value:6
op: output = 12
void main()
{ int k, N=6;
k=sumsOf2(N);
printf(“sums of 2 for N times is %d”, k);
}
int sumsOf2(int N)
{ ---- // here stop condition
return 2+sumOf2(N-1); // next recursive call.
}
---------------------------------------------------------------------------------------------------------------------------------------------
24) Write recursive function to find factorial of N. (1+2+3+ …. +N)
ip: N=5
op: 5+4+3+2+1
void main()
{ int k;
k=sum1toN(5);
printf(“sum 1 to N is %d”, k);
}
int sum1toN( int N )
{
----
----
}
----------------------------------------------------------------------------------------------------------------------------------------------
26) The sum of squares of first ten natural numbers is, 1^2 + 2^2 + 3^2 ... + 10^2 = 385
Write a program to prove it ( output is “yes” or “no”)
void main()
{ int k;
k=sumOfSquares(1);
if( k==385 ) printf(“ yes, proved”);
else printf(“ yes, proved”);
}
int sumOfSquares( int N )
{ ---- // stop when N becomes 11 and return 0;
----
}
-----------------------------------------------------------------------------------------------------------------------------------------------
68 C-Family | Recursion

27) Write a recursive function to print sum of 1+2+4+8+16...N times. (2^0+2^1+2^2+2^3+ …. N times)
Hint: do not use pow() library function.
void main()
{ int k, N=5, sum;
sum=sumOf2Powers(1, N); // initial value of series is 1, and ‘N’ is number of terms
printf(“sum of powers is %d”, sum);
}
int sumOf2Powers( int p , int N)
{ ------
------
}
---------------------------------------------------------------------------------------------------------------------------------------------
28) Write recursive function to find factorial of N. (1*2*3* …. *N)
ip: N=5
op: 5*4*3*2*1

void main()
{ int k;
k=factorial(5);
printf(“factorial of 5 is %d”, k);
}
int factorial(int N)
{ ----
----
}
---------------------------------------------------------------------------------------------------------------------------------------------
29) Write recursive function to find XY, where X is base and Y is exponent
the recurrence relation is
f(X,Y)  X*f(X,Y-1) if Y>0
f(X,Y)  1 if Y==0
void main()
{ int X=3, Y=4, Z;
Z=power( X,Y);
printf(“ X^Y = %d”, Z);
}
int power(int X, int Y)
{
--------
}
---------------------------------------------------------------------------------------------------------------------------------------------
30) Write recursive function to find sum of factors of given N. (exclude N as factor)
Later write a main() function and check given number is perfect or not?,
if N is perfect then sum of factors is equal to N. (Check for factors from 1 to N/2)

input: 6 input:28 input: 10


output: yes, perfect output: yes, perfect output: no, not perfect
69 C-Family | Recursion

void main()
{ int k,N;
scanf(“%d”, &N);
k=sumFactors(N, 1); // intial value of ‘i’ is 1
if( N==k)
printf(“yes, it is perfect”);
else
printf(“no, it is not perfect”);
}
int sumFactors( int N, int i )
{ ------ // stop the process when i>N/2
------
}
--------------------------------------------------------------------------------------------------------------------------------------------
31) x^1/1! + x^2/2! + x^3/3!..... N times [ do not use pow() fn ]
ip: x=3, N=5
op: sum= 17.4 [3.0 + 4.5 + 4.5 + 3.375 + 2.025  17.4]
void main()
{ int k, x=3, N=5, sum;
sum=sumOfSeries(x, N); // intial value of series is 1, and N is number of terms
printf(“sum of powers is %d”, sum);
}
int sumOfSeries( int x , int N)
{ ------ // here write stop condition
return power(x,N)/fact(N) + sumOfSeries(x, N-1);
}
// here power() and fact() are again recursive function ( write yourself )
----------------------------------------------------------------------------------------------------------------------------------------------
32) Write a function to find sum of all digits in a given number, the function takes N as argument and returns
sum of all digits.
ip: 2345 ip: 456 ip: 23456
op: 14 (2+3+4+5) op: 15 (4+5+6) ip: 20 (2+3+4+5+6)
hint: return N%10+find(N/10)
---------------------------------------------------------------------------------------------------------------------------------------------
33) Write a function to find sum of odd digits only.
ip: 2345
op: odd digits sum = 8 (3+5)
----------------------------------------------------------------------------------------------------------------------------------------------
34) Write a function to print first digit of given number.
ip: 2345 ip: 456
op: 2 op: 4
logic: repeatedly divide N=N/10 until N>9, finally N contains first digit then return it.
---------------------------------------------------------------------------------------------------------------------------------------------
35) write a recursive function to print first odd digit of a given number, if odd not found then return -1.
ip: 2345 ip: 456 ip: 486
op: 3 op: 5 op: -1
--------------------------------------------------------------------------------------------------------------------------------------------
70 C-Family | Recursion

36) Write a recursive function checkFibo(), to check given number is in Fibonacci series or not? This function
returns (1/0 bool value)
ip: 13 ip: 15
op: yes, it is in series op: no, not in series
---------------------------------------------------------------------------------------------------------------------------------------------
37) Write a recursive function checkPrime(), to check given number is prime or not?
This function returns (1/0 bool value)
ip: 13 ip: 15
op: yes, it is prime op: no, it is not prime
void main()
{ int N=13, bool;
bool=checkPrime(2, N); // check prime ness by dividing from 2 to N/2
if(bool==1) printf(“N is prime“);
else printf(“N is not prime”);
}
int checkPrime(int i, int N)
{ ----
----
}
---------------------------------------------------------------------------------------------------------------------------------------------
38) Write a program to find GCD of two numbers. (GCD/HCF  Greatest Common Divisor)
ip: 12, 18
op: 6
1.let x, y are input values
2.divide ‘y’ with ‘x’ (irrespective of which is big and which is small)
3.if remainder(R) is zero then stop and print ‘x’ as GCD
4.if R is not zero then take ‘x’ as ‘y’ and ‘R’ as ‘x’ and continue this process until R is zero.

---------------------------------------------------------------------------------------------------------------------------------------------
39) Write a program to find LCM of 3 numbers
ip: 12 18 45
op: 180
1. Let x, y, z are three input numbers
2. Start finding LCM of three with first factor 2
3. Now divide each x, y, z with 2, and decrement all divisible numbers to quotient obtained in the division.
For example, if x is divided with 2 then decrement x=x/2
4. If any x, y, z is divided in step3 then take 2 as factor in LCM. (LCM=LCM*2)
5. Now repeat step-3, step-4 as long as 2 divide any x, y, z
6. if 2 no longer divided, then next try with next factors 3, 4, 5…etc,
repeat this process until any of these (x, y, z) > 1.
Let the numbers are 20, 15, 35 and following table shows how
71 C-Family | Recursion

2 20 15 35

2 10 15 35
5 15 35
2, 3

3,4,5 5 5 35

5,6,7 1 1 7
1 1 1

-----------------------------------------------------------------------------------------------------------------------------------------------
40) Write a recursive function to print value of array, let array a[ ] contained N values.
void main()
{ int a[]={10, 43, 3, 11, 6, 5, 22, 60},N=8; // array contained 8 values.
show(a ,N);
}
void show( int *p, int N)
{ -----
printf(“%d “, *p); // don’t change this line
}
---------------------------------------------------------------------------------------------------------------------------------------------
41) Write a recursive function to print following output
ip: APPLE
op: APPLE
PPLE
PLE
LE
E
void main()
{ show(“APPLE“);
}
void show(char *p)
{ ------
printf(“\n%s”, p);
show(….);
}
---------------------------------------------------------------------------------------------------------------------------------------------
42) Write a recursive function to print 2-D array of size 3x4 data
void show1(int a[][4], int r, int c);
void show2(int a[], int c);
void main()
{ int a[3][4]= { {4,3,6,1}, {8,7,4,1}, {10,3,2,1} };
show1( a, 3, 4 );
}
void show1( int a[][4], int r, int c )
{ --------- // call show2() function for r times, pass row address
}
void show2( int a[], int c ) // this function prints each row for c times
{ -------
}
72 C-Family | Recursion

-------------------------------------------------------------------------------------------------------------------------------------------
43) Write a program to traverse the entire chess board with Knight (horse). Here the Knight visits the every
cell only once and it follows of its movement i.e., it moves only in L shape. This function takes x, y values
(coordinates) of first step and displays the order of movements in terms of step number for every cell.
( let board size is 5x5)

6
2 7
5
1 8 3
4
9…

---------------------------------------------------------------------------------------------------------------------------------------------
44) Write a recursive function to place 8 ministers in the chessboard of 8*8 size; Here the ministers are
arranged so that no minister kills one with another. This function takes first minister position as arguments
and remaining ministers are arranged accordingly.

1
3
2

4…

--------------------------------------------------------------------------------------------------------------------------------------------
45) Write a program to print all permutations (combinations) of a given string.
Input: abc
Output: abc
acb
bac
bca
cab
cba
---------------------------------------------------------------------------------------------------------------------------------------------
46) Write a program to accept “file name” from keyboard and search whether file is exist in the computer
hard-drive or not? (on particular drive-path given by the user)
Using library functions findfirst(), findnext() in dos.h file
--------------------------------------------------------------------------------------------------------------------------------------------
73 C-Family | pointers

Pointers
In C, functions can return only one or none value, because syntax is provided in that way, that is, using
return statement we can return at most only one value, to return more values we need to take help of
pointers. Using pointers we can return any number of values indirectly through address, this concept is
called returning through pointers or call-by-reference.
----------------------------------------------------------------------------------------------------------------------------------------------
01) This example explains call-by-value verses call-by-reference.
void main()
{ int a=10, b=20;
change( a, &b ); // a  call-by-value, &b  call-by-reference
printf(“\n a is %d, b is %d”, a, b );
}
void change( int x , int *p)
{ x=111; // the value 111 is stored in ‘x’ (not in ‘a’)
*p=222; // the value 222 is stored in ‘b’ (not in ‘p’)
}
Output: a is 10, b is 222 (no change in ‘a’, but in ‘b’)
--------------------------------------------------------------------------------------------------------------------------------------------
02) This example explains how to return sum & product of two numbers to the main() fn.
void main()
{ int a=10,b=20, sum, product;
findSumProduct ( a, b, &sum , &product );
printf(“\n sum is %d , product is %d”, sum, product);
}
void findSumProduct( int x , int y , int *ps , int *pp )
{
*ps=x+y; // indirectly stored into ‘sum’ in main() fn.
*pp=x*y; // indirectly stored into ‘product’ in main() fn.
}
output: sum is 30, product is 200
note: In this way, we can return as many values as we want through pointers, this concept often called call-
by-reference. We can’t return like return(sum, product); this concept is not available in c/c++/java.
--------------------------------------------------------------------------------------------------------------------------------------------
03) This example explains how the function find() returns sum & product of 1 to N to the main() function,
This function returns sum (1+2+3+4..…+N), and product(1*2*3*4….*N) indirectly through pointers.
Here ‘find()’ function take arguments ‘N’ along with address of variables which receives returning values.
void main()
{ int N=12, sum, product;
find(N, &sum, &product );
printf(“\n sum = %d , product = %d “, sum, product );
}
void find( int N, int *x, int *y)
{ int i, s=0 ,p=1; // here the local variables, ‘i’ for looping, ‘s’ for sum, ‘p’ for product.
for(i=1; i<=N; i++)
{ s=s+i;
p=p*I;
}
// following assignments return s , p values to sum , product in main() fn through pointers x , y.
*x=s; // sum=s; //this is called returning values indirectly
*y=p; // product=p;
}
--------------------------------------------------------------------------------------------------------------------------------------------
74 C-Family | pointers

04) fill the function body with code, which takes radius of circle as argument, and returns area & perimeter
void main()
{ int radius=5;
float area, perimeter;
find( radius, &area, &perimeter);
printf(“\n area = %f”, area);
printf(“\n perimeter = %f”, perimeter);
}
void find( -----)
{ ------
------
}
---------------------------------------------------------------------------------------------------------------------------------------------
05) Correct the following incrementBy10() function and its call statement.
void main()
{ int n=25;
incrementBy10(n);
printf(“n value is %d “, n); // expected output is 35 not 25.
}
void incrementBy10( int p )
{
p=p+10;
}
---------------------------------------------------------------------------------------------------------------------------------------------
06) fill the following function body, it should replace a=a+b and b=|a-b| for any a>0 , b>0
ip: a=2 , b=7
op: a=9 , b=5
void main()
{ int a=2 , b=7;
change( --- , --- );
prinf(“a=%d , b=%d”, a, b);
}
void change( --- , --- )
{
----
}
--------------------------------------------------------------------------------------------------------------------------------------------
07) Correct the following swap() function and its call statement.
void main()
{ int a=25, b=35;
swap( a , b );
printf(“ %d %d “, a, b); // expected output is (35,25) not (25,35) .
}
void swap( int p , int q )
{ int t;
t=p;
p=q;
q=t;
}
---------------------------------------------------------------------------------------------------------------------------------------------
75 C-Family | pointers

08) Complete the body of following swap2() function for swapping a , b.


the swap1() taking help of swap2() for swapping values.

void main()
{ int a=25, b=35;
swap1( &a , &b );
printf(“%d %d “ , a , b); // expected output is (35,25) not (25,35).
}
void swap1( int *p, int *q )
{
swap2( &p , &q );
}
void swap2( ----, ----)
{
-----
}
---------------------------------------------------------------------------------------------------------------------------------------------
09) Complete the body of following swap2() function for swapping a , b.
the swap1() taking help of swap2() for swapping values. (There is litter difference with above example)
void main()
{ int a=25, b=35;
swap1( &a , &b );
printf(“%d %d “, a, b); // expected output is (35,25) not (25,35).
}
void swap1( int *p, int *q )
{
swap2( p, q);
}
void swap2( ----, ----)
{
-----
}
---------------------------------------------------------------------------------------------------------------------------------------------
10) Write 2 functions called sort3() and swap(), used to sort 3 variable values (a, b, c) into ascending order.
The sort3() fn sorts 3 values into order and takes the help of swap() fn for swapping.
logic for sorting a, b, c is : if(a>b) swap, if(a>c) swap, if(b>c) swap
ip: 23 12 2 ip: 10 2 5
op: 2 12 23 op: 2 5 10
void main()
{ int a, b, c;
printf(“\n Enter 3 values :”);
scanf(“%d%d%d”, &a, &b, &c);
sort3( ---- );
printf(“\n output is: %d %d %d”, a, b, c);
}
void sort3( ------- )
{
--------
}
void swap(---------)
{
--------
}
---------------------------------------------------------------------------------------------------------------------------------------------
76 C-Family | pointers

11) Write a function to add 10 grace marks to one subject out of 3 subjects; where such subject marks less
than of all other subjects and after adding 10 grace marks, it should not cross 100. (100 is highest marks)
ip: 60 70 90 ip: 70 80 55 ip: 93 97 98
op: 70 70 90 op: 70 80 65 op: 100 97 98

void main()
{ int a,b,c;
printf(“\n Enter 3 subject marks :”);
scanf(“%d%d%d”, &a, &b, &c);
addGraceMarks( ----);
printf(“\n output is: %d %d %d”, a, b, c);
}
void addGraceMarks( ------- )
{
-------- // add marks here
--------
}
--------------------------------------------------------------------------------------------------------------------------------------------
12) Write a function which takes basic salary as argument, later calculate and return tax and netSalary.
if basicSalary<=10000
HRA is 30% on basicSalary.
DA is 10% on basicSalary.
else HRA is 40% on basicSalary.
DA is 20% on basicSalary.
grossSalary=basicSalary+HRA+DA. (gross is final salary before deduction of tax)
if grossSalary<=40000 then tax is zero
if grossSalary>40000 then tax is 5% on grossSalary
netSalary=grossSalary-tax

void main()
{ float basicSalary, netSalary, tax;
printf(“Enter basic salary :”);
scanf(“%f”, &basicSalary);
find( basicSalary, &tax, &netSalary);
printf(“net salary is %f , tax is %f“, netSalary, tax);
}
void find( ----- )
{ float grossSalary, HRA, DA;
-------
-------
}
---------------------------------------------------------------------------------------------------------------------------------------------
77 C-Family | pointers

13) Code a function called findBigSmall(), which takes ‘N’ as argument and returns the big & small digit of N.
ip: N=5824
op: big=8, small=2
void main()
{ int N=5824, big, small ;
findBigSmall( N , &big , &small );
printf(“\n big is %d , small is %d “, big , small );
}
void findBigSmall( int N, int *pBig, int *pSmall)
{ -------
-------
}
Logic to find big digit in N.
while(N>0)
{ rem=n%10;
if(big<rem) big=rem;
if(small>rem) small=rem;
n=n/10;
}
---------------------------------------------------------------------------------------------------------------------------------------------
14) Write a function to increment given time by N seconds, where h, m, s and N are argument to function.
void main()
{ int h, m, s, N;
printf(“\n Enter time :”);
scanf(“%d%d%d”, &h, &m, &s);
printf(“\n Enter no.of seconds to increment time :”);
scanf(“%d”, &N);
increment( ------ );
printf(“\n output is %d %d %d”, h, m, s);
}
void increment( ------- )
{ --------
--------
}
---------------------------------------------------------------------------------------------------------------------------------------------
15) Write a function to add two times, say the two times are employee working time in 2 shifts, and returns
sum of two times.
ip: 10 40 50
07 50 40
op: 18 31 30
void main()
{ int h1,m1,s1, h2, m2, s2, h, m, s;
printf(“enter time1 :”);
scanf(“%d%d%d”, &h1, &m1, &s1);
printf(“enter time2 :”);
scanf(“%d%d%d”, &h2, &m2, &s2);
add(&h, &m, &s, h1, m1, s1, h2, m2, s2); // (h,m,s)= (h1,m1,s1) + (h2,m2,s2);
printf(“after adding, output time is : %d : %d : %d”, h, m, s);
}
void add( --------- )
{ ------
------
}
---------------------------------------------------------------------------------------------------------------------------------------------
78 C-Family | pointers

16) Write a function to increment date by one day, this function takes day, month, and year as arguments
and return the incremented date.
void main()
{ int d,m,y;
scanf(“%d%d%d”, &d, &m, &y);
increment( ---- );
printf(“\n output: after incrementing the date is %d %d %d”, d, m, y );
}
void increment( ------- )
{ --------
--------
--------
}
--------------------------------------------------------------------------------------------------------------------------------------------

Pointer to Array
following program explains how to access array elements through pointer
void main()
{ int arr[5]={10,20,30,40,50};
int *p;
p=&a[0]; or p=a;
for(i=0; i<5; i++) //method-1
printf(“%d “, *(p+i) or p*i+ );
or
for(i=0; i<5; i++) //method-2
{ printf(“%d “, *p );
p++;
}
}
P a[0] a[1] a[2] a[3] a[4]
2000 10 20 30 40 50
4000 2000 2002 2004 2006 2008

P[0] P[1] P[2] P[3] P[4]


P *p *(p+1) *(p+2) *(p+3) *(p+4)
2000 10 20 30 40 50
4000 a[0] a[1] a[2] a[3] a[4]

after
a[0] a[1] a[2] a[3] a[4]
p++
2002 10 20 30 40 50
4000 2000 2002 2004 2006 2008
79 C-Family | pointers

let us see one more example, here the pointer assigned with p=&a[2] , then observe following picture

P[-2] P[-1] P[0] P[1] P[2]


*(p-2) *(p-1) *(p) *(p+1) *(p+2)
P a[0] a[1] a[2] a[3] a[4]
2004 10 20 30 40 50
4000 2000 2002 2004 2006 2008

Here p[-2] access a[0],


p[-1] access a[1],
p[0] access a[2],
p[1] access a[3],
void main()
{ int a[5] = {10, 20, 30, 40, 50};
p = &a[2]; // p=a+2;
for( i=-2; i<2; i++ )
printf(“%d “, p*i+ or *(p+i) ) ;
}
----------------------------------------------------------------------------------------------------------------------------------------------
17) Complete following fill() function by filling with 5 values: 14, 34, 37, 56, 20
void main()
{ int arr[5], i ;
fill( arr); or fill( &arr[0] );
printf(“\narray after filling values: ”);
for( i=0; i<5; i++ )
printf(“%d “, arr*i+ ); // expected output: 14, 34, 37, 56, 20
}
void fill( int p[ ] or int *p )
{ -----
-----
}
----------------------------------------------------------------------------------------------------------------------------------------------
18) Write functions called read() & write(), the function read() scans 5 values from keyboard and stores into
array and the function write() prints such 5 values on the screen.
ip: 12 32 43 57 11
op: 12 32 43 57 11
void main()
{ int a[5];
read( --- );
write( --- );
}
void read( --- )
{ ------
}
void write( --- )
{ ------
}
80 C-Family | pointers

-------------------------------------------------------------------------------------------------------------------------------------------
19) Extension to above program, read two array of 5 values to each and check two array inputted same
values in same order or not? Let two arrays are A[] and B[]
ip: 12 32 43 57 11 for A[] ip: 12 32 43 57 11 for A[]
12 32 43 57 11 for B[] 22 42 14 57 11 for B[]
op: yes op: no
the main() fn is as follows
void main()
{ int a[5], b[5], bool;
read( --- ); // read 5 values to A[]
read( --- ); // read 5 values to B[]
bool=compare(---,---);
if(bool==1)
printf(“yes”);
else
printf(“no”);
}
void read( --- )
{ ------
------
}
void compare( ---- , ---- )
{ ------
------
}
--------------------------------------------------------------------------------------------------------------------------------------------
20) Write 2 functions called read() & write(), the function read() scans n values from keyboard and assigns
into array and the function write() prints such n values on the screen.
void main()
{ int a[20], n; // Let us say n<20
read(&a[0] , &n );
write(&a[0] , n );
}
void read( int pa[ ] , int *pn )
{ ------
------
}
void write( int pa[ ] , int n )
{ ------
------
}
--------------------------------------------------------------------------------------------------------------------------------------------
21) Write a function called findBigSmall(), which takes array base address & number of values in the array
and To return the big & small of them. Later write a main() function to test it.
void findBigSmall( int a[] , int n , int *pBig , int *pSmall );
-------------------------------------------------------------------------------------------------------------------------------------------
81 C-Family | pointers

22) Write a function to search given value in the array or not, let array contained 10 unique values.
void main()
{ int a[10]={11, 34, 88, 49, 15, 66, 45, 23, 32, 17 };
int searchValue, bool;
printf( “enter searching value:” );
scanf( “%d”, &searchValue );
bool=search( &a[0] , searchValue );
if(bool==1)
printf(“element exist”);
else
printf(“element not exist”);
}

int search( ----- ) // this function returns bool value


{ ------
------
}
-------------------------------------------------------------------------------------------------------------------------------------------
23) Write a function to copy one array of integer values to another array, this function takes destination &
source array base address and number of elements to copy and returns nothing; later write a main()
function to test this.
void main()
{ int a[20]={12, 45, 78, 22, 10, 21, 44, 53}, n=8;
int b[20];
copyArray( b, a, n ); // it is like b=a, copy elements a*+ to b*+ for ‘n’ elements
printf(“\n after copying elements, the array b*+ is :”);
for(i=0; i<n; i++)
printf( “%d “, b*i+ );
}
void copyArray( int dest[], int source[], int n)
{
--------
--------
}
--------------------------------------------------------------------------------------------------------------------------------------------
24) Write functions called compare() & search() which compares two array have same values or not?
Let both arrays initialized with 5 unique values, the compare() takes help of search() fn to search for
element.
Note: Elements in first array may present any position in the second array, the main fn is as follows
void main()
{ int bool;
int a[5]={11, 34, 88, 49, 15 };
int b[5]={34, 11, 88, 15, 49 };
bool=compare( &a[0] , &b[0] );
if(bool==1) printf(“both have same values”);
else printf(“both have not same values”);
}
82 C-Family | pointers

int compare( --- , --- )


{ ------
bool=search(----);
-----
}
int search( ----- ) // like above search fn
{ ------
------
}
--------------------------------------------------------------------------------------------------------------------------------------------

25) Complete the following code to print 2 array values.


void main()
{ int a[3]={11,22,33};
int b[3]={44,55,66}; P[0] P[1]
int *p[2]; 2020 2090
p[0]=&a[0];
a[0] a[1] a[2] b[0] b[1] b[2]
p[1]=&b[0]; 11 22 33 44 55 66
for(i=0; i<2; i++) 2020 2090

{ for(j=0; j<3; j++)


printf( -----); // fill yourself.
printf(“\n”);
}
}
--------------------------------------------------------------------------------------------------------------------------------------------
26) Complete the following code to print 2 array of values, the output should be
11 22 33
44 55 66
void main()
{ int *p[2];
fill( ----- );
for(i=0; i<2; i++)
{ for(j=0; j<3; j++)
printf( -----);
printf(“\n”);
}
}
void fill( ---- )
{ int *x, *y;
x=(int*)malloc(sizeof(int)*3); P[0] P[1]
y=(int*)malloc(sizeof(int)*3); 2020 2090
x[0]=11, x[1]=22, x[2]=33;
11 22 33 44 55 66
y[0]=44, y[1]=55, y[2]=66; 2020 2090
------
------
}
---------------------------------------------------------------------------------------------------------------------------------------------
83 C-Family | pointers

*27) In the beginning examples, the swap() fn swaps only given variable values of specific type, now extend
above swap() fn to work for any data type, here swap byte by byte using char* pointer.
This function takes three arguments: address of variable1, variable2 and sizeof(data);

1011 1111 1010 1100 0000 1010 0011 0000


x[0] x[1] y[0] y[1]

void swap(void *p, void *q, int size);


{ char *x, *y;
x=(char*)p; // type casting, converting void* to char*
y=(char*)q;
for(i=0; i<size; i++)
{ --------
-------- // here swap byte by byte using *(x+i) and *(y+i) or x[i] or y[i]
--------
}
}
void main()
{ int a=12, b=13;
float c=12.45, d=45.59;
swap( &a, &b, sizeof(int) );
printf(“\n after swapping a, b values are %d %d”, a, b );
swap( &c, &d, sizeof(float) );
printf(“\n after swapping c, d values are %d %d” , c, d );
}

---------------------------------------------------------------------------------------------------------------------------------------------
28) Guess the output of following program.
void main()
{ int x=10,y=20;
increment( &x , &y );
printf(“x = %d , y = %d “, x , y ); // expected output is 35 but shows 25.
}
void increment( int *p , int *q )
{
*p++; // this is double action, *p is first action and p++ is second action.
(*q)++; // this is single action, increments ‘y’ value of main() fn.
}
-------------------------------------------------------------------------------------------------------------------------------------------
84 C-Family | Strings

Strings
01) Code to accept a character and find whether it is lower case alphabet/upper case alphabet/digit /any
other special character.
ip: A ip: $
op: upper case alphabet op: special symbol
----------------------------------------------------------------------------------------------------------------------------------------------
02) Code to accept an alphabet from keyboard and convert to opposite case; if lower case alphabet then
converts it into upper-case alphabet and vice-versa.
ip: A ip: a
op: a op: A
----------------------------------------------------------------------------------------------------------------------------------------------
03) Code to print given character ASCII value on the screen.
ip: A ip: a
op: 65 op: 97
example: char ch=’A’;
printf( “the ASCII value of %c is %d”, ch , ch);  the ASCII value of A is 65
%c  prints ASCII symbol, whereas %d  prints ASCII code
---------------------------------------------------------------------------------------------------------------------------------------------
04) Write a function called getUpper(), it returns given alphabet to upper case, later write main() function to
test it. For example,
void main()
{ char ch=’a’;
ch=getUpper(ch);
printf(“upper cae is %c”, ch);
}
char getUpper(char ch)
{ ------
------
}
---------------------------------------------------------------------------------------------------------------------------------------------
05) Following program accepts two numbers from keyboard but each of this number contain only single digit
as input and these are in character format, scanned by getchar() or scanf() function, it prints addition of
these two numbers, but shows wrong output, fix it.
void main()
{ char v1 , v2 ;
int v3;
v1=getchar() or scanf(“%c”, &v1);
v2=getchar() or scanf(“%c”, &v2);
v3=v1+v2;
printf(“%d “, v3);
}

ip: 3 4 // in (v1,v2) , the values (51,52) is stored, which are ASCII values of (‘3’,’4’ chars), thus output is 103
op: 103 // wrong output

Note: ASCII value of ‘0’ is 48, ‘1’ is 49, ‘2’ is 50,… so subtract 48 from v1 & v2 to get equal numeric value
--------------------------------------------------------------------------------------------------------------------------------------------
06) following code shows ASCII symbols of A-Z and a-z
for( i=0; i<26; i++)
printf(“%c”, 65+i); or printf(“%c”, ‘A’+i ); // output is: ABCDEF ….Z

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


printf(“%c”, 97+i); or printf(“%c”, ‘a’+i ); // output is: abcdef …z
85 C-Family | Strings

using above code samples, print following output as shown below (print 6 rows only)
ABCDEF
ABCDE
ABCD
ABC
AB
A
---------------------------------------------------------------------------------------------------------------------------------------------
07) Code to accept name of a person and print ASCII value of every character
ip: Sri hari
op: S=83, r=144, i=105, space=32, H=72, a=97, r=144, i=105
--------------------------------------------------------------------------------------------------------------------------------------------
08) Code to count number of vowels in a given string
ip: all fruits are apples
op: vowel count=7
-------------------------------------------------------------------------------------------------------------------------------------------
09) Code to accept a string from keyboard and count upper and lower case alphabets separately
ip: C-Family
op: Upper case is 2
Lower case is 5
--------------------------------------------------------------------------------------------------------------------------------------------
10) Code to accept a string from keyboard and convert upper-case alphabets to lower-case and vice-versa
ip: C-Family
op: c-fAMILY
--------------------------------------------------------------------------------------------------------------------------------------------
11) Code to accept a string and print in reverse form. (print from last character to first character)
ip: srihari
op: irahirs
--------------------------------------------------------------------------------------------------------------------------------------------
12) Code to accept a string and print alternative characters.
ip: computer
op: cmue
--------------------------------------------------------------------------------------------------------------------------------------------
13) Code to accept a string and print following way
ip: computer
op: computer
omputer
mputer
puter
uter
ter
er
r
--------------------------------------------------------------------------------------------------------------------------------------------
14) Code to accept a string and print following way
ip: computer
op: computer
compute
comput
compu
comp
com
co
c
86 C-Family | Strings

---------------------------------------------------------------------------------------------------------------------------------------------
15) Code to accept a string, the string may have digits, now print sum of all digits, for example
ip: ABC9DEF8GH35XYZ6
op: 9+8+3+5+6  31
----------------------------------------------------------------------------------------------------------------------------------------------
16) Code to accept a string, the string may have numbers, now print sum of all numbers, for example
ip: ABC29DEF38GH135XYZ16
op: 29+38+135+16
----------------------------------------------------------------------------------------------------------------------------------------------
17) Code to accept a multi word string and print no.of words in the string
(Let the words are separated by single space, also try when more spaces exist)
ip: all apples are fruits but all fruits are not apples
op: 10
----------------------------------------------------------------------------------------------------------------------------------------------
18) Code to accept multiword string and print each word length
ip: all apples are fruits
op: 3 6 3 6
--------------------------------------------------------------------------------------------------------------------------------------------
19) Code to accept a multi word string and convert all first characters of each word to upper-case and
remaining to lower case
Ip: all apples are fruits and all fruits are not apples
op: All Apples Are Fruits And All Fruits Are Not Apples
-------------------------------------------------------------------------------------------------------------------------------------------
20) Code to accept a string and print each character frequency
ip: all are good programmers
op: a-3 times repeated
d-1 time repeated
e-2 times repeated ….
------------------------------------------------------------------------------------------------------------------------------------------------
21) Check if two Strings are anagrams of each other?
Two strings are anagrams if they are written using the same exact letters, ignoring space, punctuation, and
capitalization. Each letter should have the same count in both strings. For example, the Army and Mary are
an anagram of each other.
ip1: Army ip1: area
ip2: Mary ip2: are
op: Yes, anagrams op: No, anagrams
---------------------------------------------------------------------------------------------------------------------------------------------
22) One of the most common string interview questions: Find the first non-repeated (unique) character in a
given string, for Example, if given String is "Morning" then it should print ‘M’.
ip: Hello hey ip: Madam
op: o op: d
---------------------------------------------------------------------------------------------------------------------------------------------
23) Code to accept a string and print its length
ip: hello
op: 5
method1: try without using function ( write total code in main() fn )
method2: try by writing user-function, the function take string base address as argument and returns length,
later check with main() fn, this is as given below
87 C-Family | Strings

void main()
{ char a*20+=”computer”;
int k;
k=myStrlen( &a[0] );
printf(“\n length of \’computer\’ is: %d”, k ); // length of ‘computer’ is: 8
k=myStrlen(“hello”);
printf(“\n length of \’hello\’ is: %d”, k); // length of ‘hello’ is: 5
}
int myStrlen( char *p / char p[] )
{ -----
-----
}
---------------------------------------------------------------------------------------------------------------------------------------------
24) Code to reverse given input string, later print on the screen
To reverse the string, swap a[0] by a[n-1], a[1] by a[n-2], a[2] by a[n-3+ , …etc, here ‘n’ is string length

a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9]
‘H’ ‘E’ ‘L’ ‘L’ ‘O’ ‘\0’

a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9]
‘O’ ‘L’ ‘L’ ‘E’ ‘H’ ‘\0’

Logic: try with/without using function, using function, the code is as follows
void main()
{ char a*20+=”HELLO”;
myStrrev(a); or myStrrev( &a[0] );
printf(“output is %s”, a);  OLLEH
}
void myStrrev( char *p / char p[] )
{ -------
-------
}
---------------------------------------------------------------------------------------------------------------------------------------------
25) Write a function to check given string is Palindrome or not? This function returns Boolean value.
(If string and its reverse are equal then it is called Palindrome)
ip: MADAM
op: “yes palindrome”
void main()
{ char a*20+=”MADAM”;
int bool;
bool=isPalindrome( a );
if(bool==1)
printf(“yes, palindrome”);
else
printf(“no, it is not palindrome”);
}
int isPalindrome( char *p )
{ -------
-------
}
---------------------------------------------------------------------------------------------------------------------------------------------
88 C-Family | Strings

26) Write a function called myStrlwr(), to convert all upper case alphabets to lower case.
void main()
{ char a*20+=”ABCdeF”;
myStrlwr(a);
printf(“output is %s”, a);  abcdef
}
void myStrlwr( char *p )
{ -------
-------
}
--------------------------------------------------------------------------------------------------------------------------------------------
27) Let X , Y are two strings, scan and print whether X>Y or X<Y or X==Y
input1: Hello Input1: Hello input1: Hell
input2: Hello input2: Hell input2: Hello
Output: X==Y Output: X>Y Output: X<Y

Logic: Let us try with functions myStrcmp(), the function returns as:
case1: if two strings are equal then return(0)
case2: if two strings are not equal then returns ASCII difference of first un-matched characters
that is +ve/-ve. +ve if X>Y, -ve if X<Y, Zero if X==Y.

void main()
{ char X[20], Y[20];
int k;
printf(“enter string1:”);
gets(X);
printf(“enter string2:”);
fflush(stdin);
gets(Y);
k=myStrcmp( X , Y );
if(k==0) printf(“X==Y”);
else if(k<0) printf(“X<Y”);
else printf(“X>Y”);
}
int myStrcmp( char *p, char *q )
{ -------
-------
}
---------------------------------------------------------------------------------------------------------------------------------------------
28) Extend above program by ignoring case (the alphabets can be upper/lower case)
Input1: Hello
Input2: heLLo
output: X==Y
---------------------------------------------------------------------------------------------------------------------------------------------
29) Program to copy a string from one location to another location (one array to another array)
In programming, it is often need to copy a string from one to another location, for this, if one tries to copy a
string using assignment operator then compiler shows an error.
For example:
char a*20+=”hello World”;
char b[20];
b=a; // b=&a[0];

Here we are trying to assign &a[0] to ‘b’, here ‘b’ is an array, not a pointer, therefore it shows an error.
89 C-Family | Strings

The solution is, copy char-by-char from source to destination array, for example,
b[0]=a[0]
b[1]=a[1]
b[2]=a*2+ ….Using loop

void main()
{ char a*20+=”hello” ;
char b[20];
----- // here copy char-by-char using loop. For example, b*0+=a*0+, b*1+=a*1+, b*2+=a*2+, …etc
printf(“after copy, the string is %s”, b);
}
Using functions, the code is as given below
void main()
{ char a*20+=”hello” ;
char b[20];
myStrcpy( b,a);
printf(“after copy, the string is %s”, b);
}
int myStrcpy( char *destination , char *source ) // destination=source
{ -------
-------
}
--------------------------------------------------------------------------------------------------------------------------------------------
30) Program to accept two strings and append second string at the end of first string
input1: Hello
Input2: World
Output: HelloWorld
logic: try with/without using functions. Using functions, the code is as given below
void main()
{ char a*20+=”hello”, b*20+=”world”;
myStrcat( a , b );
printf(“output is %s”, a ); //helloworld
}
int myStrcat( char *p, char *q )
{ -------
-------
}
---------------------------------------------------------------------------------------------------------------------------------------------
31) Write a program to accept a multi word string and words may separate by more than one space, remove
all unnecessary spaces between words(more than one space) [ this is known as trimming a string]

a l l c h a i r s a r e b l u E \0

a l l c h a i r s a r e b l u e \0

---------------------------------------------------------------------------------------------------------------------------------------------
32) Write a program to accept a multi word string and words may separate by more than one space, remove
all extra spaces between words, extra spaces may happened before & after coma(,) or full stop(.)

t w o a r e r e d , t W o a r e b l u e \0

t w o a r e r e d , t w o a r e b l U e \0
------------------------------------------------------------------------------------------------------------------------------------------------
90 C-Family | Strings

33) Write a function called myStrchr(), to find and return address of first occurrence of given character, if
not exist then return NULL pointer value.
void main()
{ char arr*20+=”all books are expensive”;
char *p;
p=myStrchr(arr, ‘Z’);
if(p==NULL)
printf(“character not found”);
else
printf(“character found”);

p=myStrchr(arr, ‘e’);
if(p==NULL)
printf(“character not found”);
else
printf(“character found”);
}
char* myStrchr( char *p, char ch )
{ -------
-------
}
---------------------------------------------------------------------------------------------------------------------------------------------
34) Program to accept multi word string and print each word in reverse order
(write your own version of function to reverse the word, using it, we can solve easily)
ip: all apples are fruits
op: lla selppa era stiurf
---------------------------------------------------------------------------------------------------------------------------------------------
*35) Program to accept a multi word string and find whether specific sub-string is exist or not?
ip: main-string: all apples are fruits
sub-string: are
op: yes
---------------------------------------------------------------------------------------------------------------------------------------------
36) Extension to above program, write a function called myStrstr(), which takes main-string & sub-string as
arguments and find first occurrence of sub-string in the main-string, if found return its address in
main- string, if not found return NULL.
void main()
{ char a*20+=”C language is function oriented language, C++ is oop oriented language”
char b*20+=”oriented”;
char *p;
p=myStrstr( a , b );
if(p==NULL) printf(“substring found and remaining part of main-string is %s”, p);
else printf( substring not found”);
}
char* myStrstr( char *m , char *s )
{ -------
-------
}
op: substring found and remaining part of main-string is: oriented language, C++ is oop oriented language”
--------------------------------------------------------------------------------------------------------------------------------------------
37) Write a program to accept a multi word string and find how many times the given sub-string is repeated
ip: enter main-string: all apples are fruits but all fruits are not apples
enter sub-string: are
op: 2 times
---------------------------------------------------------------------------------------------------------------------------------------------
91 C-Family | Strings

38) Write a program to accept a multi word string and replace a given sub string with new sub string.
Consider replacing string & new string lengths are equal
ip: enter main-string: all apples are fruits but all fruits are not apples
enter removing-string: are
enter replacing-string: ###
op: all apples ### fruits but all fruits ### not apples
--------------------------------------------------------------------------------------------------------------------------------------------
39) Write a program to accept a multi word string and replace a given sub string with new sub string.
Consider the replacing & new string lengths may or may not be equal
ip: enter main-string: all fruits are good but some are sour
enter sub-string: are
enter replace-string: were
op: all fruits were good but some were sour
-------------------------------------------------------------------------------------------------------------------------------------------
40) Write a program to accept a multiword string, and find biggest word length and print it.
ip: all fruits were good but some were sour
ip: fruits
------------------------------------------------------------------------------------------------------------------------------------------
41) Write a program to accept a text, char by char until user entered ‘^’ as end of input, store all characters
into array, later count no.of words, lines, digits …etc;
ip: “this program is on strings
and getting command over
logic and string manipulations
Today date is 25-2-2020 ^”
op: words count = 13
Lines count = 3
Digits count=7
--------------------------------------------------------------------------------------------------------------------------------------------
42) Write a program to accept an arithmetic simple expression from keyboard and print its sum.
The operators are + - * / % and the values are integers
ip: 10+20 ip: 20*30 ip: 20/10
op: 30 op: 600 op: 2
---------------------------------------------------------------------------------------------------------------------------------------------
43) Write a program to accept long integer value from keyboard and print after adding coma symbol in
appropriate position. (Hint: convert integer value to string and then add coma symbols)
ip: 2983453
op: 29,83,453
-------------------------------------------------------------------------------------------------------------------------------------------
44) Following example explains how to print given numeric single digit in English words, based on this logic,
print for N-digit number.
ip: 3 ip:8
op: three op: eight
void main()
{ char *p[] = {"zero", "one","two","three","four","five","six","seven","eight","nine"};
int n;
printf("enter any single digit :");
scanf("%d",&n);
printf(“%s “, p*n+ );
}
P[0] P[1] p[2] P[3]
2020 2090 3012 5378

“zero” “one” “two” “three”


2020 2090 3012 5378
92 C-Family | Strings

Extend above program to print given number in English words as


ip: 3456
op: three four five six.
Also extend above program to print given number in English words as
ip: 3456
op: three thousand four hundred five six.
-----------------------------------------------------------------------------------------------------------------------------------------
45) Write a program to sort N string into ascending order; the strings are stored in 2D array as

String1 ‘O’ ‘R’ ‘A’ ‘N’ ‘G’ ‘E’ ‘\0’


String2 ‘B’ ‘A’ ‘N’ ‘A’ ‘N’ ‘A’ ‘\0’
String3 ‘G’ ‘U’ ’A’ ‘V’ ‘A’ ‘\0’
String4 ‘A’ ‘P’ ‘L’ ‘L’ ‘E’ ‘\0’

After sorting, the strings are


String1 ‘A’ ‘P’ ‘L’ ‘L’ ‘E’ ‘\0’
String2 ‘B’ ‘A’ ‘N’ ‘A’ ‘N’ ‘A’ ‘\0’
String3 ‘G’ ‘U’ ’A’ ‘V’ ‘A’ ‘\0’
String4 ‘O’ ‘R’ ‘A’ ‘N’ ‘G’ ‘E’ ‘\0’

----------------------------------------------------------------------------------------------------------------------------------------------
46) fill the code to sort N elements in the following program, this program accepts N strings from keyboard,
later sorts N strings into ascending order….
void main()
{ char **p=NULL, a[50];
int N, i;
printf(“enter how many strings :“);
scanf(“%d”, &N);
p=(char**) malloc(sizeof(char**)*N );
for(i=0; i<N; i++)
{ printf("enter string:");
fflush(stdin);
gets(a);
p[i]=(char*)malloc(strlen(a)+1);
strcpy(p[i], a);
}
// write code for sorting (while sorting, if swap is needed then swap addresses not strings)
--------
--------
for(i=0; i<N; i++)
puts(p[i]);
p
}

P[0] “India”
P[1]
P[2] “China”
P[3]
P[4] “USA”

“Pakistan”

“Srilanka”
93 C-Family | Strings

----------------------------------------------------------------------------------------------------------------------------------------------
47) Write a program to accept a multiword string and break down each word into a separate string and store
into separate array of strings as given below
note1: let the words are separated by single space
ip: C++ is one of oop language
p

P[0] “C++”
P[1]
P[2] “is”
P[3]
P[4] “one”

“of”

“oop” …

Note2: Also try when words are separated by more spaces, coma with/without spaces, full stop, etc (here
trim the string before splitting it) , for example, the input string is,
ip: all white are good, all red are damaged ,but all are fruits. Yesterday brought from super market.
--------------------------------------------------------------------------------------------------------------------------------------------
94 C-Family | Strings
95 C-Family | Structures

Structures
01) Write a program to accept student marks like idno, name, marks1, marks2, later find total, average of
marks and print them.
Note: try with & without using functions
ip: 101 Srihari 60 70 (idno, name, marks1, marks2)
op: idno=101 , name=”Srihari” , marks1=60 , marks2=70 , total=130 , average=65.00

Using functions, the code is as follows


struct Student
{ int idno;
char name[30];
int m1, m2, total, avg;
};
void main()
{ struct Student s;
read( &s ); // scan input for idno, name , marks1, mark2 in this function
find( &s ); // find total and average of ‘s’ in this function
write(s); or write(&s) // show output in this function ( use either call-by-value or call-by-reference )
}
void read ( ---- )
{ ---
---
}
void find ( ----)
{ ----
----
}
void write ( ----)
{ ----
----
}
---------------------------------------------------------------------------------------------------------------------------------------------
02) Write a program to accept two dates and find whether they are equal or not?
Note: try with & without using functions
ip: 12 9 2010 ip: 12 9 2010
12 9 2010 13 9 2011
op: equal op: not equal
Note: try with & without using functions
Using functions, the code is as follows
struct Date
{ int d, m, y ;
};
void main()
{ struct Date a , b;
int k;
read( &a ); // scan date1 (day, month, year) using read() function.
read( &b ); // scan date2 (day, month, year)
k=compare( a , b ); // compares two dates and returns 1/0
if( k==1)
printf(“equal”);
else
printf(“not equal”);
}
96 C-Family | Structures

void read( ---- )


{ ---
---
}
int compare( ----)
{ ----
----
}
--------------------------------------------------------------------------------------------------------------------------------------------
03) Write a program to accept two times, let the two times are employee working time in two shifts, later
add & print total time worked in two shifts.
ip: 12 50 58 (shift-1 worked duration : Hours=12, Min=50, Seconds=58 )
2 53 55 (shift-2 worked duration : H= 2, M=53, S=55 )
op: 15hr 44min 53sec (total duration worked in two shifts)
struct Time
{
int h, m, s ;
};
void main()
{ struct Time a,b,c;
read( &a ); // scan time1 (hours, minutes, seconds) in this function.
read( &b ) // scan time2 (hours, minutes, seconds) in this function.
c=add( a , b ); // add two times like c=a+b
write(c); // print output time on the screen
}
void read( ---- )
{ ---
---
}
struct Time add(---, ---)
{ ----
----
}
void write(---)
{ ----
----
}
---------------------------------------------------------------------------------------------------------------------------------------------
04) Code to accept a sample time and increment it by N seconds, here N is also an input.
ip: 12 59 58 (sample time taken from keyboard : Hours=12, Min=59, Seconds=58)
124 (sample no.of seconds to increment, N=124)
op: 13hr 2min 2sec (time after incrementing N seconds)
Note: solve using functions
struct Time
{
int h, m, s ;
};
void main()
{ struct Time t; int n;
read( &t ); // scan time1 (hours, minutes, seconds) at this function.
n=3600; // or else scan N from keyboard
increment( &t , n ); // increment ‘t’ by n seconds
write(t); // print time on the screen
}
97 C-Family | Structures

void read( ---- )


{ ---
---
}
struct Time add(---, ---)
{ ----
----
}
void write(---)
{ ----
----
}
---------------------------------------------------------------------------------------------------------------------------------------------
05) Code to accept two complex numbers and print their sum using functions
ip: 3 4 ( 3 + 4i )
7 3 ( 7 + 3i )
op: 10 + 7i
struct Complex
{
int real, img;
};
-----
-----
---------------------------------------------------------------------------------------------------------------------------------------------
06) Write a program to accept 2 employee details like idno, name, date of joining, later print both
employees joined on same date or not? (The two structures can be taken as)

struct Date struct Employee


{ int d , m , y; { int idno
}; char name[30];
strcut Employee struct Date
{ int idno; { int d, m , y;
char name[30]; } jd ;
struct Date jd; };
};

void main()
{ struct Employee e1 , e2 ;
int k;
read( &e1 );
read( &e2 );
k=compare(e1 , e2);
if(k==0) printf(“equal”);
else printf(“not equal”);
}
void read(---)
{
--------
}
int compare(--- , ---)
{
--------
}
-----------------------------------------------------------------------------------------------------------------------------------------------
98 C-Family | Structures

07) Write a program to accept 2 matrices data of size r x c ( r<10, c<10 ) and print addition of them.
struct Matrix
{ int a[10][10];
int r , c ;
};
void main()
{ struct Matrix a , b , c ;
read( &a );
read( &b );
k=add( &c , a , b );
if(k==0) printf(“Error, addition is failed due to unmatched size” );
else write( c );
}
void read( ---- )
{ ---
---
}
int add( ---- )
{ ---
---
}
void write( ---- )
{ -------
-------
}
-----------------------------------------------------------------------------------------------------------------------------------------
Array of structures
08) Write a program to accept 3 student details such as idno, marks1, marks2 from keyboard and print
total & average of marks. Do with and without functions.
ip: 101 70 70
102 80 90
101 75 75
op: idno m1 m2 total avg
~~~~~~~~~~~~~~~~~~~~~~~~~~
101 70 70 140 70
102 80 90 170 85
103 75 75 150 75

struct Student
{ int idno, m1, m2, tot;
};
void main()
{ struct Student s[3]; // for 3 students
-------
-------
}
the array of structures and its sample data as shown below

S[0] S[1] S[2]


101 70 70 140 102 80 90 170 103 75 75 150
s[0].Idno s[0].m1 s[0].m2 s[0].total s[1].Idno s[1].m1 s[1].m2 s[1].total s[2].Idno s[2].m1 s[2].m2 s[2].total

--------------------------------------------------------------------------------------------------------------------------------------------
99 C-Family | Structures

09) Write a program to accept 5 student details like idno, name, maths, physics and chemistry marks
later find total & rank of students. ( Rank is based on total marks )
ip: 101 Srihari 50 60 70
102 Laxmi 60 70 80
103 Ravi 60 70 80
104 Rahim 80 86 82
105 Tom 97 90 91

op: idno name maths physics chemistry total rank


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
101 Srihari 50 60 70 180 5
102 Laxmi 60 70 80 210 3
103 Ravi 60 70 80 210 3
104 Rahim 80 86 82 248 2
105 Tom 97 90 91 278 1
------------------------------------------------------------------------------------------------------------------------------------------------
*10) Let our database contained 10 person’s name with phone number, write a program to search phone
number using name and vice-verse. Here the database of 10 persons details are initialized in array of
structures and assume name & phone are unique (no duplicates)
ip: Ravi ip: 9440 ip: Laxmi ip: Lavanya ip: 9442
op: 9440 op: Ravi op: 7412 op: not exist op: Ramu

struct Person
{ char name[30];
char phone[15];
};

void main()
{ char str[30], *p;
struct Person p*10+=, ,“Ravi”, “9440”} ,
,“Ramu”, “9442”- ,
,“Lasya”, “8500”} ,
,“Laxmi”, “7412”},
...
};
// nonstop loop to read strings one by one until “end” is pressed, and prints name/phone if found.

while(1)
{ printf(“enter name or phone:”);
gets( str );
if (strcmp(str, “end”)) break;
p=find( p , str );
if(p==NULL)
printf(“not found in the date”);
else
printf(“ %s is found “, p);
}
// this following fn searches for record, if found returns string address or else returns NULL;
char* find( --- , ---)
{ ------
------
}
-----------------------------------------------------------------------------------------------------------------------------------------------
100 C-Family | Structures

*11) Program to add two polynomials using array of structures


5x7+14x5+3x2+10x1+18
15x4+10x3+13x2+7

The two expressions are stored in array of structures as given below

p[0] p[1] p[2] p[3] P[4]


5 7 14 5 3 2 10 1 18 0
Coeff expo Coeff expo coeff expo coeff expo coeff Expo

p[0] p[1] p[2] p[3]


15 4 10 3 13 2 7 0
coeff expo Coeff expo coeff expo coeff expo

struct Poly
{ int expo;
int coeff;
};

void main()
{ struct Poly p1[10], p2[10], p3[10];
int n1, n2, n3; // n1,n2,n3 represents no.of terms in the polynomials.
readPoly(p1, &n1); // accepting first polynomial
readPoly(p2, &n2); // accepting second polynomial
addPoly( p1 , n1 , p2 , n2 , p3 , &n3);
printf("\n The result of polynomial after addition is\n");
printPoly( p3, n3 );
}

void readPoly( struct Poly p[ ], int *limit )


{ int coeff, exponent, i = 0;
while(1)
{ printf("\nEnter coefficient (use -1 to exit :");
scanf("%d",&coeff);
if(coeff == -1) break;
printf("\nEnter exponent: ");
scanf("%d",&exponent);
p[i].expo = exponent;
p[i].coeff = coeff;
i++;
}
*limit=i;
}
void addPoly ( struct Poly p1[ ] , int n1 , struct Poly p2[ ] , int n2 , struct Poly p3[ ] , int *pn3)
{
------
------
}
void printPoly ( struct Poly p[ ] , int n )
{
------
------
}
-----------------------------------------------------------------------------------------------------------------------------------------------
101 C-Family | Structures

*12) Let us simulate bus reservation problem, here reserve/cancel/print seats according to passenger
requirement, the passenger details are: name, age, phone and seat-number is nothing but index of array.
the reservation data holds in the array as given below
struct Passenger
{
char name[30];
int age;
char phone[15];
};

s[0] s[1] s[2] s[3] s[4] …


Dummy 2020 NULL 3012 5378 …

passenger with passenger with passenger with


seat number 1 seat number 3 seat number 4
(Ravi , 40, 9440) (Ramu , 30, 8440) (Laxmi , 20, 8434)
2020 3012 5378

void main()
{ struct Passenger *arr[21]={NULL}; // let total seats are 20 (first is dummy)
int count=0 // count of passengers
int choice;
while(1)
{ printf(“\n 1. Reserve ”);
printf(“\n 2. Cancel ”);
printf(“\n 3. Print ”);
printf(“\n 0. Exit “);
scanf(“%d”, &choice); // stops when seat number is zero.
if( choice==0) break;
switch( choice )
{ case 1: reserve (arr, &count);
break;
case 2: cancel ( arr, &count);
break;
case 3: print ( arr, count);
break;
case 0: return;
}
}
}

void reserve( struct Passenger *arr[], int *pCount )


{ struct Passenger *p;
p=malloc(--); // dynamically creating space for seat
scanf(“%d“, &seatNo);
if(arr[ seatNo ] != NULL)
, printf(“sorry seat already reserved”);
return;
}
scanf(“%s%d%s”, &p->name, &p->age, &p->phone);
arr[ seatNo]=p;
(*pCount)++; // as one passenger is added.
}
102 C-Family | Structures

void cancel ( struct Passenger *arr[], int *pCount )


{ -----
-----
// use free() function to delete seat-no
}

void print ( struct Passenger *arr[], int count )


{
-----
}
----------------------------------------------------------------------------------------------------------------------------------------------
13) Write a program to manage Bus Route map like add, delete, search, print, …etc;
for example single route like:: Vijayawada  Guntur  Ongole  Nellore  Chennai

Here we have to maintain details like station-name, distance from origin, distance from previous station
the sample structure and main() fn with data as given below
struct Point
{ char pointName[30];
int distanceFromOrigin;
int distanceFromPrevousPoint;
};

Arr[0] Arr[1] Arr[2] Arr[3] Arr[4]

Vijayawada Guntur Ongole Nellore Chennai


( 0, 0 ) ( 40 , 40 ) ( 150 , 110 ) ( 280 , 130 ) ( 450 , 170 )

int main()
{ struct Point *arr[10]={NULL}; // let us say maximum points in a route is 10
addPoint( arr , “null”, “Vijayawada”, 0 );
addPoint( arr , “Vijayawada, “Guntur”, 40 );
addPoint( arr , “Guntur”, “Ongole” , 110 );
addPoint( arr , “Ongole”, “Nellore” , 130 );
addPoint( arr , “Nellore”, “Chennai” , 170 );
showRoute( arr ); [Vij,0,0][Gun,40,40][Ong,150,110][Nell,280,130][Che,450,170]
deletePoint( arr, “Ongole” );
showRoute( arr ); [Vij,0,0][Gun,40,40][Nell,280,240][Che,450,170]
addPoint( arr , "Guntur","Ongole", 110 );
showRoute( arr ); [Vij,0,0][Gun,40,40][Ong,150,110][Nell,280,130][Che,450,170]
searchRoute( arr, “Guntur”, “Chennai”); *Gun,0,0+[Ong,110,110][Nell,240,130][Che,410,170]
}
void addPoint( struct Point *arr[], char *from, char *to, int distance) { ----- }
void deletePoint( struct Point *arr[], char *pointName) { ----- }
void searchRoute( struct Point *arr[], char *from, char *to) { ----- }
void showRoute(struct Point *arr[] ) { ----- }
--------------------------------------------------------------------------------------------------------------------------------------------
103 C-Family | Files

Files
01) This demo program explains how to write & read integers to text file
This program writes 5 integer to file using loop, later read back and shows on the screen.
#include<stdio.h>
void main()
{ writeToFile();
readingBackFromFileAndPrint();
}
void writeToFile()
{ int i;
FILE *fp;
fp=fopen("sample.txt", "wt");
for(i=0;i<5; i++) // writing to file: 20 21 22 23 24
fprintf(fp, "%dLJ", 20+i ); , // LJ  space
fclose(fp);
}
void readingBackFromFileAndPrint()
{ int k , n;
FILE *fp;
fp=fopen("sample.txt", "rt");
while(1)
{ k=fscanf(fp, "%d", &n); // reading integers one by one from file
if(k==0) break; // fscanf() returns 0 when end of file is reached
printf("%dLJ", n ); // printing: 20 21 22 23 24
}
fclose(fp);
}
----------------------------------------------------------------------------------------------------------------------------------------------
02) Same as above program, but binary file organization
in computer, either data/program files are stored only in two formats 1) text-format 2) binary-format
there is no other format except these two formats, whether file is pdf,mp3,mp4,doc, .exe, .o ….etc.
1) What is text format?
A) Here data is written in string format (ascii code of each character), for example the number 1234 is stored
as 49, 50, 51, 52, these are ascii codes of 1,2,3,4. (Remember, these ascii codes again stored each in binary)
B) At end of text file, 26 is inserted as end-of-file mark, this is automatically inserted by fclose() fn.
C) the new line character(\n) is stored in two values \r\n (Unix OS format), but while reading back, it read as
single character ‘\n’ in DOS/Windows system, but in Unix OS, it read as two values.
D) We don’t worry about how to write & read in string format, these things automatically done by library
functions such as fprintf(), fscanf(), fputs(), fgets(), fputc(), fgetc() ..etc.

2) What is Binary format?


A) Here data is written in the form of structures & objects, that is, as it is in program variables. For example,
the N=1234 is stored as it is in 2-byte(int) format of N.
for this, we use fread(), fwrite() functions, no other functions work.
B) for binary files, computer doesn’t insert end-of-file-mark, here read functions identifies based on file-size.
Following example explains, how to work with binary files (above program in binary format)
104 C-Family | Files

#include<stdio.h>
void main()
{ writeToFile();
readingBackFromFileAndPrint();
}
void writeToFile()
{ FILE *fp; int i, n=20;
fp=fopen("sample.txt", "wb");
for(i=0;i<5; i++, n++)
fwrite( &n, sizeof(int), 1, fp ); // for binary files, use only fwrite(), fread()
fclose(fp);
}
void readingBackFromFileAndPrint()
{ int k , n; FILE *fp;
fp=fopen("sample.txt", "rb");
while(1)
{ k=fread(&n, sizeof(n), 1, fp);
if(k==0) break; // fread() returns 0 when end of file is reached
printf("%dLJ", n ); // printing: 20 21 22 23 24
}
fclose(fp);
}
----------------------------------------------------------------------------------------------------------------------------------------------
03) this example explains how to read ‘text’ from keyboard and writing to file, later read back and shows
text content on the screen.
We know text means, a group of lines of sentences, here this program reads text as char by char until user
pressed at end ‘^’ for termination, after reading each char, writes to text file called “sample.txt”, later prints
such file content on the screen.
#include<stdio.h>
void main()
{ readFromKeyboardAndWriteToFile();
readBackFromFileAndShowOnTheScreen();
}
void readFromKeyboardAndWriteToFile()
{ FILE *fp; char ch;
fp=fopen("sample.txt", "wt");
while(1)
{ ch=getchar(); // scanning single char from file
if(ch=='^') break;
fprintf(fp, "%c", ch); // write to file
}
fclose(fp); // saves on disk
}
void readBackFromFileAndShowOnTheScreen()
{ int k; char ch; FILE *fp;
fp=fopen("sample.txt", "rt");
while(1)
{ k=fscanf(fp, "%c", &ch);
if(k==-1) break; // fscanf() returns -1 when end of file is reached
printf("%c", ch); // display char on the screen
}
fclose(fp);
}
----------------------------------------------------------------------------------------------------------------------------------------------
105 C-Family | Files

04) Let our text file have some integers, now read numbers one by one from file and count number of odds
exist in that file. Let the file contained integers as given below.
hint: to read integers from file use fscanf() like fscanf(fp, “%d”, &n);

file name: “input.txt”


12 17 20 13 29 30 32 35 40
43 27 20 21 29 31 39 11 12
10 8 2 1 29
ip: enter file name : ”input.txt”
op: odds count=13
----------------------------------------------------------------------------------------------------------------------------------------------
05) Let our text file contained some numbers, now read numbers one by one from file and copy only odd
numbers into target file.

file name: “input.txt” File name:”output.txt”


12 17 20 13 29 30  17 13 29 35 43 27
32 35 40 43 27 20 21 29 31 39 11 3
21 29 31 39 11 12
10 8 2 3
---------------------------------------------------------------------------------------------------------------------------------------------
06) Write a program to count number of words, lines, digits in a given text file.
Let the file contents as given below
File name: “sample.txt”
Text files contain textual data and may be saved in plain
text or rich text formats. While most text files are
documents created and saved by users, they can also be
used by software developers to store program data.
Examples of text files include word processing
documents, log files, and saved email messages.
contact 9440-030405

ip: file name: “sample.txt”


op: words count = 55
lines count = 6
digits count = 10
---------------------------------------------------------------------------------------------------------------------------------------------
07) Write a program to count number of keywords in a given “C” program file.
For example the keywords are “if”, “else” , “while”, “for”, ….. etc
for example, the input file “big.c” as given below

File name “big.c” Input & output


void main()
{ int a, b, c; ip: file-name ”big.c”
printf(“enter two values:”);
scanf(“%d%d”, &a, &b); op: “if”  found 2 times
if( a>b && a>c) “else”  found 2 times
printf(“big=%d”, a ); “while”  found 0 times
else if(b>c) “for”  found 0 times
printf(“big=%d”, b ); -----
else
printf(“big=%d”, b );
}
106 C-Family | Files

---------------------------------------------------------------------------------------------------------------------------------------------
08) Write a program to accept student details and process them. ( try in text & binary formats )
Accept student details from keyboard and write to file called “input.dat”, later read back, find total,
average, result and store in a separate file called “output.dat”, finally print “output.dat” on the
screen as idno name marks1 marks2 marks3 total average result
101 Srihari 55 65 76 196 65 first class
102 Srinu 30 60 60 150 50 failed

If any subject < 35 then take result=“failed”


If passed then print result based on average
If average >= 60 then result=“first class”
If average >=50 and <60 then result=“second class”
If average <50 then result=“third class”
Let the “input.dat” & “output.dat” files as given below

File name: “input.dat” File name: “output.dat”


101 Srihari 55 65 76 101 Srihari 55 65 76 196 65 “first class”
102 Srinu 30 60 60  102 Srinu 30 60 60 150 50 “failed”
103 laxmi 80 80 70 103 laxmi 50 45 55 150 50 “second
---- ----
void main()
{ readFromKeyboardAndWriteToFile();
processResult(); // “input.dat”  “output.dat”
showOutputFile();
}
void readFromKeyboardAndWriteToFile()
{ ---
---
}
void processResult()
{ ---
---
}
void showOutputFile()
{ ---
---
}
----------------------------------------------------------------------------------------------------------------------------------------------
09) Write a program to remove the comment lines in “C” program code file. Comment is : /* ------ */

‘C’ code file with comments After removing comments, the file is
/* written by srihari,9440-030405 */
void main() void main()
{ in a=10, b=20,c; { in a=10, b=20,c;
/* adding two numbers  c=a+b;
and printing */ printf(“output = %d”, c);
c=a+b; }
printf(“output = %d”, c);
}

--------------------------------------------------------------------------------------------------------------------------------------------
107 C-Family | Files

10) Some programmers write code in awkward (not free readable style), now write a program to rearrange
the “C” program code file into readable format. for example

‘C’ code file with awkward style After processing readable style, the file is
void main() { in a,b,c; void main()
printf(“enter two values”); { in a,b,c;
scanf(“%d%d”, &a, &b); c=a+b; printf(“enter two values”);
printf(“output = %d”, c);  scanf(“%d%d”, &a, &b);
} c=a+b;
printf(“output = %d”, c);
}
1. start every instruction in new line
2. instructions in the block {} must be appeared
inside the block with tab space
----------------------------------------------------------------------------------------------------------------------------------------------
A menu driven program to handle employee records
This program manages employee information: it supports adding newly joined employee details, deleting
relieving employee record, modifying address or any other information of employee, printing particulars.
Employee details are stored in a separate file called "emp.dat".
This menu run program provides the user to select his choice of operation.
Menu Run
--------------------------------
1. Adding new employee
2. Deleting employee record
3. Modifying existing record
4.Printing employee details
0. Exit
Enter choice [1,2,3,4,0]:
#include<stdio.h>
typedef struct // structure of an employee
{ int empNo;
char name[30];
char address[100];
float salary;
}EMP;
void append(); void modify(); void delete(); void print(); // fn proto-types
void main()
{ int choice;
while(1) // loop to display menu continuously
{ printf("\n\n ================================================================");
printf("\n 1.append \n 2.delete \n 3.modify\n 4 print \n 0.exit");
printf("\n Enter choice [1,2,3,4,0]:");
scanf("%d", &choice);
switch(choice)
{ case 1: append(); break;
case 2: delete(); break;
case 3: modify(); break;
case 4: print(); break;
case 0: exit(0);
}
}
}
108 C-Family | Files

// this append function appends a record in the file


void append()
{ FILE *fp; EMP e;
fp=fopen("emp.dat", "ab");
if(fp==NULL)
{ printf("\nUnable to open emp.dat file");
return;
}
printf("\n enter employee no:");
scanf("%d",&e.empNo);
printf("Enter employee name:");
fflush(stdin);
gets(e.name);
printf("enter address :");
gets(e.address);
printf("enter salary :");
scanf("%f",&e.salary);
fwrite(&e,sizeof(e),1,fp);
fclose(fp),
printf("\n successfully record added");
}
/* Delete function, deletes a record in the file
Generally, it is not possible to delete a record in a file. Alternative is, copying all records into another temporary file except
deleting record; later temporary file will be renamed with original file name. */

void delete()
{ FILE *fp,*ft; EMP e;
int eno, found=0, k;
fp=fopen("emp.dat", "rb");
ft=fopen("temp.dat","wb");
if(fp==NULL || ft==NULL )
{ printf("\nunable to open file");
fclose(fp);
fclose(ft);
return;
}
printf("\nenter employee number to delete record :");
scanf("%d",&eno);
while(1)
{ k=fread(&e,sizeof(e),1,fp);
if(k==0)break;
if(eno==e.empNo)
found=1; // record is found
else
fwrite(&e,sizeof(e), 1 ,ft);
}
if(found==1) printf("\nRecord deleted success fully");
else printf("\nRecord Not found");
fclose(fp);
fclose(ft);
remove("emp.dat");
rename("temp.dat","emp.dat");
}
109 C-Family | Files

/* Modifying information in a given record


First, it searches for modifying record in a file, if record is not found then displays error message & returns.
If found, the old address overwrites by new address of a record */
void modify()
{ EMP e;
int found=0 , eno, k;
long int pos;
FILE *fp;
fp=fopen("emp.dat","rb+");
if(fp==NULL) { printf("\nfile not found "); exit(0); }
printf("\n enter employee number:");
scanf("%d",&eno);
while(1)
{ k=fread(&e,sizeof(e),1,fp);
if(k==0) break;
if(eno==e.empNo)
{ found=1; // record is found
break;
}
}
if(found==0) { printf("\n Record not found"); return; }
pos=ftell(fp);
pos=pos-sizeof(e);
fseek(fp, pos, SEEK_SET); // move the file pointer one position back
printf("old address : %s", e.address);
printf("\n Enter New address :");
fflush(stdin);
gets(e.address);
fwrite(&e,sizeof(e), 1 ,fp);// overwriting old record
fclose(fp);
printf("\n address suceessfully modified");
}

// print function, prints the given record in “emp.dat” file by searching it


void print()
{ EMP e; int k, count=0; FILE *fp;
fp=fopen("emp.dat", "rb");
if(fp==NULL) {printf("\nfile not found "); return; }
while(1)
{ k=fread(&e,sizeof(e), 1,fp);
if(k==0) break;
printf("\n employee number: %d",e.empNo);
printf("\n employee name : %s",e.name);
printf("\n Address : %s", e.address);
printf("\n Salary: %f", e.salary);
count++;
}
printf("\n(%d) records found", count);
fclose(fp);
}
-----------------------------------------------------------------------------------------------------------------------------------------------
110 C-Family | Files
111 C-Family | C++ Programs

C++ Programs List


A class called ‘Adder’ where find total of two numbers. Following ADT class help you.
class Adder
{ private:
int a, b, total;
public:
void scan()
{
// herer scan two input values into a, b (eg: use scanf() function)
}
void add()
{
// add a, b and assign to ‘total’
}
void show()
{
// print ‘total’ (eg: use printf() function )
}
};
void main()
{ Adder ob;
ob.scan();
ob.add();
ob.show();
}
-----------------------------------------------------------------------------------------------------------------------------------------------
2) Implement a class called Employee where write functions scanSalary(), calculateTax(), printTax().
tax calculation process:
if salary<=10000 then tax=0
if salary>10000 and salary<=20000 then tax is 5% on salary
if salary>20000 then tax is 8% on salary.
The ADT class as given below
class Employee
{ private:
float salary, tax;
public:
void scanSalary(); // scan ‘salary’
void calculateTax(); // calculate ‘tax’
void printTax(); // print ‘tax’
}
void main()
{ Employee ob;
ob.scanSalary();
ob.calculateTax();
ob.printTax();
}
-----------------------------------------------------------------------------------------------------------------------------------------------
112 C-Family | C++ Programs

3) Implement a class called ‘Student’, where write functions scan(), calculate();


calculating result:
total=mark1+mark2;
average=total/2;
if student got <35 in mark1 or mark2 then result=“failed”
or else, result=”A-grade/B-grade/C-grade” based on average
if average>=60 result=“A-grade”
if average>=50 and <60 result=“B-grade”
if average<50 result=“C-grade”
class Student
{ private: int idno, mark1, mark2, total;
float avg;
char *result, name[30]
public:
void scan();
void calculate();
void printResult()
{
printf(“output: %d %s %d %d %d %f %s”,idno,name,marks1,makrs2,total,average,result);
}
}
void main()
{ Student ob;
ob.scan();
ob.calculate();
ob.printResult();
}
-----------------------------------------------------------------------------------------------------------------------------------------------
4) Extend above program to handle 5 students details (idno, name, marks1, marks2, total, average & result)
and show result of 5 students as shown in main() fn.
void main()
{ Student ob[5]; // let us have 5 students, array of 5 objects
ob[0].set(101 , “Hari”, 82, 67); // set( idno, name, marks1, marks2);
ob[1].set(102 , “Seetha”, 94, 77);
ob[2].set(103 , “Ramya”, 70, 80);
ob[3].set(104 , “Laxmi”, 54, 79);
ob[4].set(105 , “Balu”, 56, 56);
printf(“\n indo, name, mark1, mark2, total, average, result”);
printf(“\n===============================================”);
for(i=0; i<5; i++)
ob[i].showResult();
}
-----------------------------------------------------------------------------------------------------------------------------------------------
113 C-Family | C++ Programs

5) Implement a class called Circle where write functions setRadius(), calculate(), print().
The ADT class as given below
class Circle
{ private: int radius;
float area, perimeter;
public: void setRadius(int radius);
void calculate(); // calculates area and perimeter of a given radius
void show(); // displays radius, area and perimeter values
}
void main()
{ Circle ob;
ob.setRadius(5);
ob.calculate();
ob.show(); // radius=5, area=78.746, perimeter=31.45
}
-----------------------------------------------------------------------------------------------------------------------------------------------
6) Implement a class called PrintNumbers where write functions setN(), print1toN(), print1toNOdds(),
printTable(). The ADT class as given below,
class PrintNumbers
{ private: int N;
public: void setN(int N);
void print1toN(); // prints 1,2,3,4, ….N
void print1toNOdds(); // prints 1,3,5,7, … N
void printTable(); // if N=8 then 8*1=8, 8*2=16, 8*3=24, … upto 10 times
};
void main()
{ PrintNumbers ob;
ob.setN(8);
ob.print1toN();
ob.print1toNOdds();
ob.printTable();
}
-----------------------------------------------------------------------------------------------------------------------------------------------
7) Implement a class called Bank with following functionalities
class Bank
{ float balance;
float countOfTransactions.
Bank() { balance=0; } // this constructor function automatically called when object is created
void showBalance(); // show balance on the screen
void deposit(float amount); // add amount to balance & show message “successfully deposited”
void withdraw(float amount); // if amount>balance then print error message called “transaction
failed/insufficient funds” otherwise subtract amount from balance & print ”successfully withdrawn”
void showCountOfTransactions(); // every deposit & withdrawal is a transaction.
};
114 C-Family | C++ Programs

void main()
{ Bank ob;
ob.showBalance(); // current balance = 0/-
ob.deposit(1200); // successfully deposited = 1200/-
ob.showBalance(); // current balance = 1200/-
ob.withdraw(700); // successfully withdrawn = 700/-
ob.showBalance(); // current balance = 500/-
ob.withdraw(3200); // transaction failed, insufficient funds, balance is 500/- only
ob.showCountOfTransactions(); // no.of transactions are: 3
}
Also test above class using following main() fn ( this is menu-run program)
void main()
{ Bank ob;
while(1)
{ printf(“\n 1. Deposit \n2.Withdraw \n3.Show balance \n4.Count of transactions \n0.exit”);
printf(“\n Enter choice [1|2|3|4|0] :”);
scanf(“%d”, &ch);
switch(ch)
{ case 1: printf(“enter deposit amount :”);
scanf(“%f”, &amount);
ob.deposit(amount);
break;
case 2: printf(“enter withdrawal amount:”);
scanf(“%f”, &amount);
ob.withdraw(amount);
break;
case 3: ob.showBalance();
break;
case 4: ob.showCountOfTransactions();
break;
case 0: exit(0);
}
}
}
------------------------------------------------------------------------------------------------------------------------------------------------
8) Implement a class called Player where it holds player name and score as data members and it
counts(records) score and displays when it is required. Based on given main() fn, implement class and its
functionality. The main is as follows
void main()
{ Player ob1(“Ram”); // the object ‘ob1’ for player-1, initialize player name with “Ram” and score with 0.
Player ob2(“Ravi”); // the object ‘ob2’ for player-2, initialize player name with “Ravi” and score with 0.
ob1.addScore(10);
ob2.addScore(20);
ob1.addScore(7);
ob2.addScore(12);
ob1.showScore(); // Ram score is 17
ob2.showScore(); // Ravi score is 32
115 C-Family | C++ Programs

int total= ob1.getScore()+ob2.getScore(); // getScore() returns score of players


printf(“total score is %d “, total ); // displaying total score two players.
}
------------------------------------------------------------------------------------------------------------------------------------------------
9) Implement a class called Game where two players play this game, here add score as given below
void main()
{ Game ob(“Ram”, “Ravi”); // this single object holds two players name & their score.
ob.addScore(“Ram”, 5); // first argument is player name and second argument is score he made.
ob.addScore(“Ravi”, 2); // Ravi made 2 points score
ob.addScore(“Ravi”, 4); // Ravi made 4 points score
ob.addScore(“Ram”, 1); // first argument is player name and second argument is score he made.
ob.addScore(“Ram”, 7); // Ram made 7 points score
ob.addScore(“Rani”, 3); // error, invalid player name Rani
ob.showScore(“Ram”); // Ram’s score is: 13
ob.showScore(“Ravi”); // Ravi’s score is: 6
ob.showScore(); // displays two players score: Ram score is 13, Ravi score is 5
}
-----------------------------------------------------------------------------------------------------------------------------------------------
10) Implement a class called MyDate with 2 functions set() and isEqual(), the set() function sets the object
with sample values like ob.set(12,3,2019) whereas isEqual() compares equality of two dates and returns bool
value, the main() function is as follows
class MyDate
{ int d , m , y;
void set( int , int , int );
int isEqual(MyDate ob2);
};
void main()
{ MyDate ob1, ob2;
ob1.set(12,3,2019);
ob2.set(13,3,2019);
int k=ob1.isEqual(ob2);
if(k==1) printf("equal");
else printf("not equal");
}
-----------------------------------------------------------------------------------------------------------------------------------------------
11) This is same as above program, instead of setting sample values through set() function, read from
keyboard. Now implement a class called MyDate with 2 functions scan() and isEqual(), the scan() function
reads values from keyboard, whereas isEqual() compares given two dates equal or not and returns bool
value, the main() function is as follows
void main()
{ MyDate ob1, ob2;
ob1.scan();
ob2.scan();
int k=ob1.isEqual(ob2);
if(k==1) printf("equal");
else printf("not equal");
}
116 C-Family | C++ Programs

------------------------------------------------------------------------------------------------------------------------------------------------
12) Implement a class called “Complex” where take two sample complex numbers and print addition of
them, the Abstract class as given below
class Complex
{ int real, img;
void set(int real, int img);
void show();
Complex add(Complex ob2)
{ Complex t;
t.real=real+ob2.real;
t.img=img+ob2.img;
return t;
}
};
void main()
{ Complex ob1,ob2,ob3;
ob1.set(4,5);
ob2.set(7,8);
ob3=ob1.add(ob2);
ob3.show(); // 11 + 13i
}
------------------------------------------------------------------------------------------------------------------------------------------------
13) Implement a class called MyTime, where take two sample times like employee working times in two
shifts, now find total time worked by employee. The main() fn is as follows
class MyTime
{
private:
int h,m,s;
public:
void set( int h, int m, int s );
MyTime add( MyTime ob2 );
void show();
};
void main()
{
MyTime ob1, ob2, ob3;
ob1.set(10,40,50);
ob2.set(4,50,40);
ob3=ob1.add(ob2);
ob3.show(); // output: 15:31:30
}
------------------------------------------------------------------------------------------------------------------------------------------------
14) Implement a class called MyTime, where write two functions add() & increment(), these two functions
increments given time by “n” seconds. There is little difference between these two, the add() fn adds N
seconds to time and returns it. This add() fn do not add to given object, it adds to ‘temp’ variable (temporary
object) and returns it, whereas increment() adds to given object; The main() fn is as follows
117 C-Family | C++ Programs

class MyTime
{ int h,m,s;
public:
void set(int h, int m, int s);
MyTime add(int n);
void increment(int n);
void show();
};
void main()
{ MyTime ob1, ob2;
ob1.set(5,40,50);
ob2=ob1.add(3600);
ob2.show(); // 6:40:50
ob1.show(); // 5:40:50  notice, no change of values in this object
ob1.increment(3600); // adds 3600 seconds to ‘ob1’ itself.
ob1.show(); // 6:40:50  notice change of values in the object.
}
------------------------------------------------------------------------------------------------------------------------------------------------
15) Implement a class called MyTime, where increment ‘N’ seconds to given time and also maintain AM/PM.
void main()
{ MyTime ob;
ob.set(11,40,50, ”AM”);
ob.increment(3600); // adds 3600 seconds to time
ob.show(); // output: 12:40:50 PM, after adding 3600 seconds changed AM to PM.
}
class MyTime
{ int h,m,s;
char *amPm;
public:
void set( int h, int m, int s, char *amPm );
void increment( int N );
void show();
};
------------------------------------------------------------------------------------------------------------------------------------------------
16) Implement a class called “List”, where write functions to insert a value, to delete a value, to search a
value, and to print all values. The abstract class as given below
class List
{ int a[100], count;
public:
List(){ count=0;} // this is constructor, automatically called when object is created.
void insert(int v); // inserts value in the array
void delete(int v); // deletes value in the array, if not found then display error message
int search(int v); // to search for value in the array, if found then return 1, otherwise return 0.
void print(); // to print all values in the array.
};
118 C-Family | C++ Programs

void main()
{ List ob;
ob.insert(12);
ob.insert(10);
ob.insert(7);
ob.insert(8);
ob.print(); // 12, 10, 7, 8
ob.delete(7);
ob.print(); // 12, 10, 8
if(ob.search(12)==1) printf(“element found”);
else printf(“element not found”);
}
------------------------------------------------------------------------------------------------------------------------------------------------
17) Implement a class called StudentDatabase where maintain list of <10 students details, the data like
student-name and phone-number. Now our functionality is to search and return phone-number or student-
name based given argument. For this time, let us consider student-name or phone-number is not repeated,
that is, every student name is unique and phone number is also unique. Take student-name as string &
phone as long int type. The main() fn is as follows
void main()
{ StudentDataBase ob;
ob.addStudent(“Ram”, 9440030405);
ob.addStudent(“Ravi”, 9440112113);
ob.addStudent(“Rahim”, 8500117118);
ob.addStudent(“Ibrahim”, 9494113114);
ob.showDetails(“Ram”);  9440030405
ob.showDetails(9440030405L);  Ram
ob.showDetails(“Rahim”);  8500117118
ob.showDetails(“xyz”);  student not found
}
-----------------------------------------------------------------------------------------------------------------------------------------------
18) This is extension to above program, but here consider student-name or phone-number can be
duplicated. The main() fn is as follows
The function getDetails
void main()
{ StudentDataBase ob;
ob.addStudent(“Ram”, 9440030405);
ob.addStudent(“Ravi”, 9440112113);
ob.addStudent(“Rahim”, 8500117118);
ob.addStudent(“Laxmi”, 9440030405);
ob.addStudent(“Ibrahim”, 9440030405);
ob.addStudent(“Ram”, 9440111222);
ob.showDetails(“Ravi”);  9440112113
ob.showDetails(“9440030405”);  Ram , Laxmi
ob.showDetails(“Rahim”);  8500117118
ob.showDetails(“Ram”);  9440030405, 9440111222
}
-----------------------------------------------------------------------------------------------------------------------------------------------
119 C-Family | C++ Programs

19) Implement classes “Student & School” where maintain students ‘fee’ database, here every student has
idno, name & fee, record list of students details as given in main() fn.
class Student
{ int idno;
char name[30];
float fee;
public:
Student(int idno, char name[], float fee); // parameterized constructor
int getIdno()
{ return idno;
}
void show();
};
class School
{ Student *st[10];
int count;
public:
Student()
{ count=0;
}
void addRecord(int idno, char name[], float fee)
{ int i;
for(i=0; i<count; i++)
{ if( p[i]->getIdno()==idno)
{ printf(“error, student %d already paid”, idno);
return;
}
}
Student *a=new Student(idno, name, fee);
p[count]=a;
count++;
}
void show(int idno); // display particular student details like name, fee paid
void showAll(); // display all details of students
};
void main()
{ School ob;
ob.addRecord(105,”Laxmi”, 300.00); // 105 is idno, Laxmi is name, 300.00 is fee
ob.addRecord(101,”Ram”, 150.00);
ob.addRecord(100,”Ravi”, 250.00);
ob.addRecord(105, “Laxmi”, 300.00); // error, already paid
ob.showAll(); // displays all student records
ob.show(101); // op: { 101, “Ram”, 150.00 }
}
-------------------------------------------------------------------------------------------------------------------------------------------
120 C-Family | C++ Programs

20) Implement a class “Bus” where reserve/un-reserve with 10 seats capacity; the classes as given below.
class Passenger
{ int seatNo;
char name[30];
int age;
public:
Passenger(int seatNo, char name[], int age); // parameterized constructor
int getSeatNo()
{ return seatNo;
}
void show();
};
class Bus
{ Pasenger *p[10];
int count;
public:
Bus(){ count=0; }
void reserve(int seatNo, char name[], int age)
{ int i;
for(i=0; i<count; i++)
if( p[i]->getSeatNo()==seatNo)
{ printf(“error, seat already reserved”);
return;
}
Passenger *a=new Passenger(seatNo, name, age);
p[count]=a;
count++;
}
void unReserve(int seatNo);
void show(int seatNo); // display particular passenger details like name , age.
void showAll(); // display all details of passengers
};
void main()
{ Bus ob;
ob.reserve(5,”Laxmi”, 55);
ob.reserve(15,”Ram”, 15);
ob.reserve(10,”Ravi”, 25);
ob.reserve(5, “Rahim”, 44); // error, seat no:5 already reserved
ob.showAll(); // op: seats 5, 15, 25 are reserved and 7 seats left free
ob.unReserve(15); // seat 15 to un reserve
ob.showAll(); //op: seat 5, 25 are reserved and 8 seats left free
ob.show(5); // op: ,5,“Laxmi”,55-
}
-------------------------------------------------------------------------------------------------------------------------------------------
121 C-Family | C++ Programs

21) Implement a class called Stack where maintain list of values (array) with following operations.
Stack is nothing but list of values where we do only two operations (push/pop).
1) write push() function, it inserts a value at the end of array called top of the stack.
2) write pop() function, it delete & returns top element of the stack (lastly inserted value)
3) both push() and pop() function handles error, stack full(overflow), stack empty(underflow)
class Stack
{ private:
int a[10], count;
public:
Stack() { count=0;} // initially no elements in stack
void push(int v);
int pop();
void show(); // prints all elements in the stack.
int emptyStack(); // returns bool value 1/0
}
void main()
{ Stack ob;
ob.push(10);
ob.push(22);
ob.push(13);
ob.push(9);
ob.show(); // 10, 22, 13, 9
k=ob.pop();
printf(“popped value is: %d”, k); // popped values is: 9
k=ob.pop();
printf(“popped value is %d”, k); // popped values is: 13
k=ob.pop();
printf(“popped value is %d”, k); // popped values is: 22
}
------------------------------------------------------------------------------------------------------------------------------------------
22) Implement a class called “DateTime” with following functionalities, the abstract classes looks like as
given below.
class Time
{ int h,m,s;
char *amPm; // AM or PM
public:
void setTime(); // sets the time to 0:0:0
void setTime(int h,int m, int s); // default is AM
void setTime(int h, int m, int s, char *amPm );
void showTime();
void showTime24(); // shows time in 24 format
int incrementTime(int n); // increments the time, if day is changed then it returns how many days
changed, 11:0:0PM + 7200  1:0:0AM ( returns 1-day changed)
// add your own functions if needed
};
122 C-Family | C++ Programs

class DateTime
{ int d,m,y;
Time tm;
public:
void setDateTime(); // all are zeroes
void setDateTime(int day, int mon, int year); // default time is 0:0:0:am
void setDateTime(int day, int mon, int year, int h, int m, int s); // default is “am”
void setDateTime(int day, int mon, int year, int h, int m, int s, char *amPm);
void showTime(); // shows time only
void showTime24(); // shows time in 24 format
void showDateTime(); // shows Date & Time
void showDateTime24(); // shows Date & Time in 24 hr
void showDate(); // shows only date
void incrementDate(int n); // time remains same
void incrementTime(int n); // while incrementing time, if time crossed 12pm then shift to next day.
// add your own functions if needed
};
void main()
{ DateTime dt;
dt.setDateTime(30,1,2019,11,50,50,”AM”);
dt.showDateTime(); // 30-01-2019 @ 11:50:50 AM
dt.incrementTime(3600);
dt.showDateTime(); // 30-01-2019 @ 12:50:50 AM
dt.showDate(); // 30-01-2019
dt.showTime(); // 12:50:50 AM
dt.showTime24(); // 0:50:50
dt.incrementDate(10); // adding 10days to given date
dt.showDateTime(); // 9-02-2019 @ 12:50:50 AM
dt.setDateTime(30,1,2019,11,50,50,”PM”);
dt.showDateTime(); // 30-01-2019 @ 11:50:50 PM
dt.incrementTime(3600);
dt.showDateTime(); // 31-01-2019 @ 12:50:50 AM
}
-----------------------------------------------------------------------------------------------------------------------------------------------
23) Linked list data structure
#include<iostream>
#include<stdio.h>
class LinkedList
{ class Node
{ public:
int data;
Node *next;
Node() { data=0; next=NULL; }
Node(int data) { this->data=data; next=NULL; }
Node* getNext() { return next; }
int getData(){ return data; }
void insertNext(int data)
123 C-Family | C++ Programs

{ Node *temp;
temp=new Node(data);
temp->next=this->next;
this->next=temp;
}
};
Node *head;
public:
LinkedList()
{ head=new Node(); // creating header node, it is dummy in this program.
}
void insertFirst(int data)
{ head->insertNext(data);
}
void insertLast(int data)
{ Node *temp;
temp=head;
while(temp->next!=NULL)
temp=temp->next;
temp->insertNext(data);
}
void showList()
{ Node *temp;
temp=head->next;
printf("\n list is :");
while(temp)
{ printf("%d ", temp->data);
temp=temp->next;
}
}
void deleteFirst()
{ Node *temp;
if(head->next!=NULL)
{ temp=head->next;
head->next=head->next->next;
}
delete temp;
}
void deleteLast()
{ Node *prev,*temp;
temp=head;
if(head->next==NULL)
return;
while(temp->next!=NULL)
{ prev=temp;
temp=temp->next;
}
124 C-Family | C++ Programs

prev->next=NULL;
delete temp;
}
};
//===========================================================================
int main()
{ LinkedList ob;
ob.insertFirst(3);
ob.insertFirst(2);
ob.insertFirst(1);
ob.showList();
ob.deleteLast();
ob.showList();
return 0;
}
-----------------------------------------------------------------------------------------------------------------------------------------------
24. Implement a class called Cricket, store and retrieve score of each person, check following code.
Let us take 11 players with 10 overs maximum in match.
class Cricket
{ int a[11][10][6]; // 11 is no.of players, 10 is max number of overs in match, 6 is balls in over.
void addScore(int playerNo, int over, int ballCount, int runsMade)
{ -------
}
-------
}
void main()
{ Cricket ob;
int playerNo, over, ballCount, runsMade;
while(1)
{ printf(“\n 1.add score \n 2.show player score \n 3.show total 11 players Score \n 0.exit”);
printf(“\n Enter choice * 1|2|3| 0 + :”);
scanf(“%d”, &ch);
switch(ch)
{ case 1: printf(“enter player Number, over number , ballCount(1-6) , runs made :”);
scanf(“%d %d %d %d”, &playerNo, &over, &ballCount, &runsMade);
addScore(playerNo, over, ballCount, runsMade);
break;
case 2: printf(“enter PlayerNo :”);
scanf(“%d”, &playerNo);
ob.showPlayerScore( playerNo);
break;
case 3: ob.showTotalScore ();
break;
case 0: exit(0);
}
}
}
125 C-Family | Java Programs

1) A class called ‘Adder’ where find total of two numbers. Following ADT class help you.
class Adder
{
int a, b, total;
void scan()
{
// herer scan two input values into a, b
}
void add()
{
// add a, b and assign to ‘total’
}
void show()
{
// print ‘total’
}
};
void main()
{
Adder ob=new Adder();
ob.scan();
ob.add();
ob.show();
}
------------------------------------------------------------------------------------------------------------------------------------------
2) Implement a class called Employee where write functions scanSalary(), calculateTax(), printTax().
tax calculation process:
if salary<=10000 then tax=0
if salary>10000 and salary<=20000 then tax is 5% on salary
if salary>20000 then tax is 8% on salary.
The ADT class as given below
class Employee
{ float salary, tax;
void scanSalary(); // scan ‘salary’
void calculateTax(); // calculate ‘tax’
void printTax(); // print ‘tax’
}

void main()
{ Employee ob=new Employee();
ob.scanSalary();
ob.calculateTax();
ob.printTax();
}
------------------------------------------------------------------------------------------------------------------------------------------
3) Implement a class called ‘Student’, where write functions scan(), calculate();
calculating result:
total=mark1+mark2;
average=total/2;
if student got <35 in mark1 or mark2 then result=“failed”
or else, result=”A-grade/B-grade/C-grade” based on average
if average>=60 result=“A-grade”
if average>=50 and <60 result=“B-grade”
if average<50 result=“C-grade”
126 C-Family | Java Programs

class Student
{ int idno, mark1, mark2, total;
double avg;
String name, result;
void scan();
void calculate();
void printResult()
{ System.out.printf(“output: %d %s %d %d %d %lf %s”, idno,name,marks1,makrs2,total,
} average, result);
}
void main()
{ Student ob=new Student();
ob.scan();
ob.calculate();
ob.printResult();
}
-----------------------------------------------------------------------------------------------------------------------------------------------
4) Extend above program to handle 5 students details (idno, name, marks1, marks2, total, average & result)
and show result of 5 students as shown in main() fn.
void main()
{ Student[5] ob; // let us have 5 students, array of 5 objects
ob=new Student[5]; // creates 5 pointers
for( i=0; i<5; i++) // loop to create 5 objects
ob[i]=new Student();
ob[0].set(101 , “Hari”, 82, 67); // set( idno, name, marks1, marks2);
ob[1].set(102 , “Seetha”, 94, 77);
ob[2].set(103 , “Ramya”, 70, 80);
ob[3].set(104 , “Laxmi”, 54, 79);
ob[4].set(105 , “Balu”, 56, 56);
s.o.p(“\n indo, name, mark1, mark2, total, average, result ”);
s.o.p(“\n===============================================”);
for(i=0; i<5; i++)
ob[i].showResult();
}
------------------------------------------------------------------------------------------------------------------------------------------
5) Implement a class called Circle where write functions setRadius(), calculate(), print().
The ADT class as given below
class Circle
{
int radius;
double area, perimeter;
void setRadius(int radius);
void calculate(); // calculates area and perimeter of a given radius
void show(); // displays radius, area and perimeter values
}
void main()
{
Circle ob=new Circle();
ob.setRadius(5);
ob.calculate();
ob.show(); // radius=5, area=78.746, perimeter=31.45
}
------------------------------------------------------------------------------------------------------------------------------------------
127 C-Family | Java Programs

6) Implement a class called PrintNumbers where write functions setN(), print1toN(), print1toNOdds(),
printTable(). The ADT class as given below,
class PrintNumbers
{
int N;
void setN(int N);
void print1toN(); // prints 1,2,3,4, ….N
void print1toNOdds(); // prints 1,3,5,7, … N
void printTable(); // if N=8 then 8*1=8, 8*2=16, 8*3=24, … upto 10 times
};
void main()
{
PrintNumbers ob=new PrintNumbres();
ob.setN(8);
ob.print1toN();
ob.print1toNOdds();
ob.printTable();
}
------------------------------------------------------------------------------------------------------------------------------------------
7) Implement a class called Bank with following functionalities
class Bank
{ double balance;
int countOfTransactions.
Bank() { balance=0; } // this constructor function automatically called when object is created
void showBalance(); // show balance on the screen
void deposit(double amount); // add amount to balance & show message “successfully deposited”
void withdraw(double amount); // if amount>balance then print error message called “transaction
failed/insufficient funds” otherwise subtract amount from balance & print ”successfully withdrawn”
void showCountOfTransactions(); // every deposit & withdrawal is a transaction.
};
void main()
{ Bank ob=new Bank();
ob.showBalance(); // current balance = 0/-
ob.deposit(1200); // successfully deposited = 1200/-
ob.showBalance(); // current balance = 1200/-
ob.withdraw(700); // successfully withdrawn = 700/-
ob.showBalance(); // current balance = 500/-
ob.withdraw(3200); // transaction failed, insufficient funds, balance is 500/- only
ob.showCountOfTransactions(); // no.of transactions are: 3
}
Also test above class using following main() fn ( this is menu-run program)
void main()
{ Bank ob=new Bank();
while(1)
{ printf(“\n 1. Deposit \n2.Withdraw \n3.Show balance \n4.Count of transactions \n0.exit”);
printf(“\n Enter choice [1|2|3|4|0] :”);
scanf(“%d”, &ch);
switch(ch)
{ case 1: printf(“enter deposit amount :”);
scanf(“%f”, &amount);
ob.deposit(amount);
break;
case 2: printf(“enter withdrawal amount:”);
scanf(“%f”, &amount);
128 C-Family | Java Programs

ob.withdraw(amount);
break;
case 3: ob.showBalance();
break;
case 4: ob.showCountOfTransactions();
break;
case 0: exit(0);
}
}
}
------------------------------------------------------------------------------------------------------------------------------------------
8) Implement a class called Player where it holds player name and score as data members and it
counts(records) score and displays when it is required. Based on given main() fn, implement class and its
functionality. The main is as follows The main is as follows
void main()
{ Player ob1(“Ram”); // the object ‘ob1’ for player-1, initialize player name with “Ram” and score with 0.
Player ob2(“Ravi”); // the object ‘ob2’ for player-2, initialize player name with “Ravi” and score with 0.
ob1.addScore(10);
ob2.addScore(20);
ob1.addScore(7);
ob2.addScore(12);
ob1.showScore(); // Ram score is 17
ob2.showScore(); // Ravi score is 32
int total= ob1.getScore()+ob2.getScore(); // getScore() returns score of players
s.o.print(“total score is %d “, total ); // displaying total score two players.
}
------------------------------------------------------------------------------------------------------------------------------------------
9) Implement a class called Game where two players play this game, here add score as given below
void main()
{ Game ob=new Game(“Ram”, “Ravi”); // this single object holds two players name & their score.
ob.addScore(“Ram”, 5); // first argument is player name and second argument is score he made.
ob.addScore(“Ravi”, 2); // Ravi made 2 points score
ob.addScore(“Ravi”, 4); // Ravi made 4 points score
ob.addScore(“Ram”, 1); // first argument is player name and second argument is score he made.
ob.addScore(“Ram”, 7); // Ram made 7 points score
ob.addScore(“Rani”, 3); // error, invalid player name Rani
ob.showScore(“Ram”); // Ram’s score is: 13
ob.showScore(“Ravi”); // Ravi’s score is: 6
ob.showScore(); // displays two players score: Ram score is 13, Ravi score is 5
}
-----------------------------------------------------------------------------------------------------------------------------------------------
10) Implement a class called MyDate with 2 functions set() and isEqual(), the set() function sets the object
with sample values like ob.set(12,3,2019) whereas isEqual() compares equality of two dates and returns bool
value, the main() function is as follows
class MyDate
{
int d , m , y;
void set( int , int , int );
boolean isEqual(MyDate ob2);
};
129 C-Family | Java Programs

void main()
{ MyDate ob1, ob2;
ob1=new MyDate();
ob2=new MyDate();
ob1.set(12,3,2019);
ob2.set(13,3,2019);
boolean k=ob1.isEqual(ob2);
if(k==true) s.o.p("equal");
else s.o.p("not equal");
}
------------------------------------------------------------------------------------------------------------------------------------------
11) This is same as above program, instead of setting sample values through set() function, read from
keyboard. Now implement a class called MyDate with 2 functions scan() and isEqual(), the scan() function
reads values from keyboard, whereas isEqual() compares given two dates equal or not and returns bool
value, the main() function is as follows
void main()
{ MyDate ob1=new MyDate(), ob2=new MyDate();
ob1.scan();
ob2.scan();
boolean k=ob1.isEqual(ob2);
if(k==true) s.o.p("equal");
else s.o.p("not equal");
}
--------------------------------------------------------------------------------------------------------------------------------------------
12) Implement a class called “Complex” where take two sample complex numbers and print addition of
them, the Abstract class as given below
class Complex
{ int real, img;
void set(int real, int img);
void show();
Complex add(Complex ob2)
{ Complex t;
t.real=real+ob2.real;
t.img=img+ob2.img;
return t;
}
};
void main()
{ Complex ob1=new Complex(), ob2=new Complex() ,ob3;
ob1.set(4,5);
ob2.set(7,8);
ob3=ob1.add(ob2);
ob3.show(); // 11 + 13i
}
--------------------------------------------------------------------------------------------------------------------------------------------
13) Implement a class called MyTime, where take two sample times like employee working times in two
shifts, now find total time worked by employee. The main() fn is as follows
class MyTime
{ int h,m,s;
void set( int h, int m, int s );
MyTime add( MyTime ob2 );
void show();
};
130 C-Family | Java Programs

void main()
{
MyTime ob1=new MyTime(), ob2=new MyTime(), ob3;
ob1.set(10,40,50);
ob2.set(4,50,40);
ob3=ob1.add(ob2);
ob3.show(); // output: 15:31:30
}
------------------------------------------------------------------------------------------------------------------------------------------
14) Implement a class called MyTime, where write two functions add() & increment(), these two functions
increments given time by “n” seconds. There is little difference between these two, the add() fn adds N
seconds to time and returns it. This add() fn do not add to given object, it adds to ‘temp’ variable (temporary
object) and returns it, whereas increment() adds to given object; The main() fn is as follows
class MyTime
{ int h,m,s;
void set(int h, int m, int s);
MyTime add(int n);
void increment(int n);
void show();
};
void main()
{ MyTime ob1=new MyTime(), ob2;
ob1.set(5,40,50);
ob2=ob1.add(3600);
ob2.show(); // 6:40:50
ob1.show(); // 5:40:50  notice, no change of values in this object
ob1.increment(3600); // adds 3600 seconds to ‘ob1’ itself.
ob1.show(); // 6:40:50  notice change of values in the object.
}
-----------------------------------------------------------------------------------------------------------------------------------------
15) Implement a class called MyTime, where increment ‘N’ seconds to given time and also maintain AM/PM.
void main()
{ MyTime ob=new MyTime();
ob.set(11,40,50, ”AM”);
ob.increment(3600); // adds 3600 seconds to time
ob.show(); // output: 12:40:50 PM, after adding 3600 seconds changed AM to PM.
}
class MyTime
{ int h,m,s;
String amPm;
void set( int h, int m, int s, String amPm );
void increment( int N );
void show();
};
------------------------------------------------------------------------------------------------------------------------------------------
131 C-Family | Java Programs

16) Implement a class called “List”, where write functions to insert a value, to delete a value, to search a
value, and to print all values. The abstract class as given below
class List
{ int[] arr, size, count; // ‘size’ is size of array, ‘count’ is number of elements.
List( int size)
{ arr=new int[size];
count=0;
this.size=size;
} // this is constructor, automatically called when object is created.
void insert(int v); // inserts value in the array
void delete(int v); // deletes value in the array, if not found then display error message
boolean search(int v); // to search for value in the array, if found then return true, otherwise return false.
void print(); // to print all values in the array.
};
void main()
{ List ob= new List(10);
ob.insert(12);
ob.insert(10);
ob.insert(7);
ob.insert(8);
ob.print(); // 12, 10, 7, 8
ob.delete(7);
ob.print(); // 12, 10, 8
if(ob.search(12)==true)
s.o.p(“element found”);
else
s.o.p(“element not found”);
}
------------------------------------------------------------------------------------------------------------------------------------------
17) Implement classes “Student & School” where maintain students ‘fee’ database, here every student has
idno, name & fee, record list of students details as given in main() fn.

class Student
{
int idno;
String name;
double fee;
public:
Student(int idno , String name , double fee); // parameterized constructor
int getIdno()
{
return idno;
}
void show();
};
class School
{ Student[] arr;
int count;

Student( int size)


{ arr=new Student[size];
count=0;
this.size=size;
}
132 C-Family | Java Programs

void addRecord(int idno, String name, double fee)


{ int i;
for(i=0; i<count; i++)
{
if( arr[i].getIdno()==idno)
{
System.out.printf(“error, student %d already paid”, idno);
return;
}
}
Student s=new Student(idno, name, fee);
arr[count]=s;
count++;
}
void show(int idno); // display particular student details like name, fee paid
void showAll(); // display all details of students
};
void main()
{ School ob=new School();
ob.addRecord(105,”Laxmi”, 300.00); // 105 is idno, Laxmi is name, 300.00 is fee
ob.addRecord(101,”Ram”, 150.00);
ob.addRecord(100,”Ravi”, 250.00);
ob.addRecord(105, “Laxmi”, 300.00); // error, already paid
ob.showAll(); // displays all student records
ob.show(101); // op: { 101, “Ram”, 150.00 }
}
-------------------------------------------------------------------------------------------------------------------------------------------
18) Implement a class “Bus” where reserve/un-reserve with 10 seats capacity; the classes as given below.
class Passenger
{
int seatNo;
String name;
int age;
Passenger(int seatNo, String name, int age); // parameterized constructor
int getSeatNo()
{
return seatNo;
}
void show();
};
class Bus
{ Pasenger[] arr;
int count;
Bus()
{ arr=new Passenger[10];
count=0;
}
void reserve(int seatNo, String name , int age)
{ int i;
for(i=0; i<count; i++)
if( arr[i].getSeatNo()==seatNo)
{
System.out.println(“error, seat already reserved”);
return;
133 C-Family | Java Programs

}
Passenger p=new Passenger(seatNo, name, age);
arr[count]=p;
count++;
}
void unReserve(int seatNo);
void show(int seatNo); // display particular passenger details like name , age.
void showAll(); // display all details of passengers
};
void main()
{ Bus ob=new Bus();
ob.reserve(5,”Laxmi”, 55);
ob.reserve(15,”Ram”, 15);
ob.reserve(10,”Ravi”, 25);
ob.reserve(5, “Rahim”, 44); // error, seat no:5 already reserved
ob.showAll(); // op: seats 5, 15, 25 are reserved and 7 seats left free
ob.unReserve(15); // seat 15 to un reserve
ob.showAll(); //op: seat 5, 25 are reserved and 8 seats left free
ob.show(5); // op: ,5,“Laxmi”,55-
}
-------------------------------------------------------------------------------------------------------------------------------------------
19) Implement a class called Stack where maintain list of values (array) with following operations.
Stack is nothing but list of values where we do only two operations (push/pop).
1) write push() function, it inserts a value at the end of array called top of the stack.
2) write pop() function, it delete & returns top element of the stack (lastly inserted value)
3) both push() and pop() function handles error, stack full(overflow), stack empty(underflow)
class Stack
{
int[] arr, size, count;
Stack( int size)
{ this.size=size;
arr=new int[size];
count=0; // initially no elements in stack
}
void push(int v);
int pop();
void show(); // prints all elements in the stack.
int emptyStack(); // returns bool value 1/0
}
void main()
{ Stack ob=new Stack();
ob.push(10);
ob.push(22);
ob.push(13);
ob.push(9);
ob.show(); // 10, 22, 13, 9
k=ob.pop();
System.out.printf(“\npopped value is: %d”, k); // popped values is: 9
k=ob.pop();
System.out.printf(“\npopped value is %d”, k); // popped values is: 13
k=ob.pop();
System.out.printf(“\npopped value is %d”, k); // popped values is: 22
}
-----------------------------------------------------------------------------------------------------------------------------------------------
134 C-Family | Java Programs

20) Implement a class called Cricket, store and retrieve score of each person, check following code.
Let us take 11 players with 10 overs maximum in match.
class Cricket
{
int arr[11][10][6]; // 11 is no.of players, 10 is max. number of overs in match, 6 is balls in over.
void addScore(int playerNo, int over, int ballCount, int runsMade)
{
-------
}
-------
}
void main()
{ Cricket ob=new Cricket();
int playerNo, over, ballCount, runsMade;
while(1)
{ printf(“\n 1.add score \n 2.show player score \n 3.show total 11 players Score \n 0.exit”);
printf(“\n Enter choice * 1|2|3| 0 + :”);
scanf(“%d”, &ch);
switch(ch)
{ case 1: printf(“enter player Number, over number , ballCount(1-6) , runs made :”);
scanf(“%d %d %d %d”, &playerNo, &over, &ballCount, &runsMade);
ob.addScore(playerNo, over, ballCount, runsMade);
break;
case 2: printf(“enter PlayerNo :”);
scanf(“%d”, &playerNo);
ob.showPlayerScore( playerNo);
break;
case 3: ob.showTotalScore ();
break;
case 0: exit(0);
}
}
}
------------------------------------------------------------------------------------------------------------------------------------------
21) Implement a class called “DateTime” with following functionalities, the abstract classes looks like as
given below.
class Time
{ int h,m,s;
String amPm; // AM or PM
void setTime(); // sets the time to 0:0:0
void setTime(int h,int m, int s); // default is AM
void setTime(int h, int m, int s, String amPm );
void showTime();
void showTime24(); // shows time in 24 format
int incrementTime(int n); // increments the time, if day is changed then it returns how many days
changed, 11:0:0PM + 7200  1:0:0AM ( returns 1-day changed)
// add your own functions if needed
};
class DateTime
{ int d,m,y;
Time tm;
void setDateTime(); // all are zeroes
void setDateTime(int day, int mon, int year); // default time is 0:0:0:am
void setDateTime(int day, int mon, int year, int h, int m, int s); // default is “am”
135 C-Family | Java Programs

void setDateTime(int day, int mon, int year, int h, int m, int s, String amPm);
void showTime(); // shows time only
void showTime24(); // shows time in 24 format
void showDateTime(); // shows Date & Time
void showDateTime24(); // shows Date & Time in 24 hr
void showDate(); // shows only date
void incrementDate(int n); // time remains same
void incrementTime(int n); // while incrementing time, if time crossed 12pm then shift to next day.
// add your own functions if needed
};

void main()
{ DateTime dt=new DateTime();
dt.setDateTime(30,1,2019,11,50,50,”AM”);
dt.showDateTime(); // 30-01-2019 @ 11:50:50 AM
dt.incrementTime(3600);
dt.showDateTime(); // 30-01-2019 @ 12:50:50 AM
dt.showDate(); // 30-01-2019
dt.showTime(); // 12:50:50 AM
dt.showTime24(); // 0:50:50
dt.incrementDate(10); // adding 10days to given date
dt.showDateTime(); // 9-02-2019 @ 12:50:50 AM
dt.setDateTime(30,1,2019,11,50,50,”PM”);
dt.showDateTime(); // 30-01-2019 @ 11:50:50 PM
dt.incrementTime(3600);
dt.showDateTime(); // 31-01-2019 @ 12:50:50 AM
}
------------------------------------------------------------------------------------------------------------------------------------------

You might also like