KEMBAR78
C Problems | PDF | Triangle | C (Programming Language)
0% found this document useful (0 votes)
31 views109 pages

C Problems

This document is a programming guide designed for learners of C language, featuring a comprehensive list of basic programming exercises. It includes 21 chapters with various programming problems, covering topics such as basic programs, loops, functions, and data structures. Each chapter provides detailed instructions and examples for coding in C, aimed at enhancing the understanding of programming concepts.

Uploaded by

gp.ghost2087
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views109 pages

C Problems

This document is a programming guide designed for learners of C language, featuring a comprehensive list of basic programming exercises. It includes 21 chapters with various programming problems, covering topics such as basic programs, loops, functions, and data structures. Each chapter provides detailed instructions and examples for coding in C, aimed at enhancing the understanding of programming concepts.

Uploaded by

gp.ghost2087
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 109

C-Family Computers Index

This pdf suitable for hard copy (print copy for 2-sides)

For Computer Programming


Learners Designed in C-Language

C Programs List
By C-Family Computers, Vijayawada.
C-Family Computers Index

S.NO CHAPTER PAGE Problems


1 Basic Programs 1 35
2 If-Else programs 9 44
3 Loops 17 104
4 Nested Loops 37 50
5 Arrays 43 36
6 Functions 51 25
7 Recursion 59 44
8 Pointers 71 30
9 Strings 83 50
10 Structures 93 15
11 Files 101 12
On Behalf of C-Family Computers, Vijayawada, India, pin:520010, Ph: 9440-030405;
alt: 8500-117118, For feedback: srihari.vijayawada@gmail.com
For self-practice exercises on C language programming, around 500 simple
exercises are given to the beginners or level-1 programmers.
C-Family Computers 1 chapter-1 (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() statements or using single printf(), 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.
---------------------------------------------------------------------------------------------------------------------------------------------------
C-Family Computers 2 chapter-1 (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;
C-Family Computers 3 chapter-1 (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
--------------------------------------------------------------------------------------------------------------------------------------------------
C-Family Computers 4 chapter-1 (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.
--------------------------------------------------------------------------------------------------------------------------------------------------
C-Family Computers 5 chapter-1 (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
--------------------------------------------------------------------------------------------------------------------------------------------------
C-Family Computers 6 chapter-1 (Basic Programs)

*23) 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
--------------------------------------------------------------------------------------------------------------------------------------------------
24) 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
---------------------------------------------------------------------------------------------------------------------------------------------------
-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
--------------------------------------------------------------------------------------------------------------------------------------------------
C-Family Computers 7 chapter-1 (Basic Programs)

*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.

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,….
-------------------------------------------------------------------------------------------------------------------------------------------
C-Family Computers 8 chapter-1 (Basic Programs)

*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 … ]
--------------------------------------------------------------------------------------------------------------------------------------------------
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
------------------------------------------------------------------------------------------------------------------------------------------------
C-Family Computers 9 if-else Programs

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
----------------------------------------------------------------------------------------------------------------------------------------------------
C-Family Computers 10 if-else Programs

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)
---------------------------------------------------------------------------------------------------------------------------------------------------
C-Family Computers 11 if-else Programs

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
---------------------------------------------------------------------------------------------------------------------------------------------------
C-Family Computers 12 if-else Programs

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 then 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
----------------------------------------------------------------------------------------------------------------------------------------------------
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)
----------------------------------------------------------------------------------------------------------------------------------------------------
C-Family Computers 13 if-else Programs

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
--------------------------------------------------------------------------------------------------------------------------------------------------
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)
---------------------------------------------------------------------------------------------------------------------------------------------------
C-Family Computers 14 if-else Programs

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
--------------------------------------------------------------------------------------------------------------------------------------------------
C-Family Computers 15 if-else Programs

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
---------------------------------------------------------------------------------------------------------------------------------------------------
C-Family Computers 16 if-else Programs

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
C-Family Computers 17 Loop Programs

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
--------------------------------------------------------------------------------------------------------------------------------------------------
C-Family Computers 18 Loop Programs

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 -----
}
--------------------------------------------------------------------------------------------------------------------------------------------------
C-Family Computers 19 Loop Programs

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
---------------------------------------------------------------------------------------------------------------------------------------------------
C-Family Computers 20 Loop Programs

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
----
}
----
}
---------------------------------------------------------------------------------------------------------------------------------------------------
C-Family Computers 21 Loop Programs

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
---------------------------------------------------------------------------------------------------------------------------------------------------
C-Family Computers 22 Loop Programs

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 N th 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)
---------------------------------------------------------------------------------------------------------------------------------------------------
C-Family Computers 23 Loop Programs

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 ….
--------------------------------------------------------------------------------------------------------------------------------------------------
C-Family Computers 24 Loop Programs

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
---------------------------------------------------------------------------------------------------------------------------------------------------
C-Family Computers 25 Loop Programs

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) divide 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 ( N!=1 so print “no”)
for example, if N=16 then N=N/2 is 16, 8, 4, 2, 1 ( N==1 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
--------------------------------------------------------------------------------------------------------------------------------------------------
C-Family Computers 26 Loop Programs

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.
----------------------------------------------------------------------------------------------------------------------------------------------------
C-Family Computers 27 Loop Programs

**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)
---------------------------------------------------------------------------------------------------------------------------------------------------
C-Family Computers 28 Loop Programs

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)
---------------------------------------------------------------------------------------------------------------------------------------------------
C-Family Computers 29 Loop Programs

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
---------------------------------------------------------------------------------------------------------------------------------------------------
C-Family Computers 30 Loop Programs

*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
C-Family Computers 31 Loop Programs

--------------------------------------------------------------------------------------------------------------------------------------------------
*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.
--------------------------------------------------------------------------------------------------------------------------------------------------
C-Family Computers 32 Loop Programs

*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.

---------------------------------------------------------------------------------------------------------------------------------------------------
C-Family Computers 33 Loop Programs

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 factors product 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 ;
}
---------------------------------------------------------------------------------------------------------------------------------------------------
C-Family Computers 34 Loop Programs

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
---------------------------------------------------------------------------------------------------------------------------------------------------
C-Family Computers 35 Loop Programs

-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.
---------------------------------------------------------------------------------------------------------------------------------------------------
C-Family Computers 36 Loop Programs
C-Family Computers 37 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
C-Family Computers 38 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
C-Family Computers 39 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
C-Family Computers 40 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)
C-Family Computers 41 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.
C-Family Computers 42 Nested Loops
C-Family Computers 43 Array Problems

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 exist.
--------------------------------------------------------------------------------------------------------------------------------------------------
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 values.
void main()
{ int a[20]={0,1}; // first two values of series are intialized
----------
}
-------------------------------------------------------------------------------------------------------------------------------------------------
04) 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
-------------------------------------------------------------------------------------------------------------------------------------------------
05) 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
-------------------------------------------------------------------------------------------------------------------------------------------------
06) 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
-------------------------------------------------------------------------------------------------------------------------------------------------
07) Code to accept N values from keyboard and check 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)
-------------------------------------------------------------------------------------------------------------------------------------------------
08) 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
--------------------------------------------------------------------------------------------------------------------------------------------------
09) 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
--------------------------------------------------------------------------------------------------------------------------------------------------
C-Family Computers 44 Array Problems

10) A shop keeper sells 10 items from his stock inventory, items 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 0 (stop)
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 this 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

---------------------------------------------------------------------------------------------------------------------------------------------------
11) 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]

-----------------------------------------------------------------------------------------------------------------------------------------------
12) 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 marks of input, 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]

---------------------------------------------------------------------------------------------------------------------------------------------------
C-Family Computers 45 Array Problems

13) 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 by 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 ] ++”
---------------------------------------------------------------------------------------------------------------------------------------------------
14) 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 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 them 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 every cell of a[],
now fill value ‘1’ with a cell where its index is idno ( a[idno]=1) now print index(i) of each a[] where a[i]==1.
The output of this process is automatically in ascending order of all idno’s.
---------------------------------------------------------------------------------------------------------------------------------------------------
15) 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
op: 0 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.
---------------------------------------------------------------------------------------------------------------------------------------------------
16) 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
-------------------------------------------------------------------------------------------------------------------------------------------------
17) 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 of 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] }
--------------------------------------------------------------------------------------------------------------------------------------------------
C-Family Computers 46 Array Problems

18) Code to accept N values from keyboard 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
-------------------------------------------------------------------------------------------------------------------------------------------------
19) 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 ….
--------------------------------------------------------------------------------------------------------------------------------------------------
20) 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 )
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]
-----
---------------------------------------------------------------------------------------------------------------------------------------------
21) 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.
------------------------------------------------------------------------------------------------------------------------------------------------
22) 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
-------------------------------------------------------------------------------------------------------------------------------------------------
C-Family Computers 47 Array Problems

23) 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");
-------------------------------------------------------------------------------------------------------------------------------------------------
24) Write a program to increment given date by 'n' days
step 1: Let, date is scanned to (d,m,y)
step 2: fill(intialize) 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
}
}
}
---------------------------------------------------------------------------------------------------------------------------------------------------
25) 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++)
{ -----
-----
}
}
It is fastest technique to check prime ness of one number with previous primes.
------------------------------------------------------------------------------------------------------------------------------------------------
C-Family Computers 48 Array Problems

26) 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.
-------------------------------------------------------------------------------------------------------------------------------------------------
27) 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.
------------------------------------------------------------------------------------------------------------------------------------------------
28) Code to accept ‘N’ values from keyboard and remove all occurrence of ‘8’ in the array
( if interested, the value ‘8’ can be input )
ip: 14, 10, 9, 8, 10, 8, 8, 8, 11.
op: 14, 10, 9, 10, 11.
-------------------------------------------------------------------------------------------------------------------------------------------------
29) 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.
-------------------------------------------------------------------------------------------------------------------------------------------------
30) 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 ]
C-Family Computers 49 Array Problems

------------------------------------------------------------------------------------------------------------------------------------------------
*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.
---------------------------------------------------------------------------------------------------------------------------------------------------
32) For the following set of sample data, compute the standard deviation(sd) and the mean.
A[] = -6, -12, 8, 13, 11, 6, 7, 2;
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[] array, 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++];
--------------------------------------------------------------------------------------------------------------------------------------------------
34) 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

x0 x1 x2 x3 x4 x5 x6 x7 x8 x9
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]
---------------------------------------------------------------------------------------------------------------------------------------------------
C-Family Computers 50 Array Problems

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

-------------------------------------------------------------------------------------------------------------------------------------------------
-36) 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
the exchange 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.
}
---------------------------------------------------------------------------------------------------------------------------------------------------
C-Family Computers 51 C-Functions

1) Write a function(fn) called big(), which takes two integer arguments and return 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 returns 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)
{ -------
-------
}
--------------------------------------------------------------------------------------------------------------------------------------------------
C-Family Computers 52 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;
k=power(2,3); // call-1
printf(“2^3 = %d”, k);
k=power(3,2); // call-2
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 this 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 divisors 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
---------------------------------------------------------------------------------------------------------------------------------------------------
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)
--------------------------------------------------------------------------------------------------------------------------------------------------
C-Family Computers 53 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 of digits until single digit reached.
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 scan N value repeatedly 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 );
--------------------------------------------------------------------------------------------------------------------------------------------------
C-Family Computers 54 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, or else flag ‘P’ returns Perimeter)
Sometimes flag can be lower-case alphabets, but our function allows such values.
Function proto-type is: float getAreaOrPerimeter( float radius, char flag );
Later write a main() function check 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 find result
}
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)
{
// finds factorial value
}
--------------------------------------------------------------------------------------------------------------------------------------------------
C-Family Computers 55 C-Functions

16) Write a fn called isPrime(), which finds given number is prime or not?
Write main() fn, where scan 5 values to array a[], and find count of primes in the array.
--------------------------------------------------------------------------------------------------------------------------------------------------
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.
--------------------------------------------------------------------------------------------------------------------------------------------------
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)
{
--------
}
---------------------------------------------------------------------------------------------------------------------------------------------------
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 this 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()
{
-----
}
---------------------------------------------------------------------------------------------------------------------------------------------------
C-Family Computers 56 C-Functions

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;
scanf(h,m,s); // scanning time1
n=convertToSeconds(h,m,s);
scanf(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.
Now write main() fn, where scan two dates and find they are equal or not?
void main()
{ int date1,date2;
date1=scanDate();
date2=scanDate();
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()
{
------
}
---------------------------------------------------------------------------------------------------------------------------------------------------
C-Family Computers 57 C-Functions

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);
}
}
---------------------------------------------------------------------------------------------------------------------------------------------------
C-Family Computers 58 C-Functions
C-Family Computers 59 Recursive Problems

1) Fill the body of recursive function show() to print 1 to 10 numbers. (In the following examples don’t use any
loop control structures)
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)
{ -----
-----
}
--------------------------------------------------------------------------------------------------------------------------------------------------
C-Family Computers 60 Recursive Problems

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)
{ ------
-----
}
--------------------------------------------------------------------------------------------------------------------------------------------------
C-Family Computers 61 Recursive Problems

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
C-Family Computers 62 Recursive Problems

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,
--------------------------------------------------------------------------------------------------------------------------------------------------
15) Write a recursive function to print factors of a given number
Input: 18
Output: 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 up to N.
}
void show(int N, int i)
{ -------
}
-------------------------------------------------------------------------------------------------------------------------------------------------
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)
{ -------
}
-------------------------------------------------------------------------------------------------------------------------------------------------
C-Family Computers 63 Recursive Problems

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
}
---------------------------------------------------------------------------------------------------------------------------------------------------
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
{ -------
}
---------------------------------------------------------------------------------------------------------------------------------------------------
C-Family Computers 64 Recursive Problems

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;
show(N);
}
void show(int N)
{ -------
------- // print remainder of N from bottom to up 1101 (show in picture)
}

Note: print remainder of ‘N’ from bottom to top: 1%2, 3%2, 6%2, 13%2 (1, 1, 0, 1)

2 13
2 6- 1
2 3- 0
2 1- 1
0- 1

---------------------------------------------------------------------------------------------------------------------------------------------------
22) Write a recursive function(s) to print following output (don’t use any loop)
12345678
1234567
------
123
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, and every row ends with N.
-----
}
---------------------------------------------------------------------------------------------------------------------------------------------------
C-Family Computers 65 Recursive Problems

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=factorial(5);
printf(“factorial of 5 is %d”, k);
}
int factorial(int N)
{ ----
----
}
----------------------------------------------------------------------------------------------------------------------------------------------------
25) 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 )
{
----
----
}
--------------------------------------------------------------------------------------------------------------------------------------------------
C-Family Computers 66 Recursive Problems

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;
----
}
--------------------------------------------------------------------------------------------------------------------------------------------------
27) 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
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
------
}
----------------------------------------------------------------------------------------------------------------------------------------------------
28) 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)
{ ------
------
}
----------------------------------------------------------------------------------------------------------------------------------------------------
C-Family Computers 67 Recursive Problems

29) 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 )
----------------------------------------------------------------------------------------------------------------------------------------------------
30) 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)
----------------------------------------------------------------------------------------------------------------------------------------------------
31) Write a function to find sum of odd digits only.
ip: 2345
op: odd digits sum = 8 (3+5)
----------------------------------------------------------------------------------------------------------------------------------------------------
32) 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.
----------------------------------------------------------------------------------------------------------------------------------------------------
33) 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
----------------------------------------------------------------------------------------------------------------------------------------------------
34) 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
---------------------------------------------------------------------------------------------------------------------------------------------------
35) 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
C-Family Computers 68 Recursive Problems

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)
{ ----
----
}
----------------------------------------------------------------------------------------------------------------------------------------------------
36) 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

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

---------------------------------------------------------------------------------------------------------------------------------------------------
37) 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.

-----------------------------------------------------------------------------------------------------------------------------------------------
C-Family Computers 69 Recursive Problems

38) 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
}
---------------------------------------------------------------------------------------------------------------------------------------------------
39) 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(….);
}
---------------------------------------------------------------------------------------------------------------------------------------------------
40) 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
{ -------
-------
}
----------------------------------------------------------------------------------------------------------------------------------------------------
C-Family Computers 70 Recursive Problems

41) 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…

---------------------------------------------------------------------------------------------------------------------------------------------------
42) 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…

---------------------------------------------------------------------------------------------------------------------------------------------------
43) Write a program to print all permutations (combinations) of a given string.
Input: abc
Output: abc
acb
bac
bca
cab
cba
---------------------------------------------------------------------------------------------------------------------------------------------------
44) 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
---------------------------------------------------------------------------------------------------------------------------------------------------
C-Family Computers 71 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) 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 but shows 25.
}
void incrementBy10( int p )
{ p=p+10;
}
---------------------------------------------------------------------------------------------------------------------------------------------------
03) 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( --- , --- )
{ ----
}
---------------------------------------------------------------------------------------------------------------------------------------------------
04) 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) but shows (25,35).
}
void swap( int p , int q )
{ int t;
t=p; p=q; q=t;
}
---------------------------------------------------------------------------------------------------------------------------------------------------
C-Family Computers 72 pointers

05) 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) but shows (25,35).
}
void swap1( int *p, int *q )
{
swap2( &p , &q );
}
void swap2( ----, ----)
{
-----
}
---------------------------------------------------------------------------------------------------------------------------------------------------
06) 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) but shows (25,35).
}
void swap1( int *p, int *q )
{
swap2( p, q);
}
void swap2( ----, ----)
{
-----
}
---------------------------------------------------------------------------------------------------------------------------------------------------
07) 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(---------)
{
--------
}
--------------------------------------------------------------------------------------------------------------------------------------------------
C-Family Computers 73 pointers

08) 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
--------
}
---------------------------------------------------------------------------------------------------------------------------------------------------
Returning more values from function using call-by-reference
09) This example explains how sum & product of two numbers returning to 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.
---------------------------------------------------------------------------------------------------------------------------------------------------
10) 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, returns s,p values to sum,product in main() fn through pointers x,y.
*x=s; // sum=s; this is called returning indirectly
*y=p; // product=p;
}
--------------------------------------------------------------------------------------------------------------------------------------------------
C-Family Computers 74 pointers

11) Write a function 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( -----)
{ ------
}
--------------------------------------------------------------------------------------------------------------------------------------------------
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;
-------
}
---------------------------------------------------------------------------------------------------------------------------------------------------
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;
}
---------------------------------------------------------------------------------------------------------------------------------------------------
C-Family Computers 75 pointers

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( h1, m1, s1, h2, m2, s2, &h, &m, &s); // (h,m,s)= (h1,m1,s1) + (h2,m2,s2);
printf(“after adding, output time is : %d : %d : %d”, h, m, s);
}
void add( --------- )
{ ------
------
}
---------------------------------------------------------------------------------------------------------------------------------------------------
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;
printf(“\n Enter date :”);
scanf(“%d%d%d”, &d, &m, &y);
increment( ---- );
printf(“\n output: after incrementing the date is %d %d %d”, d, m, y );
}
void increment( ------- )
{ --------
--------
--------
}
--------------------------------------------------------------------------------------------------------------------------------------------
C-Family Computers 76 pointers

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

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) ) ;
}
-----------------------------------------------------------------------------------------------------------------------------------------------
C-Family Computers 77 pointers

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( --- )
{ ------
}
---------------------------------------------------------------------------------------------------------------------------------------------------
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( --- )
{ ------
------
}
C-Family Computers 78 pointers

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 );
-------------------------------------------------------------------------------------------------------------------------------------------------
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
{ ------
------
}
-------------------------------------------------------------------------------------------------------------------------------------------------
C-Family Computers 79 pointers

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”);
}
int compare( --- , --- )
{ ------
------
bool=search(----);
-----
-----
}
int search( ----- ) // like above search fn
{ ------
------
------
}
--------------------------------------------------------------------------------------------------------------------------------------------------
C-Family Computers 80 pointers

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


void main()
{ int a[3]={11,22,33};
int b[3]={44,55,66};
int *p[2];
p[0]=&a[0];
p[1]=&b[0];
for(i=0; i<2; i++)
{ for(j=0; j<3; j++)
printf( -----); // fill yourself.
printf(“\n”);
}
}

P[0] P[1]
2020 2090

a[0] a[1] a[2] b[0] b[1] b[2]


11 22 33 44 55 66
2020 2090

---------------------------------------------------------------------------------------------------------------------------------------------------
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);
y=(int*)malloc(sizeof(int)*3);
x[0]=11, x[1]=22, x[2]=33;
y[0]=44, y[1]=55, y[2]=66;
------
------
}

P[0] P[1]
2020 2090

11 22 33 44 55 66
2020 2090

---------------------------------------------------------------------------------------------------------------------------------------------------
C-Family Computers 81 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.
}
---------------------------------------------------------------------------------------------------------------------------------------------------
C-Family Computers 82 pointers
C-Family Computers 83 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
--------------------------------------------------------------------------------------------------------------------------------------------------
C-Family Computers 84 Strings

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
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
--------------------------------------------------------------------------------------------------------------------------------------------------
C-Family Computers 85 Strings

14) Code to accept a string and print following way


ip: computer
op: computer
compute
comput
compu
comp
com
co
c
--------------------------------------------------------------------------------------------------------------------------------------------------

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
--------------------------------------------------------------------------------------------------------------------------------------------------
C-Family Computers 86 Strings

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
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[] )
{ -------
-------
}
--------------------------------------------------------------------------------------------------------------------------------------------------
C-Family Computers 87 Strings

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 )
{ -------
-------
}
--------------------------------------------------------------------------------------------------------------------------------------------------
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 )
{ -------
-------
}
--------------------------------------------------------------------------------------------------------------------------------------------------
C-Family Computers 88 Strings

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.
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 )
{ -------
-------
}
--------------------------------------------------------------------------------------------------------------------------------------------------
C-Family Computers 89 Strings

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
--------------------------------------------------------------------------------------------------------------------------------------------------
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”);
}
C-Family Computers 90 Strings

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
--------------------------------------------------------------------------------------------------------------------------------------------------
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 read ‘C’ program as said in above program, (read char by char until ^), later count no.of
keywords found in the program. Take these 5 words as keywords: { if, else, while, break, continue}
ip: void main()
{ int i=1;
while(i<=20)
{ if(i==5) continue;
if(i==10) break;
printf(“%d “, i);
i++;
continue;
}
}^
op: if  2 time, while  1 time, break  1 time, continue  2 time, else  0 time
--------------------------------------------------------------------------------------------------------------------------------------------------
C-Family Computers 91 Strings

43) 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
--------------------------------------------------------------------------------------------------------------------------------------------------
44) 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
--------------------------------------------------------------------------------------------------------------------------------------------------
45) 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

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.
-------------------------------------------------------------------------------------------------------------------------------------------------
46) 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’

-------------------------------------------------------------------------------------------------------------------------------------------------
C-Family Computers 92 Strings

47) 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”

-------------------------------------------------------------------------------------------------------------------------------------------------
48) 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.
C-Family Computers 93 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
}
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”);
}
void read( ---- )
{ ---
---
}
int compare( ----)
{ ----
----
}
-------------------------------------------------------------------------------------------------------------------------------------------------
C-Family Computers 94 Structures

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) in 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
}
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;
};
-----
-----
-------------------------------------------------------------------------------------------------------------------------------------------------
C-Family Computers 95 Structures

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 idno
int d , m , y; char name[30];
}; struct Date
strcut Employee { int d, m , y;
{ int idno; } jd ;
char name[30]; };
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(---,---) { }
-------------------------------------------------------------------------------------------------------------------------------------------------
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( ---- ) { --- }
-------------------------------------------------------------------------------------------------------------------------------------------------
C-Family Computers 96 Structures

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
-------------------------------------------------------------------------------------------------------------------------------------------------
-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
-------------------------------------------------------------------------------------------------------------------------------------------------
C-Family Computers 97 Structures

*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()
{ struct Person p*10+=, ,“Ravi”, “9440”} ,
,“Ramu”, “9442”- ,
,“Lasya”, “8500”} ,
,“Laxmi”, “7412”},
...
};
char str[30], *p;
// 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( --- , ---)
{ ------
------
}
-------------------------------------------------------------------------------------------------------------------------------------------------
*11) Program to add two polynomials using array of structures
5x7+14x5+3x2+10x1+18
15x4+10x3+13x2+7

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

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

struct Poly
{ int expo;
int coeff;
};
C-Family Computers 98 Structures

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 )
{
------
------
}
-------------------------------------------------------------------------------------------------------------------------------------------------
**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
C-Family Computers 99 Structures

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.
}

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


{ -----
-----
// use free() function to delete seat-no
}
void print ( struct Passenger *arr[], int count )
{ -----
-----
}
-------------------------------------------------------------------------------------------------------------------------------------------------
C-Family Computers 100 Structures

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[] )
{ -----
-----
}
-------------------------------------------------------------------------------------------------------------------------------------------------
C-Family Computers 101 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()
{ FILE *fp; int i;
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)
#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);
}
C-Family Computers 102 Files

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();
readFromFileAndShowOnTheScreen();
}
void readFromKeyboardAndWriteToFile()
{ FILE *fp; char ch;
fp=fopen("sample.txt", "wt");
while(1)
{ ch=getchar();
if(ch=='^') break;
fprintf(fp, "%c", ch);
}
fclose(fp);
}
void readFromFileAndShowOnTheScreen()
{ 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);
}
---------------------------------------------------------------------------------------------------------------------------------------------------
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
--------------------------------------------------------------------------------------------------------------------------------------------------
C-Family Computers 103 Files

05) Let our text file contained some numbers, now read numbers one by one from file and copy all odd
numbers into another 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”


void main()
{ int a, b, c;
printf(“enter two values:”);
scanf(“%d%d”, &a, &b);
if( a>b && a>c)
printf(“big=%d”, a );
else if(b>c)
printf(“big=%d”, b );
else
printf(“big=%d”, b );
}

ip: file-name ”big.c”


op: “if”  found 2 times
“else”  found 2 times
“while”  found 0 times
“for”  found 0 times
-----
---------------------------------------------------------------------------------------------------------------------------------------------------
C-Family Computers 104 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);
}

--------------------------------------------------------------------------------------------------------------------------------------------------
C-Family Computers 105 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);
}
}
}
C-Family Computers 106 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");
}
C-Family Computers 107 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);
}
---------------------------------------------------------------------------------------------------------------------------------------------------

You might also like