Upload
dpalikhe
View
99
Download
0
Tags:
Embed Size (px)
Citation preview
PROGRAMMING
ANALYSIS IN
C
PROGRAMMING
ANALYSIS IN
C
Dedicated To,
My My My My Late Grandfather Late Grandfather Late Grandfather Late Grandfather Mitra Man PalikheMitra Man PalikheMitra Man PalikheMitra Man Palikhe
and also to School Of Engineering (SOE)-POKHARA
UNIVERSITY & PALIKHE FAMILY
2069 Asoj 16/2012 October 2 ‘TUE’
Devendra Man Palikhe
You can get soft copy of this book @ www.scribd.com/dpalikhe
PREFACE
This book entitled “PROGRAMMING ANALYSIS IN C” on C-Programming is the first
of its kind being published and written by student of SCHOOL OF ENGINEERING
(SOE), POKHARA UNIVERSITY. It mainly presents the programs and their solutions
regarding C-Programming during first semester in Engineering.
This book is meant to help the reader learn, understand, familiarize, and analyze
how to program in C. This book is for the purpose of building up the creative
ideas regarding C-Programming in mind of learners instead of the definitions
and it includes all the difficulties that the learners encounter during their voyage
in C-Programming.
This book is mainly meant for the difficult programs that learners come across
their journey in C-Programming and it includes all those questions which have
appeared in previous examinations of POKHARA UNIVERSITY that are a hard nut
to crack for the students but not merely all the questions. Most of the tough
solution of this book is based on analyzing problem through possible illustrative
ways, analyzing the problem for coding it into programs rather than on plain
statements of rules.
For the majority part, the programs are entire, real programs, rather than solitary
fragments. So this book is not an opening programming manual; it assumes some
experience and knowledge with programming concepts like variables,
assignments, statements, loops, logics, and functions.
The small programs, at last in projects that are just to enhance the creativity of
the learners, are self understood as they are written in very simple statements
and in sequential manner with outputs. All programs of this book are complied in
‘Borland C++ 5.02’.
I wish to acknowledge my greatest indebtness to my teacher Yagyanath Rimal
and my brothers Nitesh Palikhe and Nischal Palikhe for their constructive
suggestions, encouragement and constant support during publication of this
book. I would also like to thank all my colleagues. All the thoughtful criticisms and
critical suggestions of my friends, colleagues, readers and well-wishers for
improvement of this book are heartily welcome and will be highly appreciated.
ACKNOWLEDGEMENT
My sincere gratitude goes to my colleagues of school of engineering whose
constant support and encouragement has always been my source of
inspiration.
Devendra Man Palikhe
2�� Semester, BCE
School Of Engineering
POKHARA UNIVERSITY
You can get soft copy of this book @www.scribd.com/dpalikhe
CONTENTS
SOME BEGINNING PROGRAMS
Decision making
Loop A program to convert degree Celsius to Fahrenheit
A program to find positive or negative
A program to find numbers between 0 to 100 divisible by 3 and not by 5
Factorial`
Leap year
H.C.F. by division method
Reference-interchange two values
Flowchart of
Greatest among four numbers
Greatest among three numbers
Some types of numbers
Armstrong numbers
Even and odd numbers
Prime numbers
FIBONACCI SERIES
1, 1, 2, 3, 5, 8, 13, 21 …………….……….
0, 1, 1, 2, 3, 5, 8, 13, 21 ………………
DIGITS OF A NUMBER
Digits taking from a number
PALINDROME
Palindrome for number
An analysis of returning back number from its digits
Palindrome for string
Using reversing string function A char[] is declared where each time a new last character from string is taken one by one as array and then check is done to original string Palindrome for string containing even or odd quantity of characters Palindrome for string using for-loop
ELECRTICITY AUTHORITY
ARRAY
2d
PU2008FALL 2b) finding an element of 2D-array
Finding greatest and smallest number among ‘n’ numbers (using array)
PATTERNS OF CHARACTERS AND NUMBERS
‘Scanf’ function for numbers
Patterns of characters and numbers using ‘printf’ function
Basic principle of printing patterns
Some more patterns
Floyd’s triangle
Patterns of ‘*’
Some more difficult patterns
Pyramid of triangle
Reverse pyramid of triangle
Pascal’s triangle
PU2002 FALL 5 WAP that takes angle in degrees and give out value of sine for that angle without using ‘sin ()’ function of math library
Conversion
Decimal to binary
Binary to decimal
Exclusive use of ‘switch-case’ and ‘goto’ statements
2005PU A program that takes a sum of money and converts it into smaller units, where user can choose his starting unit. The conversion is in such a way that the first starting units takes maximum possible conversion then the left sum is supplied to conjugate term following it, this process continues till the end
SORTING
Selection sorting
Bubble sorting
Third sorting process
Analysis of the solution of third sorting
A special analysis in sorting-third sorting
PU2011FALL 5b) Sort ‘n’ numbers by function (special)
Description
A SPECIAL ANALYSIS
Now we are adding a new feature to above program
Examples of sorting of numbers and strings in selection and bubble sorting
Median and standard deviation
MATRIX ARRAY
Case-1: Finding smallest and greatest of a matrix
Case-2: Sum of diagonal elements of square 3*3 matrix
1. sum of diagonal from right top to left bottom 2. sum of diagonal from left top to right bottom
Case-3: Finding a matrix element in a matrix
Case-4: sum of all elements in a matrix
Case-5: transpose of a matrix
Matrix Multiplication
Matrices multiplication of (3*3) and (3*3)
More generalization of matrices multiplication
TASK A simple program that takes students marks in various subjects, name and roll numbers to print out ranks, roll numbers and marks (both % and marks) in Descending order.
Solution of the task
RECURSIVE FUNCTION
Factorial by function
Factorial by recursive
Fibonacci series by recursive
1 1 2 3 5 8 13 21 ……………….
Fibonacci series by recursive
0 1 1 2 3 5 8 13 21 ……………….
To calculate power by recursive
Calculate sum of digits by recursive
Armstrong using function
Armstrong using recursive
WITHOUT FUNCTION
To check case without using any function
Calculate power without function
To reverse a sentence without any function
Concatenate two strings without function
A DETAIL OF STRINGS
Finding a sequence of words
Finding a sequence of words any
Finding a sequence of words (working)
Finding a word in a sentence
Finding a word in a sentence (working)
Finding a word in a sentence (input from user)
OPERATORS
Table
Post/pre increment/decrement operators
For-block’s execution flow
ASSIGNMENT OPERATORS
OUTPUTS
Hints to PU 2008 FALL 3a) 3b
PU 2006 SPRING 2 a) 2 b) 2 c)
PU 2009 SPRING 2 b) important 3 a) very important
PU 2011 FALL 3 a) 3 b)
PU 2009 FALL 3 a) 3 b)
PU 2007 FALL 2 a) 2 b) PU 2012 FALL 2b i) very important
PU 2011 SPRING Ternary operator’s nested use
PU2006FALL 3) Print out combinations of 1, 2, 3 using for-loop
PUFALL2003 2 b) Read temperature of a month of 10 cities and print out average of ten cities using array and for-loop
Second way of solving
POINTERS
Pointer declaration in arrays
Program demonstrating pointer variable’s resembling with special array i.e. character array (string)
Using ‘void’ type pointer as required
Demonstrating the 2d pointers in 2d array
Call by address/ pass by pointer
Pointers in structure
Passing whole structure to function
PU 2006 SPRING 5a) Meaning of some pointer expressions
2003 fall 4 a) Write a program with user defined function using pointers to convert all the uppercase letters to lower-case and vice versa in a string given by the user
SOME CONCEPTUAL TERMS
Returning multiple value by functions
Program documentation
Important casting mechanism
Variables
Call by value vs. call by reference
A simple program demonstrating structure: It takes data and print info of whose address is “pokhara”
FILE HANDLING
File pointer vs. std
PU2009 SPRING 6 b) WAP to read name, author and price of 500 books and store the info to “library.dat” and print info of books of price > 300
PU2009 FALL 6 b) Create a structure for the following data: Id, Name, Address, Salary, Date of join and write program to input 100 employee, save in emp.dat file then print info of employee who have the address 'pokhara'
Due fee Prints student info whose due fee is less than 100
PU2002 Consumed charged data merged with file handling: WAP that stores following data of customer of electricity authority in file ‘elect.dat’: id, name, old reading, new reading and amount to be paid
PROJECTS
Books
Phone book
Mark sheet by harder method
Mark sheet by easier method
Updated mark sheet
Stores
Updated stores
You can get soft copy of this book @ www.scribd.com/dpalikhe
You can get soft copy of this book @ www.scribd.com/dpalikhe
You can get soft copy of this book @ www.scribd.com/dpalikhe
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
1
SOME BEGINNING PROGRAMS
DECISION MAKING
While going to the solution of a problem, we encounter many problems to which small decisions or a
group of small decisions or a loop of small decision can give a meaningful output. As much as
possible, decisions must be easier, simpler to read, understand and analyze being in great purpose
to the problem’s solution.
LOOP
One of the important processes in C programming is the repetition of statements (same for all time
or change gradually with time or condition or variables or inputs supplied by users, etc.). The array is
based on this looping (especially dynamic array).
A PROGRAM TO CONVERT DEGREE CELCIUS TO FAHRENHEIT
//A PROGRAM TO CONVERT DEGREE CELCIUS TO FAHRENHEIT
#include<stdio.h>
#include<conio.h>
int main() {
int celcius, fahrenheit;
clrscr();
printf("Enter temperature in celcius\t");
scanf("%d",&celcius);
fahrenheit=(celcius*1.8)+32;
printf("\n The equivalent temperature of %d in Fahrenheit is %d",celcius,fahrenheit);
getch();
return 1;}
A PROGRAM TO FIND POSITIVE OR NEGATIVE
We can conclude a number is positive or negative by comparing it with zero and the sum here is the
previous value stored in sum plus new value need to be stored in ‘sum’ i.e. ‘sum=sum + num’. Here
sum is calculated and average is calculated by dividing sum by number of items. To calculate the
number of items we declared a counter whose initial value is zero and it gets incremented by one
each time the second if gets executed and hence average is calculated.
#include<stdio.h>
#include<conio.h>
void main() {
int n,num[100],positive=0,negative=0,i;
printf("Enter how many numbers do you want to test?");
scanf("%d",&n);
for(i=0;i<n;i++) {
printf("Enter a number\n");
scanf("%d",&num[i]);
if(num[i]>0) {
positive=positive+1;
}
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
2
else if(num[i]<0) {
negative=negative+1;
}
else {
// for the case of zero number we do nothing
}
}
printf("\nThe number of positive numbers is %d",positive);
printf("\nThe number of negative numbers is %d",negative);
getch();}
A PROGRAM TO FIND NUMBERS BETWEEN 0 TO 100 DIVISIBLE BY 3 AND NOT BY 5
#include<stdio.h>
#include<conio.h>
void main() {
int i;
printf("The numbers between 0 to 100 that are divisible by 3 exactly and not divisible by 5 are:");
for(i=1;i<=100;i++) {
if(i%3==0 && i%5!=0)
printf("\n%d",i);
}
getch();}
Here numbers are taken from 0 to 100 by the help of for-loop (pre-test loop) and others are
arithmetic and logical operations where ‘%’ modulo sign gives remainder.
We can extend this program by asking n1 and n2 and fixing these limits for the values of i, so that
only numbers from n1 to n2 are checked where n1<n2.
FACTORIAL
n!=1*2*3*4*5……….(n-2)*(n-1)*n
#include<stdio.h>
#include<conio.h>
void main() {
int i,factorial,n;
factorial=1;
printf("Enter number?");
scanf("%d",&n);
for(i=1;i<=n;i++)
factorial=factorial*i;
printf("\nThe required factorial is%d",factorial);
getch();}
Here the factorial is found by multiplying from 1 to n. For this initialization is made factorial=1 (it
simply represents factorial of 1) and then the loop of i (from 1 to n) is taken which multiply the
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
3
previous factorial by a new number i (‘i’ is incremented each time by one to final to n) to get factorial
of new number ‘i’ i.e. a new value of i. So factorial at initial is initialized 1 so that multiplication runs
smoothly, it should be clear that initializing zero creates error.
LEAP YEAR
Firstly a leap year is exactly divisible by 4. A year greater than 100 must be divisible by 4 is leap. A
year less than 100 but divisible by 400 and 4 is leap year. It is because for number smaller than 100;
if it is divisible by 4 then it is leap year but for the number greater than 100 (i.e. takes place between
100- 1000), we calculate by division with 40 also so that 400 (is 4’s multiple in 100’s range i.e. 100-
1000) if is exactly gone, is leap for 100’s (i.e. 100-1000) range else not.
#include<stdio.h>
#include<conio.h>
void main() {
int year;
int factorial=1;
printf("Enter a year?");
scanf("%d",&year);
if(year%4==0){
if(year%100!=0){
printf("\nThe given year is a leap year");
}
else if(year%400==0){
printf("\nThe given year is a leap year");
}
else {
printf("\nThe given year is not a leap year");
}
}
else {
printf("\nThe given year is not a leap year");
}
getch();}
H.C.F BY (DIVISION METHOD)
Here in between two numbers (or can be extended to more numbers), a number is divided by
another number; the remainder divides the divisor till the remainder is zero (for more than two
numbers, each new number is added in dividend and above process continues till remainder zero).
For the last instant, the divisor is the H.C.F. (Highest Common Factor).
You can get soft copy of this book @ www.scribd.com/dpalikhe.
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
4
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main() {
int n1,n2,divisor,divident,remainder;
printf("Enter First Number");
scanf("%d",&n1);
printf("Enter Second Number");
scanf("%d",&n2);
if(n1>n2){
divident=n1;
divisor=n2;
}
else if(n2>n1){
divident=n2;
divisor=n1;
}
else if(n2=n1){
printf("The H.C.F. of two numbers is %d",n1);
exit(0);
}
do {
remainder=divident%divisor;
divident=divisor;
divisor=remainder;
}
while(remainder>0);
printf("The H.C.F. of two numbers is %d",divident);
getch();}
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
5
REFERENCE- INTERCHANGE TWO VALUES
Two variables have two values. In some other languages like Q-Basic, a direct function ‘swap’
interchanges their values regarding to identifiers. However there is no such in C. For e.g. if we
directly declare an identifier to value of other identifier i.e. value_a =value_b
Then both will have value b against our intension to also to get value_b=a, but here value_a gets b
and its original value ‘a’ disappears which can’t be restored. So a temporary variable must store the
value. Take two stone in two hands. How can they be interchanged, one is directly but in C there is
not so function so the other indirect method is used. Here the stone is transferred from one hand to
table and then the stone of other hand is transferred to first hand and then stone from table to
second hand. This is similar to declaring temporary variable and storing a value whose identifier is
made to take other value and then assigning the temporary value to the identifier whose value was
assigned by other. Thus declaration completes.
temp =value_b;
value_b=value_a;
value_a=temp;
#include<stdio.h>
#include<conio.h>
void main() {
int diff,a,b;
printf("Enter a Number");
scanf("%d",&a);
printf("\nEnter another Number");
scanf("%d",&b);
diff=a-b;
a=a-diff;
b=b+diff;
printf("\nThe interchanged numbers are like of this order %d\t%d",a,b);
getch();}
The next method is to take difference between two numbers taking one as a reference. The
difference is according to the reference number (the number before minus) so the number taken as
reference is subtracted to difference to get another number (because reference is the comparison of
another number with respect to a number) and another is added to difference to get first number as
its comparison s already with reference number. Making a number reference is to compare
according to its magnitude or direction but here magnitude is sufficient.
#include<stdio.h>
#include<conio.h>
void main() {
int diff,a,b;
printf("Enter a Number");
scanf("%d",&a);
printf("\nEnter another Number");
scanf("%d",&b);
diff=a-b;
a=a-diff;
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
6
b=b+diff;
printf("\nThe interchanged numbers are like of this order %d\t%d",a,b);
getch();}
FLOW CHART
Greatest among four numbers
Greatest among three numbers
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
7
SOME TYPES OF NUMBERS
ARMSTRONG NUMBERS
It is number equal to sum of cubes of all the digits present in number. For e.g. 153, 370, 371.
To check Armstrong, take each digit and save each time to sum its cube (i.e. Sum=sum + digit’s
power 3) and at last check the sum to original number. Please refer ‘digit taking from a number’
given in coming part; for the digit taking process.
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main() {
int num,digit,sum=0,temp_num;
clrscr();
printf("Enter a number");
scanf("%d",&num);
temp_num=num; /*here temp_num is necessary to hold transition values of num*/
while(temp_num>0){
digit= temp_num%10;
temp_num=temp_num/10;
sum=sum+pow(digit,3);
}
if(sum==num) printf("IT IS ARMSTRONG"); /*to preserve originality necessary for comparison
'num' holds original value */
else printf("IT IS NOT ARMSTRONG");
getch();
}
Please look ‘recursive function’ for further advancement.
EVEN AND ODD NUMBERS
Find remainder by division by two using “%” (modulo division) and then and check it is 0 or not, if 0
then even else odd.
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main() {
int num;
clrscr();
printf("Enter a number");
scanf("%d",&num);
if(num%2==0) printf("IT IS EVEN");
else printf("IT IS ODD");
getch();
}
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
8
We generally use ‘for-loop’ to add limiting values for numbers to be checked. Let’s us look a small
program that prints even numbers from 107 to 221 and prints sum of odd numbers of the given
range.
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main() {
int odd_sum=0,i;
printf("The even sumbers are\n");
for(i=107;i<=221;i++){
if(i%2==0) printf("\t%d",i);
else odd_sum=odd_sum+i; /*those which are not even are odd*/
}// for-loop terminal
printf("\nThe sum of odd is:\t%d",odd_sum);
getch();
}
PRIME NUMBERS
Prime number is such which is only exactly divisible by 1 or itself but not by others i.e. modulo
division (%) by only 1 and itself gives zero remainder but not by any else.
#include<stdio.h>
#include<conio.h>
#include<stdlib.h> //for ‘exit()’function
void main() {
int number,i;
clrscr();
printf("Enter a number");
scanf("%d",&number);
for(i=2;i<number;i++) {
if(number%i==0) {printf("NOT PRIME NUMBER"); if (getch()) exit(0); }
}
printf("IT IS PRIME NUMBER");
getch();
}
Here we are checking the division of the number from 2 to a value less than number, if it is divisible
for at least for one case then “it is not even” or “it is composite” but if the whole ‘for-loop’
terminates without any possible remainder zero then at last “it is prime” is printed. It must be clear
that ‘exit()’ function jumps all execution flow to end of program escaping all statements directly.
#include<stdio.h>
#include<conio.h>
void main() {
int number,i,divisible=0; /*here for others like number and i initialization is not compulsory as i is
intialized in for-loop and for number it is initialized by 'scanf-function'*/
clrscr();
printf("Enter a number");
scanf("%d",&number);
for(i=1;i<=number;i++) {
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
9
if(number%i==0) divisible++;
}
if(divisible==2) printf("IT IS PRIME NUMBER");
else printf("IT IS COMPOSITE OR NOT PRIME NUMBER");
getch();
}
Here ‘i’ loop starts from zero to number and for each exact division, variable ‘divisible’ is
incremented by one, so that after the for-loop terminates if ‘divisible’ is equal to two only; shows
that the number was divisible by one and itself only but not by any numbers from zero to number,
so it is prime.
NOTE: Every number is exactly divisible by one and by itself, prime numbers are strictly limited to it
but composite numbers are exactly divisible by at least one new number in addition to it.
#include<stdio.h>
#include<conio.h>
void main() {
int number,divident=2;
clrscr();
printf("Enter a number");
scanf("%d",&number);
while(divident<number){
if(number%divident==0) { printf("IT IS COMPOSITE OR NOT PRIME NUMBER"); if(getch()) exit(0); }
/*here getch() is used to hold statement printed on the screen beefore 'exit'-function is executed */
divident++;
}
printf("IT IS PRIME NUMBER");
getch(); // to hold the value printed on screen till any character is given
}
Here we are using ‘while’-loop instead of ‘for’-loop. It is similar to the case of ‘for’-loop. These ‘for-
loop’, ‘while-loop’ can also be replaced by ‘goto-statement’ like this
#include<stdio.h>
#include<conio.h>
void main() {
int number,divident=2;
clrscr();
printf("Enter a number");
scanf("%d",&number);
again:
if(divident<number) { /* here we are limiting the range of divident, it is our first aim to limit the
divident than the checking of divisible so this 'if' is used at first*/
if(number%divident==0) { printf("IT IS COMPOSITE OR NOT PRIME NUMBER"); if(getch()) exit(0); }
divident++; goto again; /*we can place these statements in 'else'-statement too*/
}
printf("IT IS PRIME NUMBER");
getch();
}
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
10
FIBONACCI SERIES
IF THE FIBONACCI SERIES IS
1, 1, 2, 3, 5, 8, 13, 21 …………….……….
We see pattern from third term that it is sum of two numbers before it; 2=1+1, 3=2+1, 5=3+2……….
For this, our result is sum of two numbers whose one number is previous sum and other is one step
more previous sum (or the number proceeding to what we are concerning to for sum or the number
we are concerning with).
a b c printed value
(c) statement value statement value statement value
a=0 0 b=1 1 a+b 1 1
a=b 1 b=c 1 a+b 2 2
a=b 1 b=c 2 a+b 3 3
a=b 2 b=c 3 a+b 5 5
a=b 3 b=c 5 a+b 8 8
a=b 5 b=c 8 a+b 13 13
a=b 8 b=c 13 a+b 21 21
a=b 13 b=c 21 a+b 34 34
And this process goes on. In the program ‘1’ at initial is printed to maintain pattern and this
happened due to inefficient initialization of values ‘a’ and ‘b’. The approaching next method cracks
it.
#include<stdio.h>
#include<conio.h>
void main() {
int a=0;
int b=1;
int c,i,n;
printf("Enter a Number\t");
scanf("%d",&n);
printf("%d\t",b);
for(i=1;i<n;i++) {
c=a+b;
printf("%d\t",c);
a=b;
b=c;
}
getch();}
Here for our initialization purpose we declare a=0, b=1 so that our sum c=0+1 is 1 initially and
second time after interchanging a, b, c we get c=2 so we print b (=1) initially we continue the pattern
however the loop continues for n-1 times as the first number is made to print automatically on any
cost or input.
IF THE FIBONACCI SERIES IS
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
11
0, 1, 1, 2, 3, 5, 8, 13, 21 ………………
Then we conclude that 0 must be sum of two terms in such a way that the second of two terms=zero
=1. So these numbers must be -1 and 1. Other interchanging and printing process are same to above.
a b c printed value
(c) statement value statement value statement value
a=-1 -1 b=1 1 a+b 0 0
a=b 1 b=c 0 a+b 1 1
a=b 0 b=c 1 a+b 1 1
a=b 1 b=c 1 a+b 2 2
a=b 1 b=c 2 a+b 3 3
a=b 2 b=c 3 a+b 5 5
a=b 3 b=c 5 a+b 8 8
a=b 5 b=c 8 a+b 13 13
And this process goes on.
#include<stdio.h>
#include<conio.h>
void main() {
int a=-1,b=1,c,n,i;
printf("Enter a number\t");
scanf("%d",&n);
for(i=1;i<=n;i++) {
c=a+b;
printf("%d\t",c);
a=b;
b=c;
}
getch();}
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
12
DIGITS OF A NUMBER
DIGITS TAKING FROM A NUMBER
Digit taking from a number is very useful and important task because while dealing to numbers in C,
we need the digits’ calculations. Digits of any number in its corresponding number system are
nothing but the remainder by division by the base of the system to the particular number. So we
divide by 10 and take the remainder for the purpose. However after a digit is taken, we need to
remove a digit (last) from the number so that we can take next digit by similar above process. For
removing last digit (i.e. at one’s place) we make integer division by 10(this takes quotient before
decimal point). This process continues till num>0 and digits are taken each time to which we can
process.
#include<stdio.h>
#include<conio.h>
void main() {
int digit[15],num,i=0,j;
printf("Enter a Number");
scanf("%d",&num);
while(num>0) {
digit[i]=num%10;
num=num/10;
i=i+1;
}
for(j=i-1;j>-1;j--){
printf("\nThe digit in %d place is %d",j+1,digit[j]);
}
getch();}
The next way is not to remove digit(last) from numbers instead calculating digits by dividing the num
each time by one’s…..ten’s….hundred’s ………(ten’s multiples) and the remainder is divided by
appropriate one’s…………..ten’s………. Here the one’s……ten’s………………..of the later is one step-down
above step because the remainder of initial contains the levels of digits of required plus the digits
below the level so they are removed by integer division. Here level means digit’s place from right
(one’s, ten’s, hundred’s……).
#include<stdio.h>
#include<conio.h>
void main() {
int digit[15],d,num,i=0,j,a=1,b=10,temp;
printf("Enter a Number");
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
13
scanf("%d",&num);
temp=num;
while(temp>0) {
d=num%b;
digit[i]=d/a;
a=a*10;
b=b*10;
temp=temp/10;
i=i+1;
}
for(j=i-1;j>-1;j--){
printf("\nThe digit in %d place is %d",j+1,digit[j]);
}
getch();}
Here a variable temp is required to continue loop for number of digits available. A number (decimal)
continuously divided by 10 for n times until quotient 0, gives number of digits because each digit
disappears in integer division by 10 (base of decimal system).
Similarly we can convert the number to string and its each character can be taken by string function
and then its (each character’s) integer value can be reversed back. It is because there are string
functions that work on characters.
Let num be a character digit then
X=num-‘0’→zero
It gives difference in ASCII values of num and zero i.e. actual number (integer value)
Number is converted to character like ‘123’
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main() {
int j;
char num[15];
char dconvert[15];
printf("Enter a Number");
scanf("%s",num);
strcpy(dconvert,num);
for(j=0;j<strlen(dconvert);j++){
printf("\nThe digit in %d place has ASCII value = %d",j+1,dconvert[j]);
}
getch();}
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
14
PALINDROME
PALINDROME FOR NUMBER
A palindrome number is that number for which the digits scanned from front is equal to glanced
from back. For e.g. 12321, 121, 125797521. Here we are taking each digit and converting the digits
(of number) to values. Here we are not sure with how many digits are there so this can be solved
especially by two ways- one connecting each numbers(digits) by converting to character and
concatenating them and finally string to integer value and then comparing the value with original
value to find whether it is palindrome or not.
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<stdlib.h>
void main() {
int j,number=0,digit;
char num[15];
char dconvert[15];
printf("Enter a Number");
scanf("%s",&num);
strcpy(dconvert,num);
for(j=strlen(dconvert)-1;j>=0;j--){
digit=dconvert[j]-'0';
number=(number*10)+digit;
}
printf("The reversed number is\t%d\n",number);
if(atoi(num)==number)
printf("It is palindrome");
else
printf("It is not Palindrome");
getch();}
In above process after a digit is calculated then the previous number is multiplied by 10 (if available)
so as to increase its level i.e. from one’s to ten’s, ten’s to hundred’s and so on and the digit is added
to it to make required number. As for the case we take second digit from left of 51 i.e. ‘5’ whose
succeeding digit is ‘1’ already stored in ‘number’ is multiplied by 10 and added to new digit, i.e.,
(1*10)+5, that equals 15 which is reverse of 51 but not palindrome number. Similar method is used
in below program.
But for the process using numerical tools, we first up all find digits and each previous digit (if
available) then multiplied by suitable and then the new digit is added to. This process continues till
digits come. Here suitable means 10 each time because ten is the base of decimal or each digit differ
from its left digit by ten’s.
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
15
Here ‘atoi’ defined in <stdlib.h> converts string to integer.
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<stdlib.h>
void main() {
int j=0,number=0,digit=0,digita=0,numa=0;
char dconvert[100],num[10];
printf("Enter a Number");
scanf("%s",&num);
int a=0;
for(j=(strlen(num)-1);j>=0;j--){
digita=num[a]-'0';
a+=1;
numa=(numa*10)+digita;
digit=num[j]-'0';
number=(number*10)+digit;
}
if(numa==number)
printf("\nIt is palindrome");
else
printf("\nIt is not Palindrome");
getch();
}
String can be converted to number directly by function 'atoi' but it can be done taking a character of
string each time and subtracting it to ASCII value of zero i.e. '0'(ASCII values are those particular
numbers representing some characters, letters or any symbol in computer).In these processes we
can take characters of string either from front or from back but the index ‘num[j]’ in above should be
in increasing and decreasing respectively from 0 to length-1 and length-1 to 0 respectively.
AN ANALYSIS OF RETURNING BACK NUMBER FROM DIGITS
The method is to find each digits similar to above and then each digit is multiplied by suitable and
then added to previous digit (or number if available). Here suitable means power of 10 because the
new value means increase in ten’s level.
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main() {
int i,num,number,digit,lastdigit=0;
printf("Enter a Number");
scanf("%d",&num);
for(i=0;num>0;i++) {
digit=num%10;
num=num/10;
int temp=digit*pow(10,i);
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
16
printf("\n%d is added to%d",temp,lastdigit);
lastdigit=digit*pow(10,i)+lastdigit;
}
printf("\nThe supplied number was%d",lastdigit);
getch();
}
PALINDROME FOR STRING
Similar to palindrome numbers, palindrome strings are those strings in which characters glanced
from front is equal to glanced from back. For e.g. radar, madam, yagay, eye, eve.
1. Using reversing string function
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main() {
char string[10];
char temp[10];
printf("Enter a String");
scanf("%s",string);
strcpy(temp,string);
strrev(string);
if(strcmp(temp,string)==0)
printf("\nThe String is Palindrome");
else
printf("\nThe String is not Palindrome");
getch();}
OR
#include<conio.h>
#include<string.h>
void main() {
char string[100],comp[100];
printf("Enter a String");
scanf("%s",string);
strcpy(comp,string);
strrev(string);
if(strcmp(comp,string)==0){
printf("\nThe String is Palindrome");
}
else {
printf("\nThe String is not Palindrome");
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
17
}
getch();}
Here ‘temp’ variable is for transition case and sudden change in ‘string’ before comparison.
2. A char[] is declared where each time a new last character from string is taken one by
one as array and then checking is done to original string
#include<stdio.h>
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main() {
int i;
char temp[2];
char string[30]="",newstring[30]="";
printf("Enter a String");
scanf("%s",string);
for(i=strlen(string)-1;i>=0;i--) {
temp[0]=string[i];
strcat(newstring,temp);
}
if(strcmp(newstring,string)==0){
printf("hello..........");
printf("the String is Palindrome");
}
else {
printf("hello");
printf("\nThe String is not Palindrome");
}
getch();
return 0;
}
Here the ‘newstring’ is to hold old value which is every time concatenated with new value.
3. Palindrome for string containing even or odd quantity of characters
This method uses the property of even and odd in palindrome that half alphabets taken from
front if equals to half alphabets taken from back then it is palindrome. But for odd (half-1/2) is
compared because the central alphabet is always constant as its pace from front is equal to from
backward. For e.g.
In case of even number of characters containing string like “YAGGAY”, here we need to read first
three characters from ‘Y’ to ‘G’ and store in ‘front’ variable then we need to read last three
characters from ‘Y’ to ‘G’ in reverse manner and store in ‘reverse’ variable. If ‘reverse’ is same to
‘front’ variable then it is palindrome, for the particular case it is palindrome.
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
18
In case of odd numbers of characters containing string like “YAGAY”, here we need to read first
two characters “YA” and store it in ‘front’ and similarly read last two characters “YA” in reverse
manner and store in ‘reverse’ and comparison is done. Here the central character “G” holds the
same value for the same position when read either from front or from reverse, so the
comparison for this central character is rejected from ‘front’ and ‘reverse’ variables.
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main() {
int i;
char string[100],front[100]="",reverse[100]="";
printf("Enter a String");
scanf("%s",string);
if(strlen(string)%2==0){//for case of even
strncat(front,string,strlen(string)/2);
strncat(reverse,strrev(string),strlen(string)/2);
}
else {//for case of odd
strncat(front,string,(strlen(string)-1)/2);
strncat(reverse,strrev(string),(strlen(string)-1)/2);
}
if(strcmp(front,reverse)==0)
printf("\nThe String is Palindrome");
else
printf("\nThe String is not Palindrome");
getch();}
4. Palindrome for string using for-loop
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main() {
int i;
char string[100]="",newstring[100]="";
printf("Enter a String");
scanf("%s",string);
static char temp[1];
for(i=(strlen(string)-1);i>=0;i--) {
temp[0]=string[i];
strcat(newstring,temp);
}
if(strcmp(newstring,string)==0){
printf("\nThe String is Palindrome");}
else{
printf("\nThe String is not Palindrome");
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
19
}
getch();
return 0;}
ELECRTICITY AUTHORITY
An electricity board charges according to the following rates:
Units Charges (In NRs.)
0-100 40
101-200 50
201-ABOVE 60
All users are also charged ‘meter charge’, which is equal to Rs. 50. Write a complete C program to
read the number of units consumed and print out the total charges.
Here the first condition is to check whether the unit is within range 0 to 100 or 101 to 200 or 201 to
above. After this we calculate the charge for units above higher maximum range then the units is
reduced for lower range continuously whereas on the other hand, charge is added systematically
from higher to lower level. Here ‘goto’ has a special purpose of direct connection. It connects higher
range to lower range before this, units of higher are reduced to lower because ‘goto’ sends to lower
where calculations of lower range only is necessarily to be done.
/*ELECTRICITY AUTHORITY CHARGES AS FOLLOW
Units Charges (In NRs.)
0 to100 R.s.40
101 to 200 R.s.50
201to ABOVE R.s.60
AND IT TAKES Rs. 50 as meter charge. A PROGRAM THAT INTAKE UNITS CONSUMED AND FIND OUT
TOTAL CHARGE.*/
#include<stdio.h>
#include<conio.h>
void main() {
int units=0,charge=0,choice=0,totalcharge=0;
printf("ELECTRICITY AUTHORITY CHARGES AS FOLLOW\nUnits----Charges (In NRs.)\n0 to100
R.s.40\n\n101 to 200 R.s.50\n\n201to ABOVE R.s.60\n\nAND IT TAKES Rs. 50 as meter charge\n");
printf("\nEnter Units Consumed\t");
scanf("%d",&units);
int old=units;
if(units>200){
choice=200;
}
else if(units>100){
choice=100;
}
else {
choice=0;
}
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
20
switch (choice){
case 200:
charge=(units-200)*60;
units=200;
totalcharge=charge;
printf("\nAbove '200' units i.e. 201 to %d (%d * 60)= %d",old,old-200,charge);
old=200;
goto A;
case 100:
A:
charge=(units-100)*50;
totalcharge=totalcharge+charge;
units=100;
printf("\nAbove '100' units i.e. 101 to %d (%d * 50)= %d",old,old-100,charge);
old=100;
goto B;
case 0:
B:
charge=units*40;
totalcharge=totalcharge+charge;
printf("\nAbove '0' units i.e. 0 to %d (%d * 40) = %d",old,old-0,charge);
totalcharge+=50;
printf("\n Meter Charge = %d",50);
break;
default:
printf("Invalid Input");
}
printf("\n-------------------------------------------------------");
printf("\nThe total cost of power consumed is NRs. %d",totalcharge);
getch();
}
We can improve its continuity by adding a line and a index using ‘goto’ statement, like this.
/*ELECTRICITY AUTHORITY CHARGES AS FOLLOW
Units Charges (In NRs.)
0 to100 R.s.40
101 to 200 R.s.50
201to ABOVE R.s.60
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
21
AND IT TAKES Rs. 50 as meter charge. A PROGRAM THAT INTAKE UNITS CONSUMED AND FIND OUT
TOTAL CHARGE.*/
#include<stdio.h>
#include<conio.h>
void main() {
printf("ELECTRICITY AUTHORITY CHARGES AS FOLLOW\nUnits----Charges (In NRs.)\n0 to100
R.s.40\n\n101 to 200 R.s.50\n\n201to ABOVE R.s.60\n\nAND IT TAKES Rs. 50 as meter charge\n");
int units=0,charge=0,choice=0,totalcharge=0;
maina :
printf("\nEnter Units Consumed\t");
scanf("%d",&units);
int old=units;
if(units>200){
choice=200;
}
else if(units>100){
choice=100;
}
else {
choice=0;
}
switch (choice){
case 200:
charge=(units-200)*60;
units=200;
totalcharge=charge;
printf("\nAbove '200' units i.e. 201 to %d (%d * 60)= %d",old,old-200,charge);
old=200;
goto A;
case 100:
A:
charge=(units-100)*50;
totalcharge=totalcharge+charge;
units=100;
printf("\nAbove '100' units i.e. 101 to %d (%d * 50)= %d",old,old-100,charge);
old=100;
goto B;
case 0:
B:
charge=units*40;
totalcharge=totalcharge+charge;
printf("\nAbove '0' units i.e. 0 to %d (%d * 40) = %d",old,old-0,charge);
totalcharge+=50;
printf("\n Meter Charge = %d",50);
break;
default:
printf("Invalid Input");
}
printf("\n-------------------------------------------------------");
printf("\nThe total cost of power consumed is NRs. %d",totalcharge);
printf("\n\n do you continue\n press 1 to continue");
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
22
if(getch()=='1') {
goto maina;}
}
Here ‘maina’ index repeats the statements only if ‘1’ value is entered. ‘getch()’ takes a character so
‘1’ is user to make 1 as character.
PU2006SPRING
3b) Electricity board charges according to the following rates.
For the first 100 units -------------------------- Rs. 40 per unit
For the next 200 units ------------------------- Rs. 50 per unit
Beyond 300 units ------------------------------ Rs. 60 per unit
All users are also charged ‘meter charge’, which is equal to Rs. 50. Write a complete C program to
read the number of units consumed and print out the total charges.
Next analyzing way in a little bit detail
#include<stdio.h>
#include<conio.h>
/*
units range cost
301 - Rs. 60
101 - 300 Rs. 50
1 - 100 Rs. 40
*/
void main() {
float units=0,cost=0;
printf("\nEnter Units Consumed:\n");
scanf("%f",&units);
if(units>300) {
cost=100*10+200*50;
units=units-300;
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
23
cost=cost+(units*60);
}
else if (units>100) {
cost=100*40;
units-=100;
cost=cost+(units*50);
}
else {
cost= units*40; // the only last possible condition units>0
}
cost=cost +50;//we can replace it by using this to each blocks of if-elseif ladder
/*In scase instead of 50 as charge if 15% is taken as any kind of sharge like meter charge or vat
then 'cost=115/100*cost' or'cost=cost+(15/100*cost)' can be used*/
printf("The total cost of %f units is %f",units,cost);
getch();
}
--------------------------------------------program termination----------------------------------------------
Next view for analyzing problem in next way but for these no real program codes are written
/*
units range cost
1 - 100 Rs. 40
101 - 300 Rs. 50
301 - Rs. 60
*/
if(units<100) {
cost=units*40;
}
elseif(units<300) {
cost=100*40;
units-=100;
cost=cost+unit*50;
}
else {
cost=100*40+50*200+(units-300)*60;// a single statement like this can also work
}
cost+=50;
---------------------------termination of one way of viewing program------------------------------
Next view for analyzing problem in next way but for these no real program codes are written
(by simple if statements using logical operators)
declare global_units=units;
if(units<100 { // this can ber replaced bu units>0 && units<100
cost=units*40;
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
24
}
if(units<300 && units>100) {
cost=10*/40+(units-100)*50;
}
if(units>300) {
cost=100*40+200-50+(units-300)*60;
}
---------------------------termination of one way of viewing program------------------------------
The coming process is similar to done in ELECRTICITY AUTHORITY already but this process is
simple in the manner that it doesn't use ‘goto’, which may be confusing for readers to analyze.
This coming method uses the technique of dividing operations in parts in such a way that each
part is executed if only the condition in 'if' is satisfied. If the condition is satisfied then some
operations is done. This operation is related to the condition of the particular 'if' then the
necessary quantity whose calculation is done is removed from the value to which calculation is
to be done as a whole. Realizing problem in codes speak more than words or programming
analysis is great than language taking programming.
if(units>0) {
if(units>100){
cost=100*40;
units-=100;
}
else {
cost=units*40;
units=0;
}
}
if(units>0) {
if(units>200){
cost=cost+200*50;
units-=200;
}
else {
cost=cost+units*50;
units=0;
}
}
if(units>0) {
cost=cost+units*60;
units=0;
}
---------------------------termination of one way of viewing program------------------------------
Here block of ‘if-statement’ checks condition as follow:
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
25
��� block ��� part Checks units >100 ��� block ���� part Checks units <100 ���� block ��� part Checks units >200 ���� block ���� part Checks units <200 ����� block ��� part Checks units >300
Here each block has specified work to do. ���Block calculates the sum for the units between 1 to 100
units and then it extracts the calculated portion from the total consumed units by subtracting units
to calculated amount of units. So that the next block of ‘if’ needs to calculate the sum for next range
of units, i.e. 2of 10 units to 300 units but its range is 200 and as calculated part (1 to 100) is
extracted so
------------0-------------------------100--------------------200--------------------300--------------
It is extracted It is left
In the last part, we similarly do for the range (101-300) and finally the left all is done by ����� block.
Here in each terminating of ���� part of each block, units is assigned zero. Sothere is no necessary
of further calculations. It is because the ��� part of each block (except �����block) works taking the
condition on the basis that it works for particular range with leaving some range for succeeding
block. It means, for e.g. ��� part of ����block works in such that in it works for particular range of
101-300 and leaving 300-above range for �����block so here units is still left to be calculated for �����block and this all is the reflection of the condition of if of ���part of ����block if (units>200) i.e.
from 101 to 300. For e.g.
If 500 units is consumed then calculation takes as below:-
(Termination in ����� block)
Block-���
units>0 500>0 True - - -
Block-���
units>100 500>100 True cost=100*40
units-=100
4000
500-100
4000
400
Block-����
units>0 400>0 True - - -
Block-����
units>200 400>0 True cost=cost+200*50
units-=200
4000+200*50
400-200
14000
200
Block-�����
units>0 200>0 True cost=cost+(units*60)
units=0
14000+200*60 26000
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
26
Let us assume consider for value units 60 that must terminate in ���block
Block-��� units>0 60>0 True - - -
Block-��� units>100 60>100 False cost=units*40
units=0
60*40
0
2400
0
Block-���� units>0 0>0 False - - -
Block-����� units>0 0>0 False - - -
Let us consider for value units 150 that terminate in ���� block:-
Block-���
units>0 150>0 True - - -
Block-���
units>100 150>100 True cost=100*40
units-=100
100*40
150-100
4000
50
Block-����
units>0 50>0 True - - -
Block-����
units>0 50>200 False cost=cost+(unit*50)
unit=0
4000+(50*50)
0
6500
Block-�����
units>0 0>0 False - - -
Actually in designing problem, we need to consider ourself as programmer and we need to analyze
all the steps or execution that takes for each possible input of users. Then we must realize in writing
and executing. Here in above program, we need to analyze the execution of value of cost and units
for each possible input of users.
There are many possible conditions even including simple ‘if’, it depends on flow of direction of
executing from top range to low range or vice-versa.
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
27
ARRAY
The derived structured data types are more effective in C because user can himself declare according
to his requirement where every element has some relationship forming a structure. Arrays are
important regarding structure type data and these structures can be efficiently, easily used on user-
interference dynamically by numbers, characters or strings (sum of characters). Names and locations
are unique for the ordinary purposes but when we want to use a common term related to both we
use array. Arrays are two-one that is fixed i.e. static whose declaration is completed before
initialization or running of main part of program. Such array are less effective, easier and the only
two purposes of such array is to-one for just demonstration of way of using array or how array works
and the other may be making collection of characters or numbers in small space rather than making
separate space for each terms. The other dynamic is vast because it include static plus the working
that is not possible from any else (even static). The dynamic array works on the principle of two-one
in which its limit is fixed by program and the other is made by user himself. The later one is more
effective. For this the program either directly or indirectly or through process of calculations declares
the size of array. To make array’s cycle, we use loop with a variable different each time (by+1, -1 or
any according to the conditions). Usually we declare by incrementing each value by 1 because in
array numbers are taken in sequential addresses starting from 0 to one number less than total
quantity of elements. For this purpose we can use, if and using counter and goto, similarly while,
counter or simply for. The easier one, concise one is for, we generally use it except for case where if
is used when condition is needed more to be focused, goto if direct linkage is necessary immediately
or in some making program more effective, fast etc. However using if and exit inside for-loop can
work. In array, we use for-loop generally from (i=1 to n) to take numbers and give them to addresses
i=0 to i=n-1 because in array address starts from 0 but quantity is n, so last address is n-1.
Similarly, we use such loop for output of numbers or characters. It they are sequentially to be
printed out we use i=0 to n-1 (i=1 to n) incrementing or decrementing (i=n to 1 or i=n-1 to 0) by 1 but
sometimes a gap of addresses is required for this appropriate increment or decrement is done. For
the case of sorting-bubble, selection, two loops were taken and array calculation was done. This is
illustrated in Loop Section. However while understanding array calculation we must be clear about
loop. Because it is only way to read or write the array elements in its proper address of finite or
infinite array elements (infinite here means in the way that we don’t know the exact quantity of
elements as it is user-dependent). Any program must be logically and technically strong enough to
hand no limitations regarding quantity and quality of values provided by users for unlimited time
purpose.
#include<stdio.h>
#include<conio.h>
void main() {
int number[5],i;
for(i=0;i<5;i++) {
printf("Enter a Number");
scanf("%d",&number[i]);
}
for(i=0;i<5;i++) {
printf("\nThe %d th number is %d",i+1,number[i]);
}
getch();
}
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
28
Besides reading and writing, loops are used to continue many cycles in arrays, some for
comparisons, some for arithmetic and logical calculations, some for arrangements and many more.
In sort, there were two loops for comparison and interchanging calculations. Look sorting for detail
analysis. However in this we will be concerned with array only.
In each loop, we find different sequentially coming array elements compared with other
sequentially. In this way every array elements got compared and our purpose satisfied. Such loops
and arrays are just general purposes. We can extend it to 2-D, 3-D or even multi-dimensional
purpose. Each time we use more dimension, we need a looping more i.e. if 2 loops for 1-D then for
the same purpose 3 loops is necessary for 2-D and similarly for others because one more loop is
necessary for 1-D to 2-D because in each step of D, there is one more necessity of a loop in defining
array elements. For 3-D process, for same one more loop is required to find the one more dimension
of array. So regarding the purpose of sorting, 2 loops for 1-D, 3 loops for 2-D, four loops for 3-D and
so on for multi-dimensional.
2D:
In 2-d array, two co-ordinates are use to specify the point of address as there are rows and columns.
So the two loops to define 2-D array elements.
#include<stdio.h>
#include<conio.h>
void main() {
int number[2][2],i,j;
for(i=0;i<2;i++) {
for(j=0;j<2;j++) {
printf("Enter a Number");
scanf("%d",&number[i][j]);
}
}
for(i=0;i<2;i++) {
for(j=0;j<2;j++) {
printf("\nThe number in %d row and %d column is \t %d",i+1,j+1,number[i][j]);
}
}
getch();
}
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
29
a b result
1 1 to 1 1
2 1 to 2 12
3 1 to 3 123
4 1 to 4 1234
PU2008FALL 2b)
WAP that asks a user for a number and finds out if the number is present in the D array given
below:
int arr[3][3] ={{6,37,33},
{12,11,13}'
{14,85,96}
};
#include<stdio.h>
#include<conio.h>
void main() {
int found=0;
int i,j,num,arr[3][3]={ {6,37,33},
{12,11,13},
{14,85,96}
};
printf("Enter a number:\t");
scanf("%d",&num);
for(i=0;i<3;i++){
for(j=0;j<3;j++){
if(arr[i][j]==num) found++;
}
}
if(found==1)printf("Found");
else printf("Not Found");
getch();
}
In this program, it uses one of the techniques of declaring values in 2D-array. Here row elements are
6, 37and 33, row elements are 12, 11and 13 and row elements are 14, 85, and 96.
Row
Column
0 1 2
0 6 12 14
1 37 11 85
2 33 13 96
GREATEST AND SMALLEST NUMBER AMONG ‘N’ NUMBERS (using array)
Here a variable greatest and smallest is declared and then the comparison is done with the variable
to other numbers serially coming in arrays by the help of for-loop. According to our necessity-
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
30
greatest or lowest, the sign of comparison is assigned and value is assigned if condition is true. After
the completion of all comparison, we get greatest and smallest among n numbers.
#include<stdio.h>
#include<conio.h>
void main() {
int i=0,j=0,number,num[100],great,small;
printf("\n Enter how many numbers?\n");
scanf("%d",&number);
printf("\n\n\n Enter numbers\n");
for(i=0;i<number;i++) {
scanf("%d",&num[i]);
great=small=num[0];
if(num[i]>great) {
great=num[i];
}
if(num[i]<small){
small=num[i];
}
}
printf("The greatest number is %d\t and the smallest number is %d",great,small);
getch();
}
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
31
PATTERNS OF CHARACTERS AND NUMBERS
For the purpose array is necessary because we deal with pointer rather than values even though it
may seem that the output has connection with values. [NOTE: In some values have connections for
this looping may be sufficient.] After talking about arrays, generally looping comes itself for the
general case of dynamics. The output of Floyd’s triangle is a 2-D. so two loops are sufficient (in
simple cases), one outer loop defines the rows and the second inner loop is for printing the pattern
of columns corresponding to each rows declared by outer loop. The main analysis is needed for inner
loop because the outer loop is just for counting the rows but inner has many things to do. The inner
lop must develop a formula connecting the outer loop’s value with the patters to be printed and its
connection to further coming patterns of inner loop. For this purpose, counter may be declared,
incremented, decremented, multiplied, divided or reduced (in case of strings) or many variables that
may be transitional or temporary or others can be declared according to the availability of resources
and values of outer loop for the purpose of pattern resembling columns of corresponding outer
loop. The above all we discussed is all about loops and arrays however our pattern can also be
achieved by scanf and printf. These formatted functions use various field widths for various outputs
but we need to develop a formula analyzing the printing patterns with the field width. These
functions generally work for characters, however it works more conveniently with numbers but
numbers being arithmetic are implemented by arithmetic process rather than by functions.
However, output doesn’t vary. In some, it is necessary for using such functions. Some of the tips for
using these functions are as below:-
1. The field width is less than length of string implies that all to be printed as usual.
2. The value after decimal (if is present) implies the number of characters to be printed. If it is
zero, nothing is printed.
3. The value before decimal makes the space to which printing is done. The printing is done in
such a way from right (in reference to space) but from left (in reference to values it have).
4. The negative sign causes no gap in printing i.e. top-most left shifting.
5. If nothing is before decimal then the printing is usual however number after decimal
restricts (if present).
An example to demonstrate the above function
#include<stdio.h>
#include<conio.h>
void main(){
int i;
char string[]="NEPAL";
for(i=1;i<=5;i++) {
printf("%-5.*s\n",i,string);
}
getch();
}
Output:
N
NE
NEP
NEPA
NEPAL
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
32
Here in the function * is the value supplied by i. this function format is usually used in UNIX.
Similarly, we can replace * by our necessary number and for this a more number or variable is
declared in argument part. Analysis:- In the program, ‘5’ defines the space to which printing is done
it is every time (or for every loop it is 5), the negative sign shifts the output to left-most part. The ‘*’
is pointed to I, whose value change from 1 to 5 so that each time the loop continues, the number of
patterns increases serially one by one as the value of I of loop increases. So even though the output
is in two-dimensional but a single loop works. Because the loop does two ting in this case (this case
is for using functions), one it provides the rows to be printed and other it defines the number of
characters to be printed corresponding to the row. For the case the number of rows is equal to the
number of characters to be printed, so there is no necessity of declaring, calculating any more
variables or any.
SCNAF FUNCTION FOR NUMBERS:-
All the above five tips are similar with two new things- one is 0 is declared before some number
value before decimal point, then the spaces vacant are filled by zeros i.e.
printf("%07d",9855) →
And other is that d can be replaced by ld, hd, d for long integers, short integers, etc. Here number
before decimal gives total space and number after decimal gives space for decimal values. But the
case for exponential is little different that part, that exponential takes the values according to the
number value available and take separate place whose place can’t be defined.
For e.g.
float y=223.34568;
printf("%-10.2e",y); →
Note: printf(“%*.*f”,width,precision,number) is valid.
These functions are used for various patterns but especially these are used to concise large value in
terms of exponent with proper width and precisions.
PATTERNS OF CHARACTERS AND NUMBERS USING PRINTF FUNCTIONS:-
For this case, as our patterns are in 2-D so usually two loops are required, however in some cases
one loop works (if the value of one loop can compensate other also). One loop is for outer purpose
of row and other is for column purpose.
Similar to the 2-D array, here the purpose of two loops is similar. The main focus is on inner loop
because the pattern is determined by it.
0 0 0 9 8 5 5
2 . 2 3 e + 0 0 2
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
33
BASIC PRINCIPLE OF PRINTING PATTERNS
Here two loops need to be required as general case but (being a special case) here) the row equals
to the number of characters of the string “NEPAL” to be printed. So here one loop is efficient if
concatenating function is used.
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main(){
int i;
char a[]="NEPAL";
for(i=0;i<5;i++) {
char final[5]="";
strncat(final,a,i+1);
printf("%d%s",i,final);
printf("\n");
}
getch();
}
Output:
0N
1NE
2NEP
3NEPA
4NEPAL
#include<stdio.h>
#include<conio.h>
void main(){
char a[]="NEPAL";
int i,j;
for(i=1;i<=5;i++) {
for(j=1;j<=i;j++) {
printf("%c",a[j-1]);
}
printf("\n");
}
getch();
}
Output:
N
NE
NEP
NEPA
NEPAL
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
34
As usual it uses two loops. Here the second is adjusted in such a way that it takes values from 1 to
number of rows it is present or from 1 to the value of outer loop it corresponds to. This is the basic
principle of making patterns. The above starts from 1 to 5, increasing 1 at a time means increasing 1
at time for each row increasing.
#include<stdio.h>
#include<conio.h>
void main(){
char a[]="NEPAL";
int i,j,k;
for(i=1;i<=5;i++) {
for(k=4;k>=i;k--){
printf(" ");
}
for(j=1;j<=i;j++) {
printf("%c",a[j-1]);
}
printf("\n");
}
getch();
}
Output:
N
NE
NEP
NEPA
NEPAL
Here as the rows increases, space decreases and in the same wave number of characters increases.
However ‘k’ is essential to declare that gives required space because here the value of k is
decreasing but I and j are increasing.
From above we can make a conclusion that the second loop is important and the main base is the
second loop which under takes the consideration of outer-loop.
We did for strings and similar is for numbers with the same basic fundamental principle.
Note: There are generally two ways of patterns- one is using string function directly and the
other is using character one at each time by 2d-loops like ‘for-loop.’ We have practiced both
the methods in the examples above.
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
35
SOME MORE PATTERNS
PU 2005 FALL5
IF INPUT IS “NEPAL” then output must be
1N
2EE
3PPP
4AAAA
5LLLLL
This program shows how the value of ‘i’ can be used in both- characters printing and number
printing. The corresponding value of ‘i’ for number printing is one more than for characters as
sharacter array starts from zero.
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main(){
char a[50];
int i=0,j=0;
printf("Enter a string");
scanf("%s",&a);
for(i=0;i<strlen(a);i++) {
printf("%d",i+1);
for(j=0;j<=i;j++) {
printf("%c",a[i]);
}
printf("\n");
}
getch();
}
Nepal
Nepa
Nep
Ne
N
#include<stdio.h>
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
36
#include<conio.h>
int main(){
char a[100]="Nepal";
int i=0,j=0,k=0;
for(i=1;i<=5;i++) {
for(j=1;j<=(5-i+1);j++) {
printf("%c",a[j-1]);
}
printf("\n");
}
getch();
return 0;
}
Hello
Hello
Hel
He
H
#include<stdio.h>
#include<conio.h>
int main(){
char a[100]="hello";
int i=0,j=0,k=0;
for(i=1;i<=5;i++) {
for(k=1;k<i;k++){
printf(" ");}
for(j=1;j<=(5-i+1);j++) {
printf("%c",a[j-1]);
}
printf("\n");
}
getch();
return 0;
}
h
he
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
37
hel
hell
hello
#include<stdio.h>
#include<conio.h>
int main(){
char a[100]="hello";
int i=0,j=0,k=0;
for(i=1;i<=5;i++) {
for(k=1;k<i;k++){
printf(" ");}
for(j=1;j<=i;j++) {
printf("%c",a[j-1]);
}
printf("\n");
}
getch();
return 0;
}
1
12
123
1234
12345
#include<stdio.h>
#include<conio.h>
int main(){
int number;
printf("Enter a Number");
scanf("%d",&number);
int i=0,j=0,k=0;
for(i=1;i<=number;i++) {
for(k=1;k<i;k++){ //space management
printf(" ");}
for(j=1;j<=i;j++) { //printing number from 1 to i for each line given by 'i'
printf("%d",j);
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
38
} printf("\n");}
getch();
return 0;
}
�� = � ��!
�
���
�� = 1 + + ���! +
���! + ��
�! + ���! + ��
�! +…………..� �!
#include<stdio.h>
#include<conio.h>
#include<math.h>
int main(){
printf("Enter power of e");
int x;
scanf("%d",&x);
printf("Enter n to be run");
int n;
scanf("%d",&n);
int i,j;
float sum=0;
float fact=1;
for(i=0;i<=n;i++){
float value= pow(x,i);
for(j=1;j<i;j++) fact=fact*j; /*factorial calculation*/
sum=sum+(value/fact);
}
printf("sum is %f ",sum);
getch();
return 0;
}
!"# = 1 � − 2 � + 3 � − 4 � + 5 � − 6 � + ⋯ … … , ./#!
#include<stdio.h>
#include<conio.h>
#include<math.h>
int main(){
printf("Enter value of x");
int x;
scanf("%d",&x);
printf("Enter n to be run");
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
39
int n;
scanf("%d",&n);
int i,j;
float sum=0;
for(i=1;i<=n;i++){
float value= pow(x,i);
if(i%2==0) {
sum=sum-i/value; /*for the case of even index sign is negative*/
}
else
{
sum=sum+i/value; /*for the case of odd index sign is positive*/
}
}
printf("sum is %f ",sum);
getch();
return 0;
}
PU2004
!"# = 01! − �
2! + �3! − �
4! + �5! . . … … … , ./#!
#include<stdio.h>
#include<conio.h>
#include<math.h>
int main(){
printf("Enter value of x");
int x;
scanf("%d",&x);
printf("Enter n to be run");
int n;
scanf("%d",&n);
int i;
float sum=0,term;
term= pow(x,1);
for(i=1;i<=n;i++){
sum=sum+((-x*term)/i);
}
printf("sum is %f ",sum);
getch();
return 0;
}
Here we are using a pattern .�=� 23∗�5�
�
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
40
Where .� represents ,�6 term and n is given by the for-loop; by i which gives the position of the
term and x is the input given by user. We can do this by next method using a function that finds out factorial and taking help of i to find
power of x and changing sign +,- after each term is found out and adding to sum , which is printed at
last.
Pu2011-fall-4b
WAP to print the series upto term is less than 250
Series
0�7��� ,
��7��� ,
��7��� ,
��7��� ,
��7��8 , ….…… upto term>250
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main(){
int i=1;
float sum=(pow(1,2)+pow(2,2))/3, oldsum=0;
while(sum<250) {
i+=1;
oldsum=sum;
sum=(pow(i,2)+pow(i+1,2))/(i+2);
}
printf("sum less than 250 is %f",oldsum);
getch();
}
Here actually at first the first term is kept in sum in initialization then it is checked and printed then i
is incremented to meet the next term of the series but before printing it is checked strictly. Here
sum is kept in float because we are not sure that the term is in int or not.
1111
1111
1111
1111
#include<stdio.h>
#include<conio.h>
int main(){
int i=0;
for(i=1;i<=16;i++) {
printf("%d",1);
if(i%4==0){ printf("\n");}
}
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
41
getch();
return 0; }
Here we are using a single loop of i, as after the numeric value of i divisible (4, 8, 12, 16) is printed
then line is broken out.
1
12
123
1234
#include<stdio.h>
#include<conio.h>
int main(){
int i=0,j=0,k=0;
for(i=1;i<=4;i++) {
for(k=1;k<=(4-i);k++){ /*to maintain required spacing*/
printf(" ");
}
for(j=1;j<=i;j++) {
printf("%d",j);
}
printf("\n");
}
getch();
return 0;
}
hints
1 1�
121 11�
12321 111�
1234321 1111�
#include<stdio.h>
#include<conio.h>
#include<math.h>
int main(){
int i=0,j=0,k=0;
int num=0;
int counter=0;
for(i=1;i<=4;i++) {
counter=counter*10+1;
for(k=1;k<=(4-i);k++){
printf(" ");
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
42
}
num=counter*counter;
printf("%d",num);
printf("\n");
}
getch();
return 0;
}
1
12
123
1234
#include<stdio.h>
#include<conio.h>
int main(){
int i=0,k=0; for(i=1;i<=4;i++) {
for(k=1;k<=i;k++){
printf("%d",k);
}
printf("\n");
}
getch();
return 0;
}
4321
432
43
4
#include<stdio.h>
#include<conio.h>
int main(){
int i=0,k=0;
for(i=4;i>=1;i--) {
for(k=4;k>=(4-i+1);k--){
printf("%d",k);
}
printf("\n");
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
43
}
getch();
return 0;
}
0.1 0.03 0.005 0.0007 0.00009 ……. for n terms
//0.1 0.03 0.005 0.0007 0.00009 ……. for n terms
#include<stdio.h>
#include<conio.h>
#include<math.h>
int main(){
int n;
double counter=1;
printf("enter value of n");
scanf("%d",&n);
int i;
int zeroafterdecimal=0;
for(i=1;i<=n;i++) {
counter/=10;
zeroafterdecimal++;
printf("%f\t",counter);
counter=counter+(2/pow(10,zeroafterdecimal));
}
getch();
return 0;
}
Floyd’s triangle
1
10
101
1010
10101
101010
.
.
.
upto n lines
/*1
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
44
10
101
1010
10101
101010
*/
#include<stdio.h>
#include<conio.h>
int main(){
int n;
printf("enter value of n");
scanf("%d",&n);
int i,j;
for(i=1;i<=n;i++) {
for(j=1;j<=i;j++) {
if(j%2==0) printf("0");
else printf("1");
}
printf("\n");
}
getch();
return 0;
}
5 55 555 5555 55555…………………………. upto n terms
//5 55 555 5555 55555….. upto n terms
#include<stdio.h>
#include<conio.h>
int main(){
int n;
printf("enter value of n");
scanf("%d",&n);
int i,j;
int count=5;
for(i=1;i<=n;i++) {
printf("%d\t",count);
count=count*10;
count+=5;
}
getch();
return 0;
}
NEPAL
EPA
P
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
45
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main() {
printf("enter a string (odd length)\t");
char string[40];
scanf("%s",&string);
int length=strlen(string);
int i,j,k;
int tim=length;
for(i=1;i<=((length/2)+1);i++){
for(k=1;k<i;k++)
printf(" ");
for(j=i;j<=tim;j++){
printf("%c",string[j-1]);
}
tim=tim-1;
printf("\n");
}
getch();
return 0;
}
OR
/*
NEPAL
EPA
P
*/
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main() {
printf("enter a string (odd length)\t");
char string[40];
scanf("%s",&string);
int length=strlen(string);
int i,j,k,con=0;
for(i=length-1;i>=0;i--){
for(k=i;k<length-1;k++)
printf(" ");
for(j=con;j<=i;j++){
printf("%c",string[j]);
}
con++ ;
printf("\n");
}
getch();
return 0;
}
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
46
Here in second case I = 4to 0 shows last position of character of each line up to which j’s value starts
from k=0 in first and then k++ i.e. k=1…..to k=2.however for k=3, i=1 so , j<=i doesn’t satisfy and runs
without any output. However the loop of I runs 2 more then necessary this can be controlled by
adding a condition that is
if (k=i) break;
in this condition the value of j is controlled up less or equal to equal or less.
1
2 2
3 3 3
4 4 4 4
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main() {
int n;
printf("enter a number\t");
char string[40];
scanf("%d",&n);
int i,j,k;
for(i=0;i<n;i++){
for(k=1;k<n-i;k++)
printf(" ");
for(j=0;j<=i;j++){
printf("%d",i+1);
}
printf("\n");
}
getch();
return 0;
}
1
22
333
4444
55555
#include<stdio.h>
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
47
#include<conio.h>
#include<string.h>
int main() {
int n;
printf("enter a number\t");
char string[40];
scanf("%d",&n);
int i,j,k;
for(i=0;i<n;i++){
for(k=0;k<i;k++)
printf(" ");
for(j=0;j<=i;j++){
printf("%d",i+1);
}
printf("\n");
}
getch();
return 0;
}
PATTERNS OF ‘*’
*
**
***
****
#include<stdio.h>
#include<conio.h>
int main(){
int n;
printf("enter value of n");
scanf("%d",&n);
int i,j;
for(i=1;i<=n;i++) {
for(j=1;j<=i;j++) {
printf("*");
}
printf("\n");
}
getch();
return 0;
}
****
***
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
48
**
*
#include<stdio.h>
#include<conio.h>
int main(){
int n;
printf("enter value of n");
scanf("%d",&n);
int i,j;
for(i=n;i>=1;i--) {
for(j=1;j<=i;j++) {
printf("*");
}
printf("\n");
}
getch();
return 0;
}
*****
****
***
**
*
#include<stdio.h>
#include<conio.h>
int main(){
int n;
printf("enter value of lines");
scanf("%d",&n);
int i,j,k;
for(i=n;i>=1;i--) {
for(k=1;k<=(n-i);k++) {
printf(" ");
}
for(j=1;j<=i;j++) {
printf("*");
}
printf("\n");
}
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
49
getch();
return 0;
}
*
***
*****
/*
*
***
*****
*/
#include<stdio.h>
#include<conio.h>
int main(){
int n;
printf("enter no of * but odd only else it change to lowest nearest odd");
scanf("%d",&n);
int i,j,k;
int count=0;
for(i=1;i<=n;i+=2) {
count++;
for(k=1;k<=(n-count);k++) {
printf(" ");
}
for(j=1;j<=i;j++) {
printf("*");
}
printf("\n");
}
getch();
return 0;
}
*****
***
*
/*
*****
***
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
50
*
*/
#include<stdio.h>
#include<conio.h>
int main(){
int n;
printf("enter no of * but odd only ");
scanf("%d",&n);
int i,j,k;
int count=0;
for(i=n;i>=1;i-=2) {
count++;
for(k=1;k<count;k++) {
printf(" ");
}
for(j=1;j<=i;j++) {
printf("*");
}
printf("\n");
}
getch();
return 0;
}
*
**
***
****
#include<stdio.h>
#include<conio.h>
int main(){
int n;
printf("enter no of lines");
scanf("%d",&n);
int i,j,k;
int count=0;
for(i=1;i<=n;i++) {
count++;
for(k=i;k<n;k++) {
printf(" ");
}
for(j=1;j<=i;j++) {
printf("*");
}
printf("\n");
}
getch();
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
51
return 0;
}
*
**
***
****
Here one space increase by each new line.
#include<stdio.h>
#include<conio.h>
int main(){
int n;
printf("enter no of lines");
scanf("%d",&n);
int i,j,k;
for(i=1;i<=n;i++) {
for(k=0;k<i-1;k++) {
printf(" ");
}
for(j=1;j<=i;j++) {
printf("*");
}
printf("\n");
}
getch();
return 0;
}
SOME MORE DIFFICULT PATTERNS
Pyramid of numbers:
1
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
52
2 3 2
3 4 5 4 3
4 5 6 7 6 5 4
5 6 7 8 9 8 7 6 5
#include<stdio.h>
#include<conio.h>
void main() {
int i,j,n=5;
for(i=1;i<=n;i++){
for(j=1;j<=n-i;j++)
printf("\t");
for(j=i;j<=2*i-1;j++) printf("\t%d",j);
for(j=2*i-2;j>=i;j--) printf("\t%d",j);
printf("\n");
}
getch();}
Reverse pyramid of numbers
5 6 7 8 9 8 7 6 5
4 5 6 7 6 5 4
3 4 5 4 3
2 3 2
1
#include<stdio.h>
#include<conio.h>
void main() {
int i,j,n=5;
for(i=0;i<=n;i++){
for(j=n-i;j<=2*n-2*i-1;j++)
printf("\t%d",j);
for(j=2*n-2*i-2;j>=n-i;j--) printf("\t%d",j);
printf("\n");
for(j=0;j<=i;j++) printf("\t");
}
getch();}
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
53
Herein pyramid of numbers and its reverse, we are printing pattern in installments i.e. is in two
parts; one part contains first 5 rows and the second contains left 4 rows. Such patterns are little bit
difficult and are useless for exam-oriented so its details are exclude.
1
01
101
0101
10101
010101
1010101
01010101
101010101
Here ‘back’ variable is used to alter the stored value (it is printed); ‘1’ and ‘0’, ‘back’ variable works
within a line only i.e. it changes value for appropriate values to be printed on same line. In contrast,
‘fback’ variable stores the first character (here ‘1’, ‘0’ are printed as characters) for each line. To
maintain pattern ‘back’ and ‘fback’ are initialized as zero. It is important to note the pattern that old
value of ‘fback’ not only changes ‘fback’ but also ‘back’, but this alternating takes place one time for
each new line, whereas the value of ‘back’ alters within a same line for the number of times equal to
the number of characters to be printed in the particular line. Study the scope of different ‘for-loop’
for this purpose.
#include<stdio.h>
#include<conio.h>
void main(){
int i,j,fback=1,back=1,n=20;
for(i=0;i<n;i++) {
for(j=0;j<=i;j++)
if(back==1) back=0,printf("1");
else back=1,printf("0");
printf("\n");
if(fback==1) fback=0,back=0;
else fback=1,back=1;
}
getch();}
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
54
1
2 3 2
3 4 5 4 3
4 5 6 7 6 5 4
5 6 7 8 9 8 7 6 5
Here input is “123456789”.
Read the relationship between outer ‘i’ loop and inner ‘j’ loop. Realizing the problem in 2D method,
the rows of the above pattern or lines of above patterns are represented by ‘i-loop’ and similarly the
columns of the above pattern or values at specific positions are represented by ‘j-loop’. These things
are mostly common in all 2D patterns; however the above pattern has many things to state. We
have used a separate variable-‘s’ to manage spacing but we can use ‘i’ variable (comparing ‘i’ with a
constant value) to manage space (such cases were done in former cases). The value of ‘i-loop’ is not
only used in specifying line but also in ‘j-loop’ to specify characters. It is the coincidence that the line
represented by ‘i’ resembles first value to be printed for the line so ‘i’ is used in ‘j-loop’. Similarly ‘k-
loop’ (used to print the reverse mannered numbers) used the property of ‘j’ as only for initialization
purpose and uses variable- ‘a’ but in decremented order to maintain reversed pattern.
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<stdlib.h>
int main() {
int i,s,j,k;
char string[100];
printf("Enter a string");
scanf("%s",string);
printf("\n");
if(strlen(string)%2==0) {/*odd number of characters*/
printf("ODD quantity of string is only preferrable");/*this is the limitation of the pattern*/
exit(0);
}
for(i=0;i<((strlen(string)/2)+1);i++) {
for(s=0;s<((strlen(string)/2)-i);s++) {/*space management*/
printf(" ");
}
for(j=i;j<((2*i)+1);j++) {
printf("%c",string[j]);
}
int a=j-2;
for(k=j+1;k<(j+1+i);k++){
printf("%c",string[a]);
a--;
}
printf("\n");
}
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
55
getch();
return 0;
}
Pascal’s triangle
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
Here input is ‘7’.
This pattern is same to binomial coefficients of Newton’s expansion.
The conclusion of the above pattern is
element [row] [column] = element [row-1] [column-1] + element [row-1] [column]
And a necessary vision is that the numbers glanced at from front or from behind each line is ‘1’ for
all the time.
The expression if(j ==0 || j==i){ line[i][j]=1; declares it. Here ‘j=0’ means first value for
each new line and ‘j=i’ is the last possible value of ‘j’ for the particulat line, the other thing we find is
that the value of ‘i’ for not only supports the row of pattern (or number of particular line) but also it
supports the total quantity of numbers to be printed; if(j ==0 || j==i) here ‘i’ has the
second purpose but line[i][j]=1 has the first purpose.
line[i][j]=line[i-1][j-1]+line[i-1][j]; this expresses the expression of above tabulation.
printf("\t\t"); here double tab maintains the necessary pattern between the numbers within a
same line.
#include<stdio.h>
#include<conio.h>
void main()
{
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
56
int i,j,k,n,line[50][50];
//clrscr(1);
printf("Enter a Number");
printf("\t");
scanf("%d",&n);
for(i=0;i<n;i++){
for(k=0;k<n-(i+1);k++){/*for tab space management before numbers*/
printf("\t");
}
for(j=0;j<=i;j++){
if(j ==0 || j==i){
line[i][j]=1;
printf("%d",line[i][j]);
}
else {
line[i][j]=line[i-1][j-1]+line[i-1][j];
printf("%d",line[i][j]);
}
printf("\t\t"); /*for tab space management between numbers*/
}
printf("\n\n"); /*for making more clearity of pattern*/
}
getch();
}
PU2002 FALL 5
WAP that takes angle in degrees and give out value of sine for that angle without using ‘sin()’
function of math library.
Actually, do you how your computer or a pocket calculator finds the value of sine? It is the
application of Taylor’s series for sine as follow:
sin x =930! − 9�
�! + 9��! − 9:
8! + 9;<! − … … … … … … … … … ..
here, ‘x’ is in radians. We can convert degrees to radians by : radian==>?@>>∗A
0B�
#include<stdio.h>
#include<math.h>
#include<conio.h>
float factorial(x){
float fact=1; int i;
for(i=1;i<=x;i++){
fact=fact*i;
}
return (fact);
}
void main () {
float degree,radian,sum=0,term;
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
57
int i,power;
printf("Enter the angle in terms of degrees:\t");
scanf("%f",°ree);
radian=(degree*3.14)/180;
for(i=1;i<=10;i++) {
power=(2*i)-1;
if(i%2==1) {
term=pow(radian,power)/(factorial(power));
}
else {
term=(-1*pow(radian,power)/(factorial(power)));
}
sum=sum+term;
}
printf("Sine(%f) =\t%f",degree,sum);
getch();
}
Here we use factorial that calculates factorial for the term required.
Initially after taking angle in degree we convert it into radians.
Then a for-loop running ten times is used so that we can calculate the sum for ten terms, but this can
be increased to any number (may be 99 or 999) so that we get our required accuracy in float values
after decimal.
Here we are using a pattern which shows that:
1. Each term has power like 1, 3, 4, 5, 7……. i.e. (2n-1), where ‘n’ shows the index of term
indicating the position. For first position n=1 gives power=(2*1-1)=1, similarly for second
term, power(2*2-1)=3, third has (3*2-1)=5 and so on….. So we are using variable ‘power’ to
represent the power for the term.
2. Each term is alternatively positive and negative. First term one is positive, second term is
negative, third term is again positive, fourth term is negative and so on…….. From this
pattern, we see that if the index of term representing the position of the term is odd then
the term is positive else it is negative.
if (i%2==1) THEN term=(pow(radian,power)/(factorial(index)));
else term=(-1*pow(radian,power)/(factorial(index)));
As we know ‘i’ here represents the index so we are checking if for ‘i’ to find whether term is positive
or negative and the statement following calculates required term with appropriate sign ‘+’ or ‘-’.
NEXT METHOD:
#include<stdio.h>
#include<math.h>
#include<conio.h>
void main () {
float degree,radian,sum=0,term;
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
58
int i;
printf("Enter the angle in terms of degrees:\t");
scanf("%f",°ree);
radian=(degree*3.14)/180;
term=pow(radian,1);
for(i=2;i<=2;i++) {
term=term-1*(term*pow(radian,2))/((2*i-2)*(2*i-1));
sum=sum+term;
}
printf("Sine (%f) =\t%f",degree,sum);
getch();
}
Here we have little bit analyze the pattern of the terms with reference to two things: one is term
preceding the term to be calculated and the other is with the index representing the position of the
term to be calculated. If we study the pattern, we come with many conclusions, one of them may be
like this (this one is used in the program):
1. In the numerator of each term, each term succeeding is multiplied by - to preceding term.
2. In the denominator, for eg. look 3! (of second term) is converted to 5! (of third term), by
multiplying 3! by 4 and 5 one after another consecutively. We may analyze that each new
term is obtained by dividing each preceding term to (2n-1) and (2n-2),i.e.
denominator of any term=denominator of preceding term*(2n-1)*(2n-2), where ‘n’ is the
index representing the term to be found out.
For e.g.
denominator of third term=denominator of second term*[(2*3-1)*(2*3-2)=5*4]. This is how
3! is changed to 5!.
(2n-1)*(2n-2) can be changed to (2n-2)*(2n-1) in order to make the order of ascending
according to our easiness for the pattern of the program.
Similarly, we may change this ‘(2n-2)*(2n-1)’ = ‘2(n-1)*(2(n-1)+1)’ and we may use this in our
code instead of ‘(2n-2)*(2n-1)’, where ‘i’ is used instead of ‘n’ in code.
By above, we come to conclusion,
termG = termG50 ∗ x��2n − 2 ∗ �2n − 1
OR
termG = termG50 ∗ x�2�n − 1 ∗ �2�n − 1
Where, ‘n’ represents the index of the term to be found out.
NOTE: if we can’t any library function then in above instead of ‘pow()’ use the method described
to calculate power without any function of “without function”-section.
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
59
Conversion
Decimal to binary
2 12
2 6 0
2 3 0
2 1 1
0 1
So �120� = �1100�
Here ‘factor’-variable works as a multiplier to obtain appropriate numbers of appropriate digits,
please refer ‘Digits taking from number’ for further.
// decimal to binary
#include<stdio.h>
#include<conio.h>
int main() {
int deci;
int r;
int sum=0;
int factor=1;
printf("enter decimal number\t");
scanf("%d",&deci);
while(deci>0) {
r=deci%2;
deci=deci/2;
sum=sum+r*factor;
factor*=10;
}
printf("The answer is %d",sum);
getch();
return 0;
}
Binary to decimal
1100=�1 ∗ 2� + �1 ∗ 2� + �0 ∗ 20+(0*2�)
// binary to decimal
#include<stdio.h>
#include<conio.h>
#include<math.h>
int main() {
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
60
int bina;
int digit;
int sum=0;
int i=0;
printf("enter binary number\t");
scanf("%d",&bina);
while(bina>0) {
digit=bina%10;
bina/=10;
sum=sum+digit*pow(2,i);
i++;
}
printf("The answer is %d",sum);
getch();
return 0;
}
Exclusive use of ‘switch-case’ and ‘goto’ statements
2005PU A program that takes a sum of money and starts converting it to smaller units where
user can choose his first starting unit. The conversion is in such a way that the first starting units
takes maximum possible conversion then the left sum is supplied to conjugate term following it, this
process continues till the end.
#include<stdio.h>
#include<conio.h>
int main(){
int currency;
int choice;
int m;
printf("Enter currency\t");
scanf("%d",¤cy);
printf("\n Enter 1000 to start from 1000");
printf("\n Enter 500 to start from 500");
printf("\n Enter 100 to start from 100");
printf("\n Enter 50 to start from 50");
printf("\n Enter 20 to start from 20");
printf("\n Enter 10 to start from 10");
printf("\n Enter 5 to start from 5");
printf("\n Enter 2 to start from 2");
printf("\n Enter 1 to start from 1");
printf("-----------------------------------------------\n\n\n\n");
scanf("%d",&choice);
switch (choice) {
case 1000:
goto thousand;
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
61
case 500:
goto fivehun;
case 100:
goto hundred;
case 50:
goto fifty;
case 20:
goto twenty;
case 10:
goto ten;
case 5:
goto five;
case 2:
goto two;
case 1:
goto one;
}
thousand:
m=currency/1000;
currency=currency%1000;
printf("The no. of thousands(1000) is\t\t\t%d\n",m);
goto fivehun;
fivehun:
m=currency/500;
currency=currency%500;
printf("The no. of five hundreds(500) is\t\t\t%d\n",m);
goto hundred;
hundred:
m=currency/100;
currency=currency%100;
printf("The no. of hundreds(100) is\t\t\t%d\n",m);
goto fifty;
fifty:
m=currency/50;
currency=currency%50;
printf("The no. of fifty(50) is\t\t\t%d\n",m);
goto twenty;
twenty:
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
62
m=currency/20;
currency=currency%20;
printf("The no. of twenty(20) is\t\t\t%d\n",m);
goto ten;
ten:
m=currency/10;
currency=currency%10;
printf("The no. of ten(10) is\t\t\t%d\n",m);
goto five;
five:
m=currency/5;
currency=currency%5;
printf("The no. of five(5) is\t\t\t%d\n",m);
goto two;
two:
m=currency/2;
currency=currency%2;
printf("The no. of two(2) is\t\t\t%d\n",m);
goto one;
one:
m=currency/1;
currency=currency%1;
printf("The no. of one(1) is\t\t\t%d\n",m);
getch();
return 1;
}
The general mechanism of each block of indices like ‘fifty:’ ’five hun:’….. checks whether the sum of
money left for it after preeceeding calculations; are sufficient enough to hold that value or not. If yes
then it does calculation. Here calculation means subtracting the left sum by the respective amounts
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
63
and then ‘goto-statement’ transfers the execution flow to next succeeding block of indices until last
index ‘one:’. Here ‘m=variable’ gives the quantity of each amount in each block. At first user is given
choice to start converting money from what bigger amount of sum like from 500 or 1000 or 100 or
50 or any. So the above mechanism starts from the respective block only. Here ‘swich-case’ is used
to meet user’s choice in various alternatives. If someone wants to coiunt money from 500 then the
sum he enters will not be counted from 1000 instead it will be counted from 500 then 100 then 50
then 20 then 10 then5 then 2 and finally 1. It is not necessary that all blocks assume some value
because the sum we enter are divisible for some; not for other and even if it is divisible the sum to
be calculated on a block changes from block to block as the calculation begins.
SORTING
Selection sorting
Algorithm (for ascending)
• Compare a [1] with second element a [2]. If a [2] is smaller than a [1] then interchange their
values.
• Compare a [1] with a [3]; interchange their values if a [3] is smaller than a [1].
• Continue comparing a [1] with other numbers.
• Repeat above processes (1, 2 and 3) for a[2],a[3]………a[n-1] comparing a[2] from a[3] to
a[n], a[3] from a[4] to a[n]………a[n-1] with a[n].
In the repeated trips the each element compares with other remaining elements coming after it and
the smallest numbers come up directly by selection (or it may step up wisely by co-incidence). Hence
it is called selection sorting as each element compares with the other. Actually, there is the
comparison of no element but there is the comparison of elements of specified addresses. Elements
don’t change, however their addresses change. So in sorting, comparison is between addresses that
take values as per condition; that is suited for the purpose-ascending or descending. Here each loop
decides the comparison of element of an address to the other addresses but not of all addresses. So
the inner loops successively give the necessary sorting. The trend of loops goes on decreasing from
(n-1) to1 because as the loop continues each time, each address gets secured on its position.
We have started comparing numbers from j=0 to j=n-1 so the address (1) gets secured and then in
next i=1 address (2) gets secured and so on. If we had started from j=n to j=2 (similarly to above
case, here j=1 automatically secured after last loop because according to the sense we know any
number of things can change their physical property; place in reference to a single thing or with
reference to a body, others can only change in regard to the values they posses, not on the specific
places they posses and hence in above case j=1 is not taken) the addresses of j=n first gets secured
then j=n-1, j=n-2……j=2 and j=1 automatically gets secured.
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
64
While the outer loop, is to supply each number (or actually each address) at a time which can be
altered in any positions of numbers from 1 to n-1 or n to 2. Here one is not taken this is the similar
case described above because one becomes our reference address again.
Work of outer loop (i) is to just facilitate each numbers each time except the reference address.
Work of inner loop (j) is to compare each address (pointer) with the other taking a reference
address. The result won’t alter if we take under consideration- the comparison of reference address
but a good program minimizes the working time and process and in other proper understanding of
pointers is the input for this program. So we don’t take the reference pointer under consideration.
You can get soft copy of this book @ www.scribd.com/dpalikhe.
Illustration of Selection Sort of four items
In each trip, a value gets secured (or a pointer gets secured). The number of comparisons= (n-1) + (n-
2) + (n-3) +………1 Sum of (n-1)……….1 is n (n-1)/2
[NOTE: Actually, we directly don’t declare reference pointer but on our assumptions, automatically
the reference pointer is achieved. We need to analyze it for more efficiency of the program.]
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
65
For descending we can simply change the condition; inverse the condition.
NOTE: Examples are done in coming using selection and bubble sorting.
Bubble sorting
For ascending,
• Compare first two elements a [1] and a [2]. If a [2] is smaller than a [1], interchange their
values.
• Compare a [2] and a [3]; interchange them if a [3] is smaller than a [2].
• Continue for all values serially.
• Repeat above (1, 2, and 3) for (n-1) times.
In repeated trips through the array, the smallest elements ‘bubble up’ to the top one step at one
loop (inner loop). Because of this bubbling up effect, this algorithm is called bubble sorting.
Ilustratration of Bubble Sort of four items
In each trip, the smallest number ‘10’ shifts one position up at the end of trips. The number of
comparisons = n (n-1)/2
In above,
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
66
4(4-1)/2 = 3+2+1
6=6 proved
For Descending, change
if (a[j]>a [j+1]) { to if (a[j] <a [j+1]) {
Third sorting process
The number of loops for both bubble and selection remains the same. The sorting processes are the
same for both string and numbers. The above two sorting processes worked on the basis that each
number is compared with others in the order of (n-1) to (n-2) to (n-3) to (n-4)………….to 1 times. This
may sometime give unnecessary processes that take long time consuming in the case of dealing with
a large quantity of numbers. Co-incidentally two or more numbers sometime may be in ascending or
descending before our interaction with them. This ascending or descending may be with numbers of
small packet range to higher packet range (here packet means a group i.e. numbers in consequent
places) or these packets may be in large quantities i.e. more in numbers quantitatively. However the
above programs cannot take the consideration or advantage of this (if it is available by co-incidence)
because the above program works taking the base of pointer first then the numbers in pointers.
There two loops were used. This advantage can be used by a concept using goto and a single loop.
The above programs worked on the basis of securing each pointer each time and decreasing the
inner loops, each time of outer loop. Taking both the advantages one of decreasing inner loop and
other of taking probability of packets of ascending or descending numbers( that may have high
probability of low or 0 co-incidentally), we can solve this by taking our base with the numbers (i.e.
their values) at first then the pointers that are connected to. This is as follow:
for(i=0;i<n;i++) {
scanf("%d",&number);
A:
for(j=0;j<i;j++) {
if(num[j]<number) {
temp=num[j];
num[j]=number;
number=temp;
j++; /*deleting these two statements ‘j++’ ,‘goto A:’ also doesn’t affect the output of program*/
goto A;
}
}
}
for(i=0;i<5;i++) {
printf("%d",num[i]);
}
This method is exclusively used in coming sorting program.
Analysis of the solution
1. Numbers fixed
2. Numbers dynamic: - Dynamics over come and its special case is static. So, we take
the dynamic array analysis. Each time a number is taken from users. Before that, array with
proper dimensions and sizes are declared. So there are vacant spaces for the numbers. It
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
67
doesn’t matter whether the consideration with string, character or numbers. Let us consider
the above program for 1-D and for numbers. First of all the loop under (i) takes each number
from user but it is not assigned to array because if it is assigned a next loop will be required a
more time and this is with basis of pointer rather than number similar to above sorting
processes and hence it doesn’t work on our requirement. Assigning to an array means basis
on pointers rather than numbers. So the number is stored in variable called number that
takes different values supplied for different times or in different loops of (i). Then the second
loop of (j) starts here ‘A:’ has important to do (to be discussed in coming parts). The number
is compared to num[j] (initially 0) and hence the number is assigned to num[j] (i.e. initially
num [0]). This is a special case that works for the first number supplied by user. Now num[j]
is not vacant.
‘Interchanging values’ is done in above sections, refer it for analysis.
Here number supplied gets its position (but not secured positions because there are still many
numbers to be supplied by users and to be compared by program). At i=0, j=0, number takes value of
temp; value of original num[j] =0. So it goes to ‘A:’ label but condition fails( and it is intended to fail)
because num[j]<numbervalue supplied initially <0 (which failed for positive value), if the value is
negative the case will be other because if the number is negative then during first condition before
‘goto’ the condition fails the negative number supplied goes to vain. There is no space, no array for
negative numbers because the num[j] =0 automatically (initially). So our program works with the
assumption that the first number should be positive but the second, third……numbers can be both
negatives and positives. However we can take advantages of this case for the case of positive
numbers. We can remove the disadvantage by taking a very negative number as num [0] and
executing all but in this case the output of sorted numbers should be from num [0] to num [n-1] as
regular in above. This is for the case of descending.
Now the number zero (declared automatically) goes to vain. This was intended to do. J=0 to I j=0to0
and the inner loop exits and i=1 so that a number is taken from user compared to num[0] if number
is big it replaces it and values interchange and ‘goto’ makes to take the other value to other array
element. In this way, if the condition of ‘if’ is satisfied then it displace the value of certain array index
and the value of array index is tested for array [index+1] so that the values get proper place for their
descending values.
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
68
Here the value of j is incremented for j, because the displaced numbers need to be compared with
the index after it which is sure to be displaced by it because the process is in descending at last of
each loop. In this way, our achievement is got.
Advantage → Sorting is based on each number so the sorting is purely dynamic, each case and each
end of loop gives required sorting of numbers. This sorting even in transition period can be useful for
our various purposes and projects.
Disadvantage → If sorted packets aren’t available in sufficient way or it can’t overcome the pointer
basis sorting (that may be due to less probability in gradual sequential deviation) then the number of
loops is high and time consuming.
In all cases descending and ascending are changed by inversing the condition within if (). But in third
sorting for descending, num [0] is declared zero it can also be left doing nothing as with ascending
(depending upon compiler).
PU2011FALL 5b)
Sort ‘n’ numbers by function (special)
/*
we are sorting in ascending order,
this process is a type of third sorting we described in sorting-section
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
69
*/
#include<stdio.h>
#include<conio.h>
int i,j,number,num,temp;
int innersort[100]; //declare it globally
void sorting(int num);
void printing();
void main(){
printf("how many numbers?");
scanf("%d",&number);
for(i=0;i<number;i++){
printf("\nEnter a number:\t");
scanf("%d",&num);
sorting(num);// call the function for each value entered
}
printing();
getch();
}
void sorting(int num) {
static int counter=0; //can be declared as global variable too
printf("num to be ckd=%d\n\n",num);
for(j=0;j<counter;j++) {
if(num<innersort[j]) {
temp=innersort[j];
printf("one swapping done\t"); /*this line shows only execution (swap occurs) if entered new
number is less than previously entered numbers and the number of execution of this statement for a
newly entered number shows that the number of times the swapping is done for the new number
with the stored numbers*/
innersort[j]=num;
num=temp;
}
}
innersort[counter]=num;
counter++;
}
void printing(void) {
printf("\nsorted list is\n");
for(i=0;i<number;i++){
printf("\n%d",innersort[i]);
}
}
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
70
Description
It is good if you look the 3@=sorting type described in the sorting portion. This above technique takes
each number from user and does ‘innersort’-function invoke. This function takes each number as
input and sort in the series of previously sorted list. To count the previously saved sorted numbers
counter variable (static type is used here so that its value has scope within function and the
declaration static counter=0 is used only in 1KL time function calling, later in coming calls the
statement counter++ affects it only increasing by one per time the new number is given as argument
to function but … it doesn’t hamper if we use counter a global variable in main method. Similar as
counter we can declare innersort[100] as static type inside function but the problem is that at last
while printing the sorted output we need to print the values of innersort which is done by printing()
function as it can’t use static innersort() declared inside sorting function, so extern or globally the
variable innersort is declared) is used. The loop of I starts from 0 to counter-1. The input num is
checked to array of ‘innersort[]’, if condition is met then the num replaces the particular innersort[]’s
value and the innersort[]’s value is taken by num and the loop still continues till all numbers are
checked in condition. Here the new ‘num’ checks the values for the left part of i-loop and at last,
after successive replacing appropriate values at appropriate places there is left a value num whose
address of address of array, so the ‘innersort[counter]=num’ gives the last position to the number.
Counter is increased each time as each new ‘num’ is assigned a new place so each time a number is
increasing. The declaration of counter, increment, scope using of counter in specific positions of the
program has its own vital and specific purposes. Initially counter=0 so that the loop of i fails and it is
our intention too because at initializing 1KLnumber there is no need of any sorts of comparisons.
Then the number sis initialized to array index0; the 1KLposition then counter is incremented showing
that how many numbers are sorted in the list. Hence the value of counter at various points shows
the number of elements sorted and added in the list of innersort array.
But after a condition is met, the number from innersort and assigned to num has nothing to do with
the left upcoming pattern of sorting in i-loop except finding a place between number replacing its
origin place and the number previously succeeding it. So we can use a method below:-
For e.g.
1 20 50 100
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
71
If is the list of innersort[] elements.
If the new ‘num’ is then it must be inserted in between and as like
Index 0 1 2 3 resulting into
Index 0 1 2 3 4
Such direct replacement is not possible in C, so we continue our while loop of i and replace in each
loop and at last a new position is declared.
Let us analyze the problem in reality
Solution:
Here 4 numbers 1, 20, 50, and 100 are already declared in inner loop as
innerloop[0]=1
innerloop[1]=20
innerloop[2]=50
innerloop[3]=100
Now the function ‘sorting()’ is called; let us suppose for a new value 25 as sorting(25).
Here the value of counter =4 because as we know counter=number of values sorted in innersort[] as
described earlier. So the remaining process goes like for (i=0 to 3)
i Condition Result Remark
0 25<1 False Just continue loop of i
1 25<20 False Just continue loop of i
2 25<50 True Replace num and innersort[2]’s value i.e.
temp=20;
innersort[2]=25;
1 20 50 100
25
1
20 20 50
20 25 50 100
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
72
num=50;
(cont…..)
So the list now in innersort looks like
Index 0 1 2 3
Value
and the variable num=50.
Now this variable needs to be inserted but it doesn’t matter us because there is still a loop of i to be
continued.
i Condition Result Remark
3 50<100 True Replace num and innersort[3]’s value i.e.
temp=100;
innersort[3]=502;
num=100;
Now the list of innersort looks
Index 0 1 2 3
Value
and num=100.
Now it is directly assigned by innersort[counter] i.e.
innersort[4]=100;
and the list is as
Index 0 1 2 3 4
Value
This is our required aim of function. In this way the function maintains the sorting ability for each
new number taken each time from user.
A SPECIAL ANALYSIS
We saw that after we have replaced 25 in its position the new num for the particular instant was 50
and for next loop was 1 needs no further comparison in between themselves i.e. after the
comparison of num with the sorted list and getting its appropriate the other numbers need o other
comparisons as they were sorted in previous sorting i.e. of previous function call. So, we can just
change their address position’s index by +1, like below:-
1
1
1
20 25 100
20 25 50
20 25 50 100
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
73
void sorting(num){
for(i=0;i<counter;i++) { //i=0 to counter-1
if(num<innersort[i]) {
temp[counter-1-i];
temp[0]=innersort[i];
innersort[i]=num;
for(j=1;j<counter-i;j++) { //j=1 to counter-1-i
temp[j]=innersort[i+j];
}
for(k=0;k<counter-i;k++) { //k=0 to counter-1-i
innersort[i+k+1]=temp[k];
}
printing();//break the function
}
}
The declaration
temp[counter-1-i]; why?
counter show total positions but as the array starts from zero index so -1 is used as i times the loop
is runned already or the particular instant value of i resembles the number of index of innersort up
to which value is sorted.
Then this ‘temp-array’ assigns all the values including the value replaced by the num to all the
succeeding values.
We take advantage of value of j in finding the left positions of values and assigning it to temp
governed by j. so j has two purposes, one finding position of preceding values and assigning to new
temp values.
At last k-loop is run,
innersort[i+k+1]=temp[k] ?
The value of i is of index and similarly is with k, but the position value differs by +1 as we need the
next position to the index i so at first i+k+1=i+0+1=i+1, next time i+1+1=i+2 and so on, the value is
index resenting temp[]. As value of k increases, the new position of innersort is assigned a new value
at each time of increment.
Now we are adding a new feature to above program
/*
we are sorting in ascernding order,
this process is a type of third sorting we described in sorting-section
*/
#include<stdio.h>
#include<conio.h>
int i,j,num,temp,counting_num=0;
int innersort[100];
void sorting(int num);
void printing(void);
void main() {
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
74
readnextnumber:
printf("Enter any number\nOr enter -999 to look sorting:\t");
scanf("%d",&num);
if(num==-999){ goto outside;}
counting_num++;
sorting(num);
goto readnextnumber;
outside:
printing();
getch();
}
void sorting(int num) {
static int counter=0;
for(j=0;j<counter;j++) {
if(num<innersort[j]) {
temp=innersort[j];
innersort[j]=num;
num=temp;
}
}
innersort[counter]=num;
counter++;
}
void printing(void) {
printf("The sorted list is\n");
for(i=0;i<counting_num;i++){
printf("%d\n",innersort[i]);
}
}
Here we are not directly asking how many number to be sorted instead we are saying that -999
made as an input shall determine the end of input automatically.
EXAMPLES OF SORTING
SORT NUMBERS ASCENDING (SELECTION SORTING)
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
75
//SORT NUMBERS ASCENDING (SELECTION SORTING):
#include<stdio.h>
#include<conio.h>
int main() {
int i=0,j=0,number[100],temp,n;
printf("Enter how many numbers\t");
scanf("%d",&n);
printf("\n\n\n");
for(i=0;i<n;i++) {
printf("Enter [%d] number\t",i+1);
scanf("%d",&number[i]);
}
/*Sorting begins-ascending*/
for(i=1;i<n;i++) {
for(j=i+1;j<=n;j++) {
if(number[i]>number[j]) {
temp=number[i];
number[i]=number[j];
number[j]=temp;
}
}
}
printf("\n Ascending List \n\n");
for(i=0;i<n;i++)
printf("%d\t",number[i]);
getch();
return 0;
}
SORT NUMBERS DESCENDING (BUBBLE SORTING)
//SORT NUMBERS DESCENDING (BUBBLE SORTING)
#include<stdio.h>
#include<conio.h>
int main() {
int i=0,j=0,number[100],temp=0,n;
printf("Enter how many numbers\t");
scanf("%d",&n);
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
76
printf("\n\n\n");
for(i=0;i<n;i++) {
printf("Enter [%d] number\t",i+1);
scanf("%d",&number[i]);
}
/*Sorting begins-ascending*/
for(i=0;i<n;i++) {
for(j=(i+1);j<n;j++) { //for(j=1;j<=n-i;j++)can be used as at first point j=(i+1)=(0+1)=1 and j<=n-i is
same to j<n
if(number[i]<number[j]) {
temp=number[i];
number[i]=number[j];
number[j]=temp;
}
}
}
printf("\n Descending order \n\n");
for(i=0;i<n;i++)
printf("\t%d\t",number[i]);
getch();
return 0;
}
SORT 5 NAMES ASCENDING (BUBBLE SORTING)
Here sort is necessary we use bubble sort or selection sort or the last sort we looked in sort portion,
similarly here dummy; a temporary variable works as temp variable of before whose only purpose is
to interchange values. Strcpy() copies string [j-1] (string[0], string[1], string[2]…….)to dummy which is
taken by string[j] (string[1],string[2]……) All its process are similar to the above three cases of
numeric.
//SORT NAMES ASCENDING (BUBBLE SORTING)
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main() {
char string[100][20],dummy[20];
int i=0,j=0,n;
printf("Enter quantity\n");
scanf("%d",&n);
while (i<n) {
printf("Enter a name\t:");
scanf("%s",&string[i++]);
} //while-loop terminal
/*Sorting begins-ascending*/
for(i=1;i<n;i++) {
for(j=1;j<=n-i;j++) {
if(strcmp(string[j-1],string[j])>0) {
strcpy(dummy,string[j-1]);
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
77
strcpy(string[j-1],string[j]);
strcpy(string[j],dummy);
}
}
}
printf("\n Alphabetical List \n\n");
for(i=0;i<n;i++)
printf("\n[%d]=\t%s",i+1,string[i]);
getch();
}
SORT NAMES DESCENDING (SELECTION SORTING)
//SORT NAMES DESCENDING (SELECTION SORTING)
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main() {
char string[100][20], dummy[20];
int i=0,j=0;
int num;
printf("Enter qunatity:\t");
scanf("%d",&num);
printf("Enter names of %d items\n",num);
while (i<num) {
printf("Enter a name");
scanf("%s",&string[i++]);
}
for(i=0;i<(num-1);i++) { //the last is rejected automatically
for(j=i+1;j<num;j++) {
if((strcmp(string[i],string[j]))<0) {
strcpy(dummy,string[j]);
strcpy(string[j],string[i]);
strcpy(string[i],dummy);
}
}
}
printf("\n Descending List \n\n");
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
78
for(i=0;i<num;i++)
printf("\n[string%d]=%s",i+1,string[i]);
getch();
}
A PROGRAM THAT TAKES NAMES AND FIVE SUBJECT MARKS OF FIVE STUDENTS THAT
DISPLAY STUDENT RANKS AND SUBJECT MARKS (BY USING SELECTION SORTING)
Hints:
Here array is an important too to store names, their corresponding subject marks, and its
percentages. We sort percentage, in the way of sorting percentage, we interchange corresponding
values of names so that in the way of our sorting (in this case descending-for mark sheet) percentage
it corresponds to its names and hence the two field names and percentage interchange
simultaneously. If we want to print subject marks, then we need to interchange subject mark’s
pointer similar to the above cases.
Median and Standard Deviation
For median
We first arrange in ascending or descending order then
For even quantity of numbers, median=�G/�NO7�P�70NO
� value
For odd, median=�P�70NO
� value
//median
#include<stdio.h>
#include<conio.h>
int main() {
int i=0,j=0,number[100],temp;
int n;
int median;
printf("Enter how many numbers\t");
scanf("%d",&n);
printf("\n\n\n");
for(i=0;i<n;i++) {
printf("Enter [%d] number\t",i+1);
scanf("%d",&number[i]);
}
/*Sorting begins-ascending*/
for(i=1;i<n;i++) {
for(j=i+1;j<=n;j++) {
if(number[i]>number[j]) {
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
79
temp=number[i];
number[i]=number[j];
number[j]=temp;
}
}
}
if(n%2==0) {
median=(float)(number[n/2-1]+number[n/2+1-1])/2;
/*here in contrast to formula,'-1', 1 is subtracted at last ascharacter array starts from zero so
to maintain equilibrium with such array*/
}
else {
median=number[n/2+1-1]; /*same to above*/
}
printf("the median is %d",median);
getch();
return 0;
}
For standard deviation
We find mean; Mean=0G ∑ xG0
then variance is find out
Variance= 0G ∑ �x − mean�G0
Standard deviation=√variance
//mean, variance and standard deviation
#include<stdio.h>
#include<conio.h>
#include<math.h>
int main() {
int i=0,number[100];
int n;
float mean=0,variance,sd;
printf("Enter how many numbers\t");
scanf("%d",&n);
printf("\n\n\n");
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
80
for(i=0;i<n;i++) { /*input and mean calculation*/
printf("Enter [%d] number\t",i+1);
scanf("%d",&number[i]);
mean=mean+(float)number[i]/n;
/*as we know total quantity then mean is the sumation of all numbers divided by total
quantity*/
/*here casting is essential to prevent truncation of value (losing values afetr deciaml)due to
integer division*/
}
printf("The mean is \t%.4f\n",mean);
for(i=0;i<n;i++) { /*variance calculation*/
variance=(float)1/n*(pow(((float)number[i]-mean),2));
/* instead we can do divide by 'n' after all summation afetr for-loop too*/
/*casting is essential*/
}
printf("The variance is \t%.4f\n",variance);
sd=pow(variance,0.5); /*standard deviation calculation*/
printf("The standard deviation is \t%.4f",sd);
getch();
return 0;
}
MATRIX ARRAY
Matrix is 2-D like in similar way the array elements are actually stored (whether it is 2-D or 3-D or
multi-D). So taking this advantage matrix can be easily expressed in terms of array elements where
loops are used to define and express array elements (detailed in Array Section). Here define means
declaration and intake whereas express means printing or analyzing array elements for calculations
or comparisons.
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
81
CASES:
Case-1: Finding smallest and greatest of a matrix
For this we keep the first value to ‘small’ and ‘big’ and compare each value according to required
and if condition satisfies the new value is assigned to the variables and lastly we print output.
//greatest and smallest element in matrix
#include<stdio.h>
#include<conio.h>
void main(){
int matrix[3][3];
int small,big;
int i,j;
for(i=0;i<3;i++) {
for(j=0;j<3;j++) {
printf("Enter matrix1[%d][%d]",i,j);
scanf("%d",&matrix[i][j]);
}
}
small=matrix[0][0];
big=matrix[0][0];
printf("\n\n");
for(i=0;i<3;i++) {
for(j=0;j<3;j++) {
if(matrix[i][j]>big) big= matrix[i][j];
if(matrix[i][j]<small) small= matrix[i][j];
}
}
printf("The smallest matrix element is %d\n",small);
printf("The biggest matrix element is %d",big);
getch();}
Case-2:
Sum of diagonal elements of square 3*3 matrix
1. sum of diagonal from right top to left bottom
1 2 34 5 6 7 8 9 here required = 3+5+7
3=matrix[0][2]
5= matrix[1][1]
7= matrix[2][0] i.e the value of sum of indices is less than 3 or equal to 2
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
82
//sum of diagonal from right top to left bottom
#include<stdio.h>
#include<conio.h>
void main(){
int matrix[3][3];
int i,j;
int sum=0;
for(i=0;i<3;i++) {
for(j=0;j<3;j++) {
printf("Enter matrix1[%d][%d]",i,j);
scanf("%d",&matrix[i][j]);
}
}
printf("\n\n");
for(i=0;i<3;i++) {
for(j=0;j<3;j++) {
if(i+j==2){ //i+j<3 also works
sum=sum+matrix[i][j];
}
}
}
printf("The sum of diagonal from right top to left bottom %d\n",sum);
getch();
}
2. sum of diagonal from left top to right bottom
1 2 34 5 6 7 8 9 here required = 1+5+9
3=matrix[0][0]
5= matrix[1][1]
7= matrix[2][2] i.e the value of index ‘I’= index’j’
//sum of diagonal from left top to right bottom
#include<stdio.h>
#include<conio.h>
void main(){
int matrix[3][3];
int i,j;
for(i=0;i<3;i++) {
for(j=0;j<3;j++) {
printf("Enter matrix1[%d][%d]",i,j);
scanf("%d",&matrix[i][j]);
}
}
int sum=0;
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
83
printf("\n\n");
for(i=0;i<3;i++) {
for(j=0;j<3;j++) {
if(i==j){
sum=sum+matrix[i][j];
}
}
}
printf("The sum of diagonal from left top to right bottom %d\n",sum);
getch();}
Case-3: Finding a matrix element in a matrix
For this, comparison is done with all values or elements of matrix and lastly result is shown. If it is
found then counter =1 and hence we don’t print “not found”.
// Finding a matrix element in a matrix
#include<stdio.h>
#include<conio.h>
void main(){
int matrix[3][3];
int i,j;
for(i=0;i<3;i++) {
for(j=0;j<3;j++) {
printf("Enter matrix1[%d][%d]",i,j);
scanf("%d",&matrix[i][j]);
}
}
int search;
printf("Enterthe element to be find out?\t");
scanf("%d",&search);
int counter=0;
printf("\n\n");
for(i=0;i<3;i++) {
for(j=0;j<3;j++) {
if(matrix[i][j]==search){
printf("the element [%d] is found in [%d] row and [%d] column",search,i+1,j+1);
counter+=1;
}
}
}
if(counter!=1){
printf("not found");
}
getch();}
Case-4: sum of all elements in a matrix
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
84
Here’ sum’ sums all the values of matrix.
//Case-3: sum of allelements in a matrix
#include<stdio.h>
#include<conio.h>
void main(){
int matrix[3][3];
int i,j;
for(i=0;i<3;i++) {
for(j=0;j<3;j++) {
printf("Enter matrix1[%d][%d]",i,j);
scanf("%d",&matrix[i][j]);
}
}
int sum=0;
printf("\n\n");
for(i=0;i<3;i++) {
for(j=0;j<3;j++) {
sum=sum+matrix[i][j];
}
}
printf("the sum is %d",sum);
getch();
}
Case-5: transpose of a matrix
Here we know in transpose matix the values are interchanged in rows and columns that is I and j are
interchanged.
1 2 34 5 6 7 8 9
Its transpose is
1 4 72 5 8 3 6 9
// transpose of matrix
#include<stdio.h>
#include<conio.h>
int main(){
int matrix[3][3],newmatrix[3][3];
int i,j;
for(i=0;i<3;i++) {
for(j=0;j<3;j++) {
printf("Enter matrix1[%d][%d]",i,j);
scanf("%d",&matrix[i][j]);
}
}
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
85
int sum=0;
printf("\n\n");
for(i=0;i<3;i++) {
for(j=0;j<3;j++) {
newmatrix[j][i]=matrix[i][j];
}
}
for(i=0;i<3;i++) {
for(j=0;j<3;j++) {
printf("%d\t",newmatrix[i][j]);
}
printf("\n");
}
getch();
}
Matrix Multiplication
of n×m and m×p orders →n×p orders matrix
Here the new matrix is of order n ×p. So the outer loop is from i=0 to n-1, second loop is similarly
i=0 to p-1, then an inner loop is for looping till the required sum is obtained. This sum is obtained
from summing column elements of second matrix i.e. p times to the row elements of first matrix. It
doesn’t matter how many row elements are considered because we have earlier declared the
positions of new matrix by first and second loops. Third loop is just for sum. So third loop is from k=0
to m-1. The obtained final matrix is of order n×p.
matrix1[n][m]
matrix2[m][p]
matrix3[n][p]
for i= 0 to n-1 {
for j= 0 to p-1 {
sum=0
for k = 0 to m-1 {
sum=sum+matrix1[i][k]*matrix2[k][j];
}
matrix3[i][j]=sum
}
}
Here i=0 to n-1 (and similarly for j, k) because in array addresses starts from 0 to n-1 for n elements.
By matrix multiplication, as element of new matrix has the row equal to first matrix and column
equal to second matrix and during multiplication there is the sum of elements in such that first
matrix row remains same and column changes in such a way that it equals to second row and its
column constant. This is illustrated above. There first matrix’s row i=constant, second matrix column
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
86
j= constant but first’s column and second’s row changes k=not constant even within loop of j. This is
basic principle of matrix multiplication of any order matrix to any order matrix. This can be simplified
to 3×3 matrix × 3×3 matrix, for this m=n=3.
If inputs are
1 2 34 5 6 7 8 9 and
1 1 11 0 00 0 1 then output is 3 1 49 4 1015 7 16
//MATRIX MULTIPLICATION OF (3*3) AND (3*3) MATRICES
#include<stdio.h>
#include<conio.h>
#define N 3
int main(){
int matrixa[3][3],matrixb[3][3],matrixc[3][3];
int sum=0,i,j,k;
printf("MATRIX MULTIPLICATION OF (3*3) AND (3*3) MATRICES\n\n\n");
printf("\n\n");
for(i=0;i<N;i++) {
for(j=0;j<N;j++) {
printf("Enter matrixa[%d][%d]",i,j);
scanf("%d",&matrixa[i][j]);
}
}
printf("\n\n");
for(i=0;i<N;i++) {
for(j=0;j<N;j++) {
printf("Enter matrixb[%d][%d]",i,j);
scanf("%d",&matrixb[i][j]);
}
}
for(i=0;i<N;i++){
for(j=0;j<N;j++){
sum=0;
for(k=0;k<N;k++){
sum=sum+((matrixa[i][k])*(matrixb[k][j]));
}
matrixc[i][j]=sum;
}
}
printf("\nNew matrix3\n");
for(i=0;i<N;i++) {
for(j=0;j<N;j++) {
printf("%d\t",matrixc[i][j]);
}
printf("\n");
}
getch();
return 1;
}
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
87
More generalization of matrices multiplication
//MATRIX MULTIPLICATION OF (n*m) AND (m*p) MATRICES
#include<stdio.h>
#include<conio.h>
void main(){
int matrix1[100][100],matrix2[100][100],matrix3[100][100],n,m,p,sum,i,j,k;
printf("MATRIX MULTIPLICATION OF (n*m) AND (m*p) MATRICES\n\n\n");
printf("Enter value of n");
scanf("%d",&n);
printf("Enter value of m");
scanf("%d",&m);
printf("Enter value of p");
scanf("%d",&p);
printf("\n\n");
for(i=0;i<n;i++) {
for(j=0;j<m;j++) {
printf("Enter matrix1[%d][%d]",i,j);
scanf("%d",&matrix1[i][j]);
}
}
printf("\n\n");
for(i=0;i<m;i++) {
for(j=0;j<p;j++) {
printf("Enter matrix2[%d][%d]",i,j);
scanf("%d",&matrix2[i][j]);
}
}
for(i=0;i<n;i++){
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
88
for(j=0;j<p;j++){
sum=0;
for(k=0;k<m;k++){
sum=sum+matrix1[i][k]*matrix2[k][j];
}
matrix3[i][j]=sum;
}
}
printf("\nNew matrix3\n");
for(i=0;i<n;i++) {
for(j=0;j<p;j++) {
printf("%d\t",matrix3[i][j]);
}
printf("\n");
}
getch();
}
TASK: A simple program that takes students marks in various subjects, name and roll numbers to
print out ranks, roll numbers and marks (both % and marks) in Descending order.
Hints: Use concept of array in such a way that the marks, percentages, names and roll numbers
while in sorting by descending by any method to marks-percentage corresponds to same change in
every other variable so that name, marks, percentage, roll and rank corresponds to required
particular person.
You may add search by roll or search by few initial words options. For this use string function to
compare the input to available name values stored and in true then print output. For few initial
words firstly find string-length so that comparison is done to only that much length of names stored.
Solution:
//a program taking student's marks and printing out rank without using file handling and just to
array for beginners
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<string.h>
int count=0;
int roll[100];
char name[100][100];
float mark1[100],mark2[100],percent[100];
int main() {
int num;
int number,a;
int temp_count=count;
char dummy[20];
int check;
char checkk[30];
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
89
int j=0,k=0; float temp=0; int temp_i=0;
A:
printf("What do you want to do?\n");
printf("[1]\tto add mark list\n");
printf("[2]\tto look mark list\n");
printf("[3]\tto search by roll\n");
printf("[4]\tto search by name\n");
printf("[5]\tto exit\n");
printf("-------------------------------------------\n");
scanf("%d",&num);
printf("-------------------------------------------\n");
switch(num) {
case 1:
printf("Enter the number of input student's marks?\t");
scanf("%d",&number);
for(a=temp_count;a<(number+temp_count);a++) {
printf("Enter Roll\n");
printf("Enter Name(ENTER Single name)\n");
printf("Enter Marks in Computer\n");
printf("Enter Marks in Maths\n");
scanf("%d",&roll[a]);
scanf("%s",&name[a]);
scanf("%f",&mark1[a]);
scanf("%f",&mark2[a]);
percent[a]=(mark1[a]+mark2[a])/2;
count++;
}
if(getch()) goto A;
case 2:
printf("MARKSHEET OF STUDENTS\t(RANK WISE)\n\n");
printf("\n\n--------------------------------------------------------------\n");
printf("RANK ");
printf("ROLL ");
printf("NAME\t");
printf("Computer ");
printf("Maths ");
printf("PERCENT");
//Sorting begins-descending by bubble method
for(j=1;j<count;j++) {
for(k=1;k<=count-j;k++) {
if(percent[k-1]<percent[k]) {
temp_i=roll[k-1];
roll[k-1]=roll[k];
roll[k]=temp_i;
strcpy(dummy,name[k-1]);
strcpy(name[k-1],name[k]);
strcpy(name[k],dummy);
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
90
temp=mark1[k-1];
mark1[k-1]=mark1[k];
mark1[k]=temp;
temp=mark2[k-1];
mark2[k-1]=mark2[k];
mark2[k]=temp;
temp=percent[k-1];
percent[k-1]=percent[k];
percent[k]=temp;
}
}
}
// Rank List
int i;
for(i=0;i<count;i++) {
printf("%d\t",i+1);
printf("\n%d\t",roll[i]);
printf("%s\t",name[i]);
printf("%f\t",mark1[i]);
printf("%f\t",mark2[i]);
printf("%f\n",percent[i]);
}
if(getch()) goto A;
case 3:
printf("Enter roll number\t");
scanf("%d",&check);
for(i=0;i<count;a++) {
if(roll[i]==check){
printf("MARKSHEET OF STUDENTS\t(RANK WISE)\n\n");
printf("\n\n----------------------------------------------------------------------------------\n");
printf("RANK ");
printf("ROLL ");
printf("NAME\t");
printf("Computer ");
printf("Maths ");
printf("PERCENT\n");
printf("%d\t",i+1);
printf("%d\t",roll[i]);
printf("%s\t",name[i]);
printf("%f\t",mark1[i]);
printf("%f\t",mark2[i]);
printf("%f\n\n",percent[i]);
break;
}
}
if(getch()) goto A;
case 4:
printf("Enter name\t");
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
91
scanf("%s",&checkk);
for(i=0;i<count;a++) {
if(strncmp(name[i],checkk,strlen(checkk))==0){
printf("hello");
printf("MARKSHEET OF STUDENTS\t(RANK WISE)\n\n");
printf("\n\n--------------------------------------------------------------\n");
printf("RANK ");
printf("ROLL ");
printf("NAME\t");
printf("Computer ");
printf("Maths ");
printf("PERCENT\n");
printf("%d\t",i+1);
printf("%d\t",roll[i]);
printf("%s\t",name[i]);
printf("%f\t",mark1[i]);
printf("%f\t",mark2[i]);
printf("%f\n\n\n",percent[i]);
break;
}
}
if(getch()) goto A;
case 5:
printf("THANKS TO YOU AND HOPE YOU TO LOOK SIMILAR USING FIHE HANDLING IN COMING
LESSONS");
if(getch()){
exit(0);
}
}
getch();
return 1;
}
RECURSIVE FUNCTION
It is a method for dividing a problem into smaller units in such a way that each units are similar to
other irrespective of some small changes that can be made change gradually and eventually to al so
that a function is called for required number of times within another function, the last condition of
function to be called or not must be declared for e.g. in factorial
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
92
if(n==1) return (1);
is last condition that terminates the function. A function is repeatedly called to individual thje
problem into parts however a function is called within another function so there is the combination
of results to give a net output.
To calculate number of permutations and combinations using function factorial
For permutation
n[\n!�n − r!
For combination
n]\n!�n − r! r!
#include<stdio.h>
#include<conio.h>
int factorial(int n) {
int fact=1; int i;
for(i=1;i<=n;i++)
fact=fact*i;
return fact;
}
int main() {
int n,r;
printf("n\t");
scanf("%d",&n);
printf("r\t");
scanf("%d",&r);
int f1,f2,f3;
f1=factorial(n);
f2=factorial(n-r);
f3=factorial(r);
int com=f1/(f2*f3);
int per=f1/f2;
printf("The combination is %d",com);
printf("\n The permutation is %d",per);
getch();
return 0;}
Factorial by recursive
#include<stdio.h>
#include<conio.h>
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
93
int factorial(int);
void main() {
int num;
printf("Enter a number\t");
scanf("%d",&num);
printf("The factorial of %d is %d\t",num,factorial(num));
getch();
}
int factorial(int num) {
if(num==1){
return(1);
}
else
{
return(num*factorial(num-1));
}
}
Fibonacci series by recursive
1 1 2 3 5 8 13 21 ……………….
#include<stdio.h>
#include<conio.h>
int fibo(int);
int main() {
int num;
printf("Enter a number\t");
scanf("%d",&num);
printf("The fibonaci \t");
int i;
for(i=0;i<num;i++) {
printf("\t%d",fibo(i+1));
}
getch();
return 1;
}
int fibo(int num) {
if(num==1){
return(1);
}
else if(num==2){
return(1);
}
else
{
return(fibo(num-2)+fibo(num-1));
}
}
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
94
Fibonacci series by recursive
0 1 1 2 3 5 8 13 21 ……………….
#include<stdio.h>
#include<conio.h>
int fibo(int);
int i;
int main() {
int num;
printf("Enter a number\t");
scanf("%d",&num);
printf("The fibonaci \t");
for(i=0;i<num;i++) {
printf("\t%d",fibo(i+1));
}
getch();
return 1;
}
int fibo(int num) {
if(num==1){
return(0);
}
else if(num==2){
return(1);
}
else
{
return(fibo(num-2)+fibo(num-1));
}
}
To calculate power by recursive
#include<stdio.h>
#include<conio.h>
#include<math.h>
#include<stdlib.h>
float power(float x,int n){
if(exp<0) {exit(1);}
else if (n==0) { return (1);}
else return (x*power(x,n-1));
getch();
}
void main() {
float x;
int n;
printf("Enter a number\t");
scanf("%f",&x);
printf("enter power \t");
scanf("%i",&n);
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
95
printf("The answer is %f",power(x,n));
getch();
}
Calculate sum of digits by recursive
#include<stdio.h>
#include<conio.h>
extern suma=0;
int sum(int num){
int i=1,digit=0;
digit=num%10;
suma+=digit;
num/=10;
i++;
if(num>0){
sum(num);
}
return (suma);
}
void main() {
int number;
printf("Enter a number\t");
scanf("%d",&number);
printf("The answer is %d",sum(number));
getch();
}
Armstrong using function
#include<stdio.h>
#include<conio.h>
#include<math.h>
int arms(int num) {
int sum=0;
int digit=0;
do {
digit=num%10;
num=num/10;sum=sum+pow(digit,3);}
while (num>0);
return sum;
}
int main() {
int num;
printf("Enter a number\t");
scanf("%d",&num);
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
96
if(arms(num)==num) {
printf("yes it is armstrong");
}
else printf("not");
getch();
return 1;
}
Armstrong using recursive
#include<stdio.h>
#include<conio.h>
#include<math.h>
int arms(int num) {
int sum=0;//must be inside function arms() so that for each recursive it starts from 0 so it is local
int digit;
printf("the num is %d\n",num);
printf("the sum is %d\n",sum);
if(num==0){
return 0;}
else {
digit=num%10;
num=num/10;
sum=pow(digit,3);
return(sum+arms(num));
}
}
int main() {
int digit;
int total=0;
int a;
int num;
printf("Enter a number\t");
scanf("%d",&num);
if(arms(num)==num) {
printf("yes it is armstrong");
}
else printf("not armstrong");
getch();
return 1;
}
WITHOUT FUNCTION
To check token without using any function
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
97
#include<stdio.h>
#include<conio.h>
int main() {
printf("enter a token:\t");
char b;
scanf("%c",&b); //address '&' is compulsory here
int a=b;
if(a>=48 && a<=57) {
printf("digit");
}
else if(a>=65 && a<=90) {
printf("Ucase");
}
else if(a>=97 && a<=122) {
printf("Lcase");
}
else {
printf("special");
}
getch();
return 0;
}
Calculate power without function
//calculate power
#include<stdio.h>
#include<conio.h>
int main() {
int base;
printf("enter base\t");
scanf("%d",&base);
int power;
printf("enter power\t");
scanf("%d",&power);
int i;
int result=1;;
for(i=1;i<=power;i++){
result=result*base;
}
printf("The answer is %d",result);
getch();
return 0;
}
To reverse a sentence without any function
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
98
Here length of string is calculated by while loop that increments varable length staring from zero
until we read ‘\0’ i.e. the termination of string, while reading each character of string by help of
counter ‘i’ that increase for each loop of while, the value of i starting from zero that measn reading
character of string from character array position zero.
Then i= length-1 cause the no of index in character array ends to length-1. j loop starts from 0 to
length-1 where I continuously increases that is reading position of string increases in the other hand
the character to be signed is done by j in such a way that it fills the last space of rev string
continuing to fill up to first.
Here j=from 0 to length-1 and i=length-1 to 0
So the loop exactly matches to both reading and writing material.
// To reverse a sentence without any function
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main() {
int j;
char rev[100];
int length=0,i=0;
char input[100];
printf("enter a sentence\t");
gets(input);
while (input[i]!='\0')
{
length++; i++;
}
i=length-1;
for(j=0;j<length;j++,i--)
rev[j]=input[i];
rev[j]='\0';
printf("%s",rev);
getch();
return 0;
}
Concatenate two strings without function
// this process is exactly similar to working-mecchanism of strcat() function
Here similar to above process we calculate the length of two strings s1 and s2. The value of i=0 after
the length of s1 is found so that no new variable is needed.
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
99
After that a new variable cona takes all values of s1 one by one by character array method where
i=0to length of l1-1 then in second loop i=length of l1 to less than sum of both length because the
adding process in cona must start from the ending of last loop of i so and this second loop continues
for length of l2 times if count from 1. So the loop starts from l1 to less than (l1+l2). Finally ‘\0’ is
added to make a string.
//Concatenate two strings without function
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main() {
char s1[100],s2[100];
printf("enter a string\t");
gets(s1);
printf("enter another string\t");
gets(s2);
int l1=0,l2=0,i=0;
while (s1[i]!='\0')
{
l1++; i++;
}
i=0;
while (s2[i]!='\0')
{
l2++; i++;
}
char cona[200];
for(i=0;i<l1;i++){
cona[i]=s1[i];
}
int j=0;
for(i=l1;i<(l1+l2);i++,j++)
cona[i]=s2[j];
cona[i]='\0';
printf("%s",cona);
getch();
return 0;
}
Search specific word in given string
Here
for(i=0;i<=(l1-l2);i++){ // the maximum possible condition to find word
this loop starts from zerp to maximum possible to find the word
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
100
for e.g if ‘ef’ is to be find in ‘abcdef’ then five loops must go on each loop’s length equal to length
‘ef’ that is 2
.loops from 0 to 4
For loop0 compare ef to ab
For loop1 compare ef to bc
For loop2 compare ef to cd
For loop3 compare ef to de
For loop4 compare ef to ef
The fifth loops is thus the maximum possible for comparison asd above. In above case ‘ef’ is put at
last to show maximum possible case.
Here number of loops=
Zero to (length of in find string- length o two find string)
i.e. 5 =1+(6-2)
5=5 proved.
Here
for(j=i,k=0;j<(l2+i);j++){
total count is equal to l2, so this loop has number of loops equal to l2 as we know we need to
compare l2 with other so l2 is importantly taken under consider.
Here,
temp[k]=input[j];
k++;
}
for each new loop of I, k startsfrom zero i.e. new comparison starts up to the number of characters
equal to l2 but for each loop of j,k increases trhat in new position of temp[] variable is fulfilled and
after its length becomes equal to length of l2 trhen comparison is done.
The value of j starts from mi because after each comparisons done at last, there is no necessity to
compare for those characters already compared so the value of j starts from previous value of I i.e.
new characters are compared each time and in the other hand the complete comparison for all
characters is possible and termination is also possible.
//searching a character or string in a sentecnce
#include<stdio.h>
#include<conio.h>
#include<string.h>
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
101
int main() {
char input[100],search[100];
printf("enter a sentence\t");
gets(input);
printf("enter specific word\t");
gets(search);
int l1=0,l2=0,i,j,k;
l1=strlen(input);
l2=strlen(search);
char temp[100];
for(i=0;i<=(l1-l2);i++){ // the maximum possible condition to find word
for(j=i,k=0;j<(l2+i);j++){
temp[k]=input[j];
k++;
}
temp[k]='\0'; //compulsory else the blank spaces may make obstacle and
temp is not a complete string as'\0' is last character of all string
if(strcmp(temp,search)==0) {
printf("found");
break;
}
}
getch();
return 0;
}
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
102
A DETAIL OF STRINGS
Finding a sequence of words
// searching whole sentence
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main(){
char check[50]="";
int i=0,j=0,nooffound=0;
char name[100]="NEPAL A HEAVEN";
printf("ENTER");
scanf("%[^\n]",&check);
for(i=0;i<strlen(name);i++) {
if(name[i]==check[j]){
nooffound++;
j++;
continue; //this may be omitted
}
}
if(nooffound==strlen(name)){
printf("all words matched");
}
else if(nooffound==0) printf("no matching with a character even");
else printf("some characters or words are matched but not all");
getch();
}
Finding a sequence of words any
//searching sequential characters
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<stdlib.h>
int main(){
char check[50];
int i,nooffound=0;
char name[100];
int max=0;
int count=0;
int temp=0;
printf("ENTER a sentence\n");
scanf("%[^\n]",&name);
printf("ENTER\n");
scanf("%s",&check);
for(i=0;i<strlen(name);i++) {
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
103
if(name[temp]==check[count]){
printf("I=%d",i);
nooffound++;
if(nooffound>max) {
max=nooffound;
}
count++;
temp++;
}
else {
if(nooffound>max) {
max=nooffound;
}
nooffound=0;
if(count>0) {
count=0;
}
temp++;
}
if(count==strlen(check)) {
count=0;
}
if(nooffound==strlen(name)){
printf("exactly found");
if(getch()) exit(0);
}
}
printf("Not foundexactly");
printf("\n[%d]characters are in sequence",max);
getch();
return 0;
}
Finding a sequence of words (working)
//searching sequential characters
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<stdlib.h>
int main(){
char check[50];
int i,nooffound=0;
int max=0;
int count=0;
int temp=0;
char name[100]="nepal is a hindu country";
printf("ENTER\n");
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
104
scanf("%[^\n]",&check);
for(i=0;i<strlen(name);i++) {
printf("\ncount=[%d]",count);
printf("\ncheck=[%c] and name=[%c]",check[count],name[temp]);
if(name[temp]==check[count]){
if(nooffound>max) {
max=nooffound;
}
nooffound++;
printf("NO OF FOUND%d",nooffound);
count++;
temp++;
}
else {
if(nooffound>max) {
max=nooffound;
}
if(count>0) {
count=0;
}
temp++;
nooffound=0;
}
if(count==strlen(check)) {
count=0;
}
if(nooffound==strlen(check)){
printf("exactly found");
if(getch()) exit(0);
}
}
printf("Not foundexactly");
printf("\n[%d]characters are in sequence",max);
getch();
return 0;
}
Finding a word in a sentence
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<stdlib.h>
int main(){
int i;
int a=-1;
char incheck[50];
char name[50]="My country is Nepal , a heaven";
char check[50]="";
clrscr();
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
105
printf("My country is Nepal , a heaven\n\n");
printf("ENTER A WORD\n");
scanf("%s",check);
for(i=0;i<strlen(name);i++) {
a++;
incheck[a]=name[i];
if((strncmp(incheck,check,(strlen(check)))==0)) {
printf("found\nInput any thing to exit");
if(getch())exit(0);
}
else if(name[i]==' '){
strcpy(incheck,"");
a=-1;
}
}
printf("not found");
getch();
return 0;
}
Finding a word in a sentence (working)
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<stdlib.h>
int main(){
int i;
int a=-1;
char incheck[50];
char name[50]="My country Nepal is heaven";
char check[50]="";
printf("My country Nepal is heaven\n");
printf("ENTER A WORD\n");
scanf("%s",check);
for(i=0;i<strlen(name);i++) {
a++;
incheck[a]=name[i];
printf("\ncheck=[%s] and incheck=[%s]\n",check,incheck);
if((strncmp(incheck,check,(strlen(check)))==0)) {
printf("found\nInput any thing to exit");
if(getch())exit(0);
}
else if(name[i]==' '){
printf("above space");
printf("incheeeeeeeeeeeeeeek=%s\n",incheck);
strcpy(incheck,"");
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
106
a=-1;
}
}
printf("not found");
getch();
return 0;
}
Finding a word in a sentence (input from user)
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<stdlib.h>
int main(){
int i;
int a=-1;
char incheck[50]="";
char name[50]="";
char check[50]="";
printf("Enter A Long Sentence\n");
scanf("%[^\n]",&name);
printf("ENTER A WORD\n");
scanf("%s",&check);
for(i=0;i<strlen(name);i++) {
a++;
incheck[a]=name[i];
if((strncmp(incheck,check,(strlen(check)))==0)) {
printf("found\nInput any thing to exit");
if(getch())exit(0);
}
else if(name[i]==' '){
strcpy(incheck,"");
a=-1;
}
}
printf("not found");
getch();
return (0);
}
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
107
OPERATORS
The numeric values used in any expression or used like -2,3,5.0,10.67,10e-2 are operands but the
signs or symbols used to operate between operands are called operators. Operators are various
types listed below:-
TABLE
Rank Operator Associativity
1 (), [] L to R
2 + (unary), -(unary),++,--,! ,*(indirection) R to L
3 *,%,/ L to R
4 +,- L to R
5 <<,>>(shifts) L to R
6 <,<=,>,>= L to R
7 ==,!= L to R
8 && L to R
9 || L to R
10 ?:(conditional or tertiary) R to L
11 =,*=,/=,%=,+=,-=,&=(assignment operators) R to L
12 . (dot) ,(comma) L to R
The rank list shows the priority of which operators to take execution at first or second …….and
similarly so on. The inner () has highest priority than gradually surrounding ().
Inside the same rank, the table shows direction of associativity - L to R means left to right and R to L
means right to left. This direction shows how the calculation’s execution takes place. If in any
expressionthere is more than on operators of a same rank, then the associativity directs the flow of
execution. The operators directed according to associativity come into execution as an when it is
encounted.
For e.g.
100+20/(3+5)*(6+2)
Here () has 1KLpriority
/,* has 2G=priority
+ has 3@=priority
So at 1KL() must be calculated but there are two (3+5) and (3+2) expressions but as we know () has L
to R associativity, (3+5) must be first calculated and (6+2) second resulting,
=100+20/8*(6+2)
=100+20/8*8
Now we come for 2G=priority /,*
It has also left to right associativity, so
=100+2*8 // 20/8 gives 2 as it is integer division (is that takes operates between 2 integer
operands) that truncates decimal part
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
108
=100+16
Now + is operated which has 3@=priority,
=116
Few more examples,
20%8*30(L to R associativity)
= 4*30
= 120
HOW ERRORS MAY OCCUR?
ERROR CALCULATION
3.5+12%6*3
=3.5+12%18
=3.5+12
=15.5
Here %,* has L R associativity but in our calculation we didin’t consider it and we did R to L
asscociativity knowingly or unknowingly, this is our mistake.
In numeric calculations, one mistake is sufficient to bring wrong answer.
CORRECT CALCULATION
3.5+12%6*3
=3.5+0*3
=3.5+0
=3.5
Comparing the underlined parts of these two calculations we see that one gives 12 but another 0,
this shows the actual difference which occurred due to incorrect associativity. Hence the above two
examples illustrates the vast differences due to small errors.
For leap year
A leap year is a year if it is divisible by 4 but not by 100, except that years divisible by 400 are leap
years.
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
109
if((year%4==0 && year%100!=0) || year%400==0) printf("leap year");
else printf("Not leap year");
a%b; here % is modulo division that gives remainder when a is divided by b, but a and b must be int
type as % cannot accept float datas.
Let us give year=20 then
if((20%4==0 && 20%10!=0) || 20%400==0)
Here the inner () has 1KL priority. Inside this inner parenthesis (), % has 1KL priority but there are two
% signs so by L-R associativity of %we get
�1KL step =if((0==0 && 20%10!=0) || 20%400==0)
�2G= step =if((0==0 && 0!=0) || 20%400==0)
Now, ==, != has priority with L-R associativity
�3@= step =if((True && 0!=0) || 20%400==0)
�4L` step =if((True && False) || 20%400==0)
�5L` step =if((False) || 20%400==0)
Because True and False gives False refer Truth Table
=if(False || 20%400==0)
In above case, we did all calculations of inner () so outer is now to be taken consideration.
Here, % has 1KL priority ,== 2G= priority and || 3@= priority.
So,
�6L` step =if(False || 0==0)
�7L` step =if(False || True)
�8L` step =if(True)
So 20 is the leap year, we did it in 8 steps.
POST/PRE INCREMENT/DECREMENT OPERATORS
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
110
Prefix(before the variable: ++a) and postfix(after the variable: a++)
++n increments n before its value is used
n++ increments n after its value has been used.
LINE POST PRE
1 x=5; //x=5 x=5; //x=5
2 x++; //x=5 ++x; //x=6
3 x; //x=6 x; //x=6
In 2G= line of pre-, first x is incremented by 1 i.e. x becomes 6 and this value of x is used however in 2G= line of post- the value of x=5 is used then only after its one time use, the x is incremented by 1
i.e. x becomes now 6 which is shown by line 3 of post, but x becomes 6 already from line 2 of pre-.
In post
a++ or a- -
In this particular line value of ‘a’ is original’s but the next time or may be on next line the value is
initially incremented or decremented before than under-consideration of ‘a’ or statements or
expressions including ‘a’ or including its parts.
FOR-BLOCK’S EXECUTION FLOW
For block
Initialize a value (let say i)
Check condition (if true then follow statement else terminate for-loop)
Statement
Statement
Statement
.
.
.
.
.
Update value controlling for loop(here it is i)
(actually there are two controlling methods one is counter-controlling and the next is sentinel-
controlling loop, counter controlling is definite but in sentinel it is not definite and the termination is
determined by some undefinite terms like may be user’s input)
Illustration of pre/post operators in detail
for(i=1;i<+5;i++)
print("%u",i);
and
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
111
for(i=1;i<=5;++i)
print("%u",i); // here u means unsigned int
These two for-expressions use post and pre increments of i but does not hamper the statements
inside, it holds. It is because both post and pre are declared in one line and its use like printing i is
declared in next line or a next statement, so the output are same. But let us look an example:-
for(i=1;i<+5;a=i++){
print("%d",i);
print("%d",a);
}
and
for(i=1;i<+5;a=++i){
print("%d",i);
print("%d",a);
}
Here in a=i++, ++ has first priority than = so, first is 1++, which means that i has 1 value but in next
statement that using i, there i will be 2, but here a=i++ takes the instant value of i in the line i.e.
before increment as it is for only the next statement using i, where i will be incremented. So a=1 as it
is, but in second example, ‘a’ will be 2.
We are not going to deal with these post/pre fix operators in detail here however we will clear them
when we encounter them in coming parts.
ASSIGNMENT OPERATORS
i=i+2=5;
here = has R to L so, i+2=5 �1KL step
i=i+2 �2G= step
but from 1KL step i+2=5
so, from �2G= step i=5
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
112
OUTPUTS
NOTE: Before looking outputs, please once more revise operators-section.
HINTS TO pu2008fall 3a)
x=++x+y;//++x has first priority so,++3+4=4+4=8
z*=(x+y) //z=z*(x+y)
3b)
#include<conio.h>
#include<stdio.h>
void main() {
int x=0,i=0;
for(i=1;i<10;++i)
{
if(i%2==1)
x+=i;
else
{
x--;
printf("%d",x);
break;
}
}
printf("\nx=%d",x);
getch();
}
i Condition
i%2==1
Result Operations Remarks
1 1%2==1 True x=x+i
X=0+1
2 2%2 False x- - X=1—
print 0
Here in the line x--, the value of x is original that is 1, but in the following line print x, the value of x is
0.
Now the ‘break;’ statement breaks the for-loop and the value of “x=0” is printed.
You can get soft copy of this book @ www.scribd.com/dpalikhe.
PU 2006 SPRING2 a)
#include<stdio.h>
#include<conio.h>
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
113
int a = 100, b = 200;
int funct1 (int c);
main ( )
{
int count, c;
for (count = 1; count <= 5; ++count) {
c= 4 * count * count;
printf ( " %d ", funct1 ( c ) );
}
getch();
}
funct1 ( int x)
{
int c;
c = (x < 50) ? (a + x) : (b - x) ;
return( c );
}
We can use table under appropriate column names to make easier to calculation like below:
count c=4*count*count condition x<50 result operations
1 c=4*1*1=4 4<50 TRUE c=a+x=100+4=104
print 104
2 c=4*2*2=16 16<50 TRUE c=a+x=100+16=116
print 116
3 c=4*3*3=36 36<50 TRUE c=a+x=100+36=136
print 136
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
114
4 c=4*4*4=64 64<50 FALSE c=b-x=200-64=136
print 136
5 c=4*5*5=100 100<50 FALSE c=b-x=200-100=100
print 100
2 b)
#include<stdio.h>
#include<conio.h>
main( )
{
int i=0,x=0;
for(i=1;i<10;++i )
{
if (i%2==1)
x+=i;
else
x--;
printf("%d", x);
continue;
}
printf ( " \nx = %d ", x );
getch();
}
i Condition
i%2==1
Result Calculation first Calculation second
1 1%2==1 true x=x+i
x=0+1 i.e. 1
print 1
continue loop
// continue; statement simply continues the for-loop in this case however it may make greater
difference for others where the statements below continue-statement but inside for-loop are just
aborted.
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
115
2 2%2==1 false x--=1-- print 0
3 3%2==1 true x=x+i=0+3=3 print 3
4 4%2==1 false x--=3-- print 2
5 5%2==1 true x=x+i=2+5=7 print 7
6 2%2==1 false x--=7-- print 6
7 7%2==1 true x=x+i=6+7=13 print 13
8 2%2==1 false x--=13-- print 12
9 3%2==1 true x=x+i=12+9=21 print 21
2) c
#include <stdio.h>
#include<conio.h>
#define ROWS 3
# define COLUMNS 4
int z [ROWS][COLUMNS] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
main ( )
{
int a, b, c;
for ( a = 0; a < ROWS; ++a)
{
c = 999;
for ( b = 0; b < COLUMNS; ++b )
if ( z[a][b] < c ) c = z[a][b];
printf ( " %d ", c );
}
getch();
}
While checking 999 with all numbers, no new number is > than 999 so c is 999 and 999 is thus
printed.
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
116
PU2009SPRING
2 b) important
#include<stdio.h>
#include<conio.h>
void main()
{
int sum,a,k,j;
sum=0;
a=12345;
while (a!=0)
{
j=a%10;
printf("%d",j);
if(j%2==0)
{
sum=sum+j;
}
a=a/10;
}
printf("sum=%d",sum);
getch();
}
The exact question inquestion paper is mistake as while(a!=0) while(12345!=0) never becomes
false and no termination so we keep a=a/10 and the purpose of program seems that it sums all even
digits of ‘a’ and prints sum.
Condition
(a!=0)
Result (T/F) Computations
(j=a%10)
and print j
Condition
(j%2==0)
Result Calculation Valve of a
(a=a/10)
12345!=0 T j=12345%10=5
print 5
5%2==0 False - a=12345/
10=1234
1234!=0 T j=1234%10=4
print 4
4%2==0 True sum=0+4=4 a=1234/1
0=123
123!=0 T j=123%10=3
print 3
3%2==0 False - a=123/10
=12
12!=0 T j=12%10=2
print 2
2%2==0 True sum=4+2=6 a=12/10=
1
1!=0 T j=1%10=1
1%2==0 False - a=1/10=0
0!=0 False (------end of while-loop------)
print sum =6
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
117
3 a) very important
#include<stdio.h>
#include<conio.h>
void main()
{
int x=0, i=0;
for (i=1; i<10; i++){
if (i%2==0)
x += i;
else
{
x -- ;
printf ("%d\t", x);
}
}
printf("\nx=%d", ++x);
getch();
}
i Condition
(i%2==0)
Result Calculation Update i of for-
loop
(i++)
1 1%2==0 False x=0- -
print -1
i=1++
(see how 1++
changes to 2 in
next statement)
2 2%2==0 T x=x+i=-1+2=1 i=2++
3 3%2==0 F x=1- -
print 0
i=3++
4 4%2==0 T x=x+i=0+4=4
i=4++
5 5%2==0 F x=4--
print 3
i=5++
6 6%2==0 T x=x+i=3+6=9
i=6++
7 7%2==0 F x=9--
print 8
i=7++
8 8%2==0 T x=x+i=8+8=16
i=8++
9 9%2==0 F x=16--
print 15
i=9++
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
118
i=10 but i<10 is only permissible for for-loop, so loop terminates.
print x=16 //++15 is 16
PU2011FALL
3 a)
#include<stdio.h>
#include<conio.h>
void main()
{
int i=5,j=4,k=9;
i=(i+k)/3+k%(j+i)+j*k%i/2;
printf("%d",i);
getch();
}
i=(5+9)/3+9%(4+5)+4*9%5/2
here () has highest priority and follows L to R associativity. So,
i=14/3+9%(4+5)+4*9%5/2 (1�� step)
i=14/3+9%9+4*9%5/2 (2�� !.a
now, %,*,/ has high precedence with L to R associativity, so
i=4+9%9+4*9%5/2 �3�� !.a
i=4+0+4*9%5/2 �4�6 !.a
i=4+0+36%5/2 (5�6 !.a
i=4+0+1/2 (6�6 !.a
i=4+0+0 (7�6 !.a
now + has high precendence than =,so
i=4+0 (8�6 !.a
i=4 (9�6 !.a
now the value of i is 4, print i //4 prints out
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
119
3 b)
#include<stdio.h>
#include<conio.h>
void main()
{
int x=16,y=18,z;
y+=x++;
z=++x+y++;
x=x+y+z--;
printf("\n x=%d\ny=%d\nz=%d",x,y,z);
getch();
}
y+=x++;
her, ++ has high precedence than assignment operator +=. So, at first x++ is calculated. 16++ means x
has 16 value o the line but 17 on next line.
So, y=y+16++
=18+16++
=34
In next line, ++ has R to L associativity so , at first y++ is calculated, then ++x, then + is done and
finally assigned to z.
z=++x+34++ (1�� step)
=++17+34++ (2�� step)
=18+34++
=52
z=52
In 3�� line
x=18+35+52--
=18+35+52
=105
Line x y z
Value
before
calculation
of line
Value after
calculation
of line
Value
before
calculation
of line
Value after
calculation of line
Value before
calculation of
line
Value after
calculation
of line
1 16 16++ 18 18+16++=18+16=34 Not
defined(garbage
value)
Not
defined( it
gives error
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
120
like no
value
declared
when
printed)
2 17 ++17=18 34 34++ - 52
3 15 105 35 35 52 52--
4 105 105 35 35 51 51
Print x=105, y=35, z=51
Hints: Read each line of statement separately and make a general table like above which includes
values of x,y,z in various lines and sub-divide the values into two parts- one stores value before the
calculation of the line is done and the next stores value after the calculation of the line has been
done. In order to do calculation for a particular line we need to take the value from “value before
calculation of line” and do our all calculations of the line. In calculation of a line, a value may go
under various sort of changes it doesn’t matter to us and we have to remember a thing that a
variable has only one address so a value changed from any where or at any time automatically
changes the value where its old values are erased without any delay so one by one step method
makes everything clear.
For e.g. a=5
a++,b=a- -
Value of a before calculation, a=5
In calculation, 5++ but later changed to 6 on next using of ‘a’
Then after calculation a- -means 6- - on next line it is a=5 sometime a variable’s value may be
changed more than 1 time abruptly within a single statement or line.
Let’s return to our lesson, after the calculation we need to fill the “value after calculation of line”
with the new arising values but we should be careful that I post operators write the symbol++ or - -
as it is so we change it into its real form by initialization ofnext line.
For e.g. the x is 16++ of line 1 changes to x is 17 in line2. So this table-work must go side-by-side with
the line-by-line calculation.
PU2009FALL 3 a)
#include<stdio.h>
#include<conio.h>
void main()
{
int m = 100, n = 50;
printf ("%d\n", 10+m++); //1^st line
printf ("%d\n", 10+n--); //2^nd line
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
121
printf ("%d\n", 10+--n); //3^rd line
getch();
}
1�� line 10+#77
10+10077 // 100 for this line and 101 for next
print 110
2�� line 10+,55
10+5055 // 50 for this line and 49 for next
print 60
3�� line 10+55n
10+5548
print 58
Line number Value of m Value of n Printing on
line Before After Before After
1 100 10077 50 50 10+
10077=110
2 101 101 50 5055 1+
5055=60
3 101 101 49 5549
=48
10+48=58
Neglect unnecessary values in the table for the case on line 2 and 3 values of ‘m’ and value of ‘n’ on
line 1. But in long statements, this unnecessary tabulation may give a great relief to us.
3 b)
#include<stdio.h>
#include<conio.h>
void main()
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
122
{
char string [ ] = "HELLO WORLD";
int m;
for (m=0;string[m]!='\0';m++)
{
if (m%2==0) printf ("%c",string[m]);
}
getch();
}
m Condition of for-
loop
string[m]!= ‘\0’
Condition
(m%2==0)
Result Calculation Update of m
(m++)
0 True 0%2==0 T print H 0++
1 T 1%2==0 F - 1++
2 T 2%2==0 T print L 2++
3 T 3%2==0 F - 3++
4 T 4%2==0 T print O 4++
5 T 5%2==0 F - 5++
6 T 6%2==0 T print W 6++
7 T 7%2==0 F - 7++
8 T 8%2==0 T print R 8++
9 T 9%2==0 F - 9++
10 T 10%2==0 T print D 10++
11 F (-------for-loop terminates--------)
Here we are checking the condition of for-loop in order to demonstrate how character array works.
OUTPUT: HLOWRD
PU2007FALL 2 a)
#include<stdio.h>
#include<conio.h>
void main()
{
int x =10,a =10,b=0, y =11, z =12;
x+=++a-b++; // line
x-=++z%--b; // line
x*=++a+b++*z-- ; // line
printf("a=%d\tb=%d\tx=%d\ty=%d\tz=%d",a,b,x,y,z);
getch();
}
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
123
Without assigning a variable a value and using it makes error but it doesn’t hamper for assignment
so we have supposed b=0 in the question. But even after that something divide by b (zero) gives
complilation error so the program gac’t run. However here we are going to rewad the process of
calculation by assuming error as correct.
line ++ has priority and R L associativity
x=x+(++a-b++) (first step)
x+(++10)-0 ( second step)
x+11-0
x=x+11 ( step)
x=10+11 =21
line 2
x-=++z%- -b
x-=++z%- -1 (first step)
x-=++12%0// here int divide by zero may give error
x- =13%0 (second step)
x-=13 ( third step)
x=21-13=8
write the actual values instead of variable only when the particular calculation is to be done else it
will confuse you.
Line 3
x*=++a+b++*z- -
x*=++a+b++*13- - (first step)
x*=++a+0++*13
x*=++a+0*13 ( second step)
x*=++11+0*13
x*=12+0*13 (third step)
x*=12+0 ( fourthstep)
x*=12 ( fifthstep)
x=x*12 ( sixth step)
x=8*12=96
Line x y z a B
before after before after before after before after before after
1 10 21 11 11 12 12 10 ++10=11 0 0++
2 21 8 11 11 12 13 11 11 1 0
3 8 96 11 11 13 11 ++11=12 0 0++
Here, now on the particular line after execution
x=96, y=11 (never changed in any line), z=(i.e. 13 on line but changes 12 on line which is not defined
in program), a=11,b= (i.e. 0 on line but 1 on coming line).
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
124
About answer of c; it is undeclared variable so it gives error as undeclared variable when access ‘c’ in
program.
2 b)
#include<stdio.h>
#include<conio.h>
void main()
{
int k, a;
a = 10;
for(k=0;k<10;k++)
{
if(k%2==0)
a = a+k;
else
a = a-1;
printf("a=%d\n",a);
}
printf("\n the value of a = %d", a);
getch();
}
k Condition
(K%2==0)
Result Calculation print a
0 0%2==0 T a=a+k=10+0=10 print 10
1 1%2==0 F a=a-1=10-1=9 print 9
2 2%2==0 T a=a+k=9+2=11 print 11
3 3%2==0 F a=a-1=11-1=10 print 10
4 4%2==0 T a=a+k=10+4=14 print 14
5 5%2==0 F a=a-1=14-1=13 print 13
6 6%2==0 T a=a+k=13+6=19 print 19
7 7%2==0 F a=a-1=19-1=18 print 18
8 8%2==0 T a=a+k=18+8=26 print 26
9 9%2==0 F a=a-1=26-1=25 print 25
print a=25
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
125
2012FALL 2b i) Very important
#include<stdio.h>
#include<conio.h>
void main()
{
int x=10,y=20,z=5,i;
i=x*(++y+z++)%3+y/x*2-5;
x+=z;
y-=z;
x--;
z+=10;
z--;
printf("x=%d\ny=%d\nz=%d",x,y,z);
printf("\ni=%d",i);
getch();
}
1�� line () has high priority in which ++ has 1�� play with R to L associativity then outside () for
*,/,% with L to R associativity then +,- eith L to R associativity,
Here steps are written when actual calculation is done excluding actual value assignment.
1�� line
i=x*(++y+z++)%3+y/x*2-5
= x*(++y+5++)%3+y/x*2-5 1��step
=x*(++20+5)%3+y/x*2-5
= x*(21+5)%3+y/x*2-5 2��step
= x*26%3+y/x*2-5 3��step
= 10*26%3+y/x*2-5
=260%3+y/x*2-5 4�6step
=2+21/10*2-5 5�6step
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
Note:- what happen if these way z/x instead earlier said that a post operator’s actual value comes
into play either in next line if there is no further use of that variable in that line or if there is use in
same line that the actual and final value must come into pla
must write 6 for the case.
=2+2*2-5 6�6step
=2+4-5 7�6step
=6-5 8�6step
=1 9�6step
So i =1
TABLE
Line x
Before
calculation of
line
After
calculation of
line
1 10 10
2 10 16
3 16 16
4 16 16- -
5 15 15
6 15 15
7 10 No any
calculation
2�� line x+=z i.e. x=x+z=10+6=16
3�� line y-=z i.e. y=y-z=21-6=15
4�6 line x- - i.e. 16- -
5�6 line z+=10 i.e. z=z+10=6+10=16
6�6 line z- - i.e. 16- -
Print x= 15 y=15 z=15 i=1
PROGRAMMING ANALYSIS IN C
happen if these way z/x instead earlier said that a post operator’s actual value comes
into play either in next line if there is no further use of that variable in that line or if there is use in
same line that the actual and final value must come into play so instead of 5++ in Table for z, we
y z
calculation of
Before
calculation of
line
After
calculation of
line
Before
calculation of
line
20 ++20=21 5
21 21 6
21 21-6=15 6
15 15 6
15 15 6
15 15 16
calculation
15 No any
calculation
15
line x+=z i.e. x=x+z=10+6=16
6=15
line z+=10 i.e. z=z+10=6+10=16
126
happen if these way z/x instead earlier said that a post operator’s actual value comes
into play either in next line if there is no further use of that variable in that line or if there is use in
y so instead of 5++ in Table for z, we
calculation of
After
calculation of
line
5++
6
6
6
16
16- -
No any
calculation
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
127
PU 2011 SPRING Ternary Operator’s nested use
#include<stdio.h>
#include<conio.h>
void main() {
int i=-4,j,num=0;
j=(num>5?(num<=10?100:20):500);
printf("%d",num);
printf("%d",j);
getch();
}
Output:
0500
Here inner () is operated at first in ternary operator
num<=10
0<=10 (True)
So, j=(num>5?100:500)
As the inner condition condition becomes true so 100 is taken but remember it is not assigned to
num, num still has 0 value.
Now, num>5
0>5 (False)
So, j=500. While printing num=0 and j=500 so 0500is printed out.
PU2006FALL 3
Print out combinations of 1, 2, 3 using for-loop
#include<stdio.h>
#include<conio.h>
void main(){
int i,j,k,num,flag=1;
for(i=1;i<=3;i++) {
flag=1;
num=i;
for(j=1;j<=3;j++) {
if(j==i) continue;
num=num*10+j;
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
128
for(k=1;k<=3;k++) {
if(k==i || k==j) continue;
num=num*10+k;
printf("%d\n",num);
flag=0; break;
}
if(flag==0) break;
}
}
getch();
}
PUFALL2003
2 b)
Read temperature of a month of 10 cities and print out average of ten cities using array and for-loop
#include<stdio.h>
#include<conio.h>
void main(){
int i,j,sum=0;
char city[10][25];
int tmp[10][30];
for(i=0;i<10;i++) {
printf("Enter name of city");
scanf("%s",&city[i]);
}
for(i=0;i<10;i++) {
for(j=0;j<30;j++) {
printf("Enter temperature of %s for %d day",city[i],j+1);
scanf("%d",&tmp[i][j]);
}
}
for(i=0;i<10;i++) {
sum=0; //for each value of ‘i’ i.e. for eachnew city sum must starts from zero
for(j=0;j<30;j++) {
sum=sum+tmp[i][j];
}
printf("average of %s city is %d",city[i],sum/30);
}
getch();
}
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
129
SECOND WAY OF SOLVING
#include<stdio.h>
#include<conio.h>
void main(){
int i,j,avg[10];
char city[10][25];
int tmp[10][30];
for(i=0;i<10;i++) {
printf("Enter name of city");
scanf("%s",&city[i]);
}
for(i=0;i<10;i++) {
avg[i]=0;
for(j=0;j<30;j++) {
printf("Enter temperature of %s for %d day",city[i],j+1);
scanf("%d",&tmp[i][j]);
avg[i]=avg[i]+(tmp[i][j]/30);
}
}
for(i=0;i<10;i++) {
printf("average of %s city is %d",city[i],avg[i]);
}
getch();
}
Here average is calculated directly as the sum of such values which has got ratio (or fraction) to the
total number of species i.e. 30
For e.g, if there are data 10, 50,60,5 then its average can be calculated as
Avg=(10+50+60+5)/4=31.25 (in I CASE)
But in second case it is calculated as
Avg=10
4+50
4+60
4+5
4=31.25
As here 4 represent the total quantity of data, formerly in program it was 30
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
130
POINTERS
Pointer declaration in arrays
1-D array:
Declaration *a[3]={1,2,3};
To access *a[i]; such that i running from 0 to 2
2-D array:
Declaration *(a+i)+j; or (*a)[]; or *a[][];
// or to pass value by address or pointer
To access *(*(a+i)+j); or *(a[i]+j); // to use value
int x,*p,y;
x=5;
p=&x;
y=*p; //accessing x through p-pointer variable
*p=50; //accessing 50 to x through pointer p
In 1-D,
*(x+i) represents 1-D array x[i] and *(*(a+i)+j) represents a[i][j]
In p[i][j]
p pointer to 1�� row
p+i pointer to ��6 row
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
131
*(p+i) pointer to 1�� element in ��6row
*(p+i)+j pointer to b�6 element(column) in ��6row
*(*(p+i)+j) value of ��6 row and b�6 column
PROGRAM DEMONSTRATING POINTER VARIABLE’S RESEMBLENSE WITH SPECIAL ARRAY i.e.
CHARACTER ARRAY (STRING)
N E P A L \0
Address 54 59
(name) (ptr)
#include<stdio.h>
#include<conio.h>
void main(){
char *name;
char *ptr;
name="NEPAL";
ptr=name;
while(*ptr!='\0') {
printf("%c is stored at address %d\n",*ptr,ptr);
ptr++;
}
printf("\n length=%d\n",ptr-name);
getch();
}
DESCRIPTION
The pointer ptr points the name variable so ptr gives address of each characters of name variable i.e.
“NEPAL” and similarly *ptr access each characters.
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
132
After while termination, the ptr has gained one more succeeding address after “L” of NEPAL i.e. of
“\0” so its subtraction with name which has address of 1��character of name variable i.e. “N” of
“NEPAL”gives length of “NEPAL”.
USING VOID TYPE POINTER AS REQUIRED
void* v; //a void pointer
int a =50;
v=&a;
printf("%d",*(int*)v); //prints 50
//here '(int*)v' declare v as int type pointer
Demonstrating the 2D pointers in 2d array
#include<stdio.h>
#include<conio.h>
int main() {
int*matrix[2][2];
int i,j;
printf("first matrix");
for(i=0;i<2;i++)
for(j=0;j<2;j++) scanf("%d",*(matrix+i)+j);
//printf("\n%d",*(matrixa+i)+j);
for(i=0;i<2;i++)
for(j=0;j<2;j++)
printf("output:%d",*(*(matrix+i)+j));
getch();
return 1;
}
CALL BY ADDRESS/PASS BY POINTER
int x=5;
cahnge(&x); // call by reference or address
printf("%d",x); // x=15
change(int* p) {
/*here in int* p, * has R-L associativity.
So, p is a variable of type pointer as p has priority than * and of type int.
Here the input as argument is taken by p not *p, *p shows the p is pointer type alse we can say int*
is one thing and p another, int* showing type of value taken by p and type of p-variable i.e. int and
(pointer) respectively.
*/
*p=*p+10;
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
133
}
POINTERS IN STRUCTURE
struct student *ss;
to assign or access value we use ‘(*ss).id’ //* has R-L associativity but we need L-R associativity so ()
used
or we use ‘ss->id’
PASSING WHOLE STRUCTURE TO FUNCTION
function_name(struct_name obj); //calling
and we can directly accesss elements of structure inside function
PU 2006 SPRING 5a
Meaning of some pointer expressions:
Qn. Explain the meaning of the following declaration:
i) int *p;
ii) int *p[10];
iii) int (*p)[10];
iv) int *p(void);
v) int (*p)(char*a);
Answer:
Meaning of i):
It simply declares a variable ‘p’ which is pointer type that means it stores address of some other
variable but this pointer type is int so , it stores only address of int type some other variable.
Meaning of ii) and iii):
*has lower precedence than [], so *p[10] declare p has an array of 10 pointers but (*p)[10]
declare p as an pointer to an array of 10 elements.
{*has R-L}and{(),[] has L-R}
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
134
Meaning of iv):
POINTER TO FUNCTIONS:
iv) int *p(void); declare p as a function (taking void means nothing as argument) returning a
pointer type int value.
It is because () has high priority and L R associativity i.e. p(void) p is a function wioth no
argument and similarly * has R to L associatrivity in addition to 2�� priority so
int*p(void) ;
is a function returning pointer type.
Meaning of v):
int (*p)(char*a);
The 1�� priority () has L to R associativity. So, (*p) is taken 1�� than (char*a) i.e. p is a
pointer to a function taking argument as pointer type vartiable-a and this function returns
int value.
2003 fall 4 a) Write a program with user defined function using pointers to convert all the upper-
case letters to lower-case and vice versa in a string given by the user.
For example: The C pRogramming.
tHE c PrOGRAMMING.
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main() {
void converter(char*);
char string[50];
printf("enter a string\t");
scanf("%[^\n]",&string);
converter(&string);
getch();
return 0;
}
void converter(char* string){
int i;
for(i=0;i<strlen(string);i++){
int a=string[i];
if(a>=65 && a<=90) { // if we look the ASCII value table this range is for Upper case
a=a+32; // the ASCII value difference betweenlower and upper
is32
}
else if(a>=97 && a<=122) { // similarly this range is for Lower case
a=a-32;
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
135
}
printf("%c",a);
}
}
SOME CONCEPTUAL TERMS
RETURNING MULTIPLE VALUES BY FUNCTION
Show how pointers can be used to return more than one values from a function
(PU2003FALL4 a)]
A function is a block that takes arguments (char, int, float of normal type or pointer type) and does
either some sort of calculations or other processes and may either return a value or return no value
as a direct visible output. So realizing in a direct method or by just using simple ordinary variables, a
function can return at most one value, but by using pointer variables, a function can return multiple
values. These output parameters are obtained by &(address operator) and indirection operator(*).
For e.g.
#include<stdio.h>
#include<conio.h>
void calculation(int x, int y, int* sum, int* sub) {
*sum=x+y;
*sub=x-y;
}
void main() {
int x=5, y=2, a, s;
calculation(x,y,&a,&s);
printf("Sum=%d\t diff=%d",a,s);
getch();
}
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
136
Here as argument two pointer variables are passed in addition to two simple variables. The sum and
diff is assigned to address of ‘a’ and‘s’ or to pointer variable’s pointing address. Now from the main
method these values are accessed. So the function does calculations and stores values in addresses
by help of pointers.
A function directly returns at most only one variable but can choose what value to be returned
among many depending upon conditions- meeting.
PROGRAM DOCUMENTATION
It means remarkations used to give information or declaration of some lines. Two types-single line
and multiline denoted by //…….and /*………*/. This documentation increases the readability sand in
execution of program, these statements arte left and the flow of execution rejects it and directly
goes to next line so it doesn’t hamper the speed of execution of program. So it is advantageous.
Documentation makes easy to understand a program even for beginning users and also to
programmer himself if for a big program, he might lose concentration after long programming or
recovering the program after a long time.
IMPORTANT CASTING MECHANISM
#include<stdio.h>
#include<conio.h>
void main() {
int a=20,b=6;
float r1,r2;
r1=a/b;
printf("%f",r1);//3.000000
r2=(float)a/b;
printf("\n%f",r2);//3.333333
printf("\n%f",(float)(a/b));//3.000000
getch();
}
Here on first printing float is in top hierarchy than int so int value 3(because 20/6=3 in int integer
division)is converted into float by ‘r1=a/b;’ statement, but in second printing the ‘a’ is converted into
float by ‘=(float)a/b;’ and here () has precedence than / and the result is in float type, however in
third printing ‘(float)(a/b)’, first up all a/b is done which is 3 then only it is changed into float so
printing 3.00000.
VARIABLES
Automatic variables are those local variables (variables accessible within only a specified block)
declared inside functions so that it is only accessible within function, it make up its own new address
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
137
so that it does not alter the variable of main method even if main method has the same name
variable and at last, these variables are generated only after function is called and their lifetime is
limited until the end of execution of the same function for the same particular call of function i.e.
when we call a function for a number of times then the local variable are evolved and terminated for
the same number of times, and each time creating new space, new value (may be some
initialization) where old values have no existence.
But if we want to use the old values of local variables then static type local variables must be
declared, i.e. in static type local variables within between many calls of a same function, the value of
a variable remains still in the sense that it exits but, changes in the sense that it may not hold a value
for the all time in a specified position i.e. in automatic variable at initialization a variable holds a
same value for all calls but this mightn’t be in static. Here the variable is generated when a first call is
given to function and it only terminates on whole execution of program.
Global variables are accessible, changeable and assignable from any part of a program- main method
or any sub-module, module, block, etc.
CALL BY VALUE VS CALL BY REFERENCE
What actually is a function? A function is a block that does some operation. It may do two types of
operation and by two different ways. One operation sis the internal operation which plays role for
inner calculations and the next operation adds some feature in addition to former operation i.e. the
operation is visible to where the function is called or the function returns some value. This value
returned is very much co-related to the way by which the function is operated and we know a
function is operated by two ways- one is by passing some values as input in order to process it or
operate it whereas the other is passing no value at all. But now, we are concerned with methods of
passing values and memory space.
In call by value, the actual arguments we pass in function are copied to some local variables of the
function. As we know local variables specify their own addresses or locations so if we now make
some changes to the variable then we make change for local variable not for the real variables
passed from main method.
int a=5,b=2;
sum(a,b);
printf("x=%dand y=%d",x,y);
void sum(x,y) {
int sum=x+y;
}
Here 5 and 2 are copied to the function and hence the local variables x and y store them but they
are not accessible from outside (main method).
int a=5;
change(a);
printf("%d",a); //gives output 5 instead of 0
void change(a){
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
138
a=0;
}
Now look here ‘a’ declared in function is different than declared in main method as we see that the
print of ‘a’ in main method even after function call shows that a=5 still, this shows that the address
of a, b in function is different than address of a, b in main method.
Now call by address or reference is just oppose of what we have gone through. In call by address,
the value is changed by any sort of changes either in function or in main method as in both cases
there is only one value with only one address for a variable.
A Simple program demonstrating structure: It takes data and print info of
whose address is “pokhara”.
A Simple program demonstrating structure:
It takes data and print info of whose address is “pokhara”
#include<stdio.h>
#include<conio.h>
#include<string.h>
struct employee {
char name[40];
char address[30];
int tel;
int salary;
struct yrofjoin {
int y;
} year;
}e1[100];
void main(){
int i;
int n;
printf("number of data");
scanf("%d",&n);
for(i=0;i<n;i++){
printf("Name\t");
scanf("%s",e1[i].name);
printf("Address\t");
scanf("%s",e1[i].address);
printf("Telephone\t");
scanf("%d",&e1[i].tel);
printf("Salary\t");
scanf("%d",&e1[i].salary);
printf("Year of Join\t");
scanf("%d",&e1[i].year.y);
}
for(i=0;i<n;i++){
if(strcmp(e1[i].address,"pokhara")==0) {
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
139
printf("\n the info of persons whose address is pokhara are");
printf("\n\t%s\t%s\t%d\t%d\t%d\n",e1[i].name,e1[i].address,e1[i].tel,e1[i].salary,e1[i].year.y);
}
}
getch();
}
FILE HANDLING
File pointer vs std
fscanf(stdin,"%d",&roll);
This is the next format of 'fscanf', here it will just take input from screen as stdin means standard
input i.e. input from screen but does nothing to file similar this 'stdout' by 'fprintf' prints data not
from file but from program to screen i.e. std means reading from input of user i.e. from screen to
program or printing to screen from program.
printf("Enter Phone number\n");
fscanf(stdin,"%s",&phone); // it takes input from screen to program
fprintf(fp1a," %s %s %d",name,add,phone); //this prints data from program to file
defined by ‘fp1a’
fscanf(fp1a," %s %s %d",name,add,phone); //it reads data from file defined by pointer
‘fp1a’
fprintf(stdout,"\n%s\t%s %d\n\n",name,add,phone); //it prints data from program to
screen
by above we come to two conclusions that if there is file pointer in the function that does connect
between program and file (it may be both reading and writing operations) however ‘std’ does
connection between program and screen, even though ‘fprintf’ or ‘fscanf’ seems to be only with file
handling. The other conclusion is that there must be certain relationship:
Screen Program File
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
140
From the above example, we see that at first phone number is taken from user as input to program
that is then stored in file and similarly, phone number is read from file to program then only printed
to screen, however direct printing and reading between screen and file is not possible.
PU2009 SPRING 6 B)
WAP to read name, author and price of 500 books to “library.dat” and then print info of books of
price > 300.
#include<stdio.h>
#include<conio.h>
struct library {
char book_name[35];
char book_author[15];
float book_price;
}element[500];
void main() {
int i;
FILE*fp;
printf("\nEnter Information of 500 Books\n");
fp=fopen("library.dat","w");//cause creating a new file or replacing if there is old file
for(i=0;i<500;i++) {
printf("Enter name:");
scanf("%s",&element[i].book_name);
printf("Enter Author:");
scanf("%s",&element[i].book_author);
printf("Enter Price:");
scanf("%f",&element[i].book_price);
fprintf(fp," %s %s %f",element[i].book_name,element[i].book_author,element[i].book_price);
}
fclose(fp);
fp=fopen("library.dat","r");
printf("\n Books whose price greater than Rs. 300\n");
printf("Name\t\t Author\t\t price\n");
for(i=0;i<500;i++) { // it is describe din B-part
// while(fp!=feof) { or while(fp!=NULL) { can be used instead this is described in A-part
fscanf(fp," %s %s %f",&element[i].book_name,&element[i].book_author,&element[i].book_price);
if(element[i].book_price>300) {
printf("%s\t%s\t\t0.3%f\n",element[i].book_name,element[i].book_author,element[i].book_price);
}
}
//TO HERE
fclose(fp);
getch();
}
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
141
Analysis:
Problem:
Here we need three variables to store name of book, author of book and price of book, but these
variables work only to a book so an array of 5800 book is required. We need to store all the
information of 500 books to a file and after that we have to read them and print the books having
price more than 300. So here an structure; a simple structure is necessary as there is no necessary of
branching structure elements as name of book, author and price are totally independent to each
other as well as they belong to different groups. The entity of that structure must be an array of 500
which can be used to read elements.
But for the particular case of above we use its advantage in printing too i.e. the 500 elements are
used for checking the conditio0n (price>300) and printing if satisfied.
B-part:
We know that there are 500 books so we directly did it, i.e. we continued our loop of i for 500 times
but in case we are unsure we follow A. In B, we are using the structure again from its object
elements initial value 0 to 499 to store the value from the file. If the condition is met, then it is
printed out. Instead of the array of structure’s object “element” we can use a single variable that
stores a value at a loop and check condition and work according to condition and for next loop the
variable stores next value and similarly so for goes on OR we may use array of variables without any
structure; it is because the array has noth8ing to do with the condition as each array check at each
time which is same to each variable at a time.
PU2009fall6 b)
Create a structure for the following data:
ID Name Address Salary Date of joining
dd mm yy
And write program to input 100 employees, save in emp.dat file and print info of employee who
have the address 'pokhara'.
#include<stdio.h>
#include<conio.h>
#include<string.h>
struct employee {
int id;
char name[40];
char address[30];
int salary;
struct yrofjoin {
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
142
int d;
int m;
int y;
} yoj;
}e1[100];
void main(){
int i;
FILE*fp;
fp=fopen("emp.dat","w");
for(i=0;i<100;i++){
printf("ID\t");
scanf("%d",&e1[i].id);
printf("Name\t");
scanf("%s",&e1[i].name);
printf("Address\t");
scanf("%s",&e1[i].address);
printf("Salary\t");
scanf("%d",&e1[i].salary);
printf("Day of Join\t");
scanf("%d",&e1[i].yoj.d);
printf("Month of Join\t");
scanf("%d",&e1[i].yoj.m);
printf("Year of Join\t");
scanf("%d",&e1[i].yoj.y);
fprintf(fp,"%d-%s-%s-%d-%d-%d-
%d/",e1[i].id,e1[i].name,e1[i].address,e1[i].salary,e1[i].yoj.d,e1[i].yoj.m,e1[i].yoj.y);
}
printf("\n\n");
fclose(fp);
fp=fopen("emp.dat","r");
printf("DATA STORED ABOUT EMPLOYEE WHO LIVES IN POKHARA\n");
printf("ID\t");
printf("Name\t\t");
printf("Address\t\t");
printf("Salary\t\t");
printf("Date of join\n\n");
for(i=0;i<100;i++){
fscanf(fp,"%d-%s-%s-%d-%d-%d-
%d/",&e1[i].id,&e1[i].name,&e1[i].address,&e1[i].salary,&e1[i].yoj.d,&e1[i].yoj.m,&e1[i].yoj.y);
if(strcmp(e1[i].address,"pokhara")==0) {
printf("%d\t%s\t%s\t%d\t%d-%d-
%d/",e1[i].id,e1[i].name,e1[i].address,e1[i].salary,e1[i].yoj.d,e1[i].yoj.m,e1[i].yoj.y);
}
}
fclose(fp);
getch();
}
We have used:-
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
143
fprintf(fp,"%d-%s-%s-%d-%d-%d-%d/",
e1[i].id,e1[i].name,e1[i].address,e1[i].salary,e1[i].yoj.d,e1[i].yoj.m,e1[i].yoj.y);
here
%d-%s-%s-%d-%d-%d-%d/
Is the format to store data, instead of – and / we can use other symbols too. Why are they used?
Let us suppose an input like
ID: 1
NAME: abc
ADDRESS: pokhara
SALARY: 500
DAY OF JOIN:1
MONTH OF JOIN:2
YEAR OF JOIN:2069
And if we put the format like this
%d%s%s%d%d%d%d
Without any space and symbols then in it will be save like this
1abcpokhara500122069
And while reading from file by
fscanf(fp,“%d%s%s%d%d%d%d”………………….);
%d will surely extract 1, but %s succeeding %d will extract abcpokhara because in the stored data
abcpokhara is a single string but here our intensition was to just extract NAME: abc, the second %s
succeeding it will extract no string as abc pokhara is already extracted by preceding %s and
500122069 is not a string.similarly the %d intentended to extract salary:500 will extract 500122069
and left %d%d%d for day, month,year will have nothing to extract.
So we need to use either appropriate symbols that has not been used in datas stored or we can
simply use single or double or more spaces or tabs according to complexity of data storage like this
%d %s %s %d %d %d %d
Here double space has been used, it is good not to use single space if we are storing string because
string like name can have space between first and last name.
Look carefully
%d-%s-%s-%d-%d-%d-%d/
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
144
We have used /, why think reasonably. It is because in file datas are added one-by-one in compact
manner i.e. if we store two datas like this:
ID: 1
NAME: abc
ADDRESS: pokhara
SALARY: 500
DAY OF JOIN:1
MONTH OF JOIN:2
YEAR OF JOIN:2069
ID: 2
NAME: xyz
ADDRESS: lekhnath
SALARY: 123
DAY OF JOIN:5
MONTH OF JOIN:11
YEAR OF JOIN:2066
And the format of saving in file is
“%d-%s-%s-%d-%d-%d-%d”
Then file it will be stored like this
1-abc-pokhara-500-1-2-20692-xyz-lekhnath-123-5-11-2066
Here you notice that in 20692, 2069 is year for first person and 2 is id of second person, but similar
to above, 20692 will be extracted as a single int type data and there will be no id to extract for
second person so we use
“ %d-%s-%s-%d-%d-%d-%d/”
which will change the above format of storing into
1-abc-pokhara-500-1-2-2069/2-xyz-lekhnath-123-5-11-2066
It is better if you use
“ /%d-%s-%s-%d-%d-%d-%d”
Here / is in front so that before each set of data is stored / is stored keeping a barrier between sets
of data, but use what you feel good and what program accepts without destroying the barrier
between set of data and also within the data of same set. We discussed about two barriers- one
internal between data of same set and another external between sets of data.
NOTE: In reading file by file_pointer, the last term of each installment of data in file must be
completely free from spaces or any symbols used as barrier like this
“ %d %s %f”
because file pointers read all (symbols too) showing that file is not feof i.e. it reads some symbols
like this
while(!feof(fp)){
fscanf(fp, “ %d %s %f ”);
fprintf(stdout, “ %d %s %f”);
}
Here even after all required values of data have been read and printed then ‘fscanf’ reads last
double space which shows ‘feof’ of ‘while’ is false (means ‘while-loop’ executes once more) even
after all required datas is already printed then ‘fprint’ is executed but the format does match as the
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
145
double spaces of file is unmatched to “ %d %s %f ” so the previous latest values of variables are
once more printed which means the last data of file is double printed. But next time, ‘feof’ is true
and ‘while-loop’ terminates.
Due fee
Prints student info whose due fee is less than 100
#include<stdio.h>
#include<conio.h>
void main(){
FILE *fp;
int n;
int roll;
float duefee;
int i;
char name[50];
fp=fopen("student.txt","w");
printf("How many input");
scanf("%d",&n);
for(i=0;i<n;i++) {
printf("Enter Student ID\t");
printf("Enter Student Name\t");
printf("Enter Duefee\n\n");
fscanf(stdin,"%d",&roll);
fscanf(stdin,"%s",&name);
fscanf(stdin,"%f",&duefee);
fprintf(fp," %d %s %f",roll,name,duefee);
}
fclose(fp);
fp=fopen("student.txt","r");
printf("STUDENTS WITH DUE FEES LESS THAN 100\n");
while(!feof(fp)){
fscanf(fp," %d %s %f",&roll,&name,&duefee);
if(duefee<100){
printf("ID\t");
printf("Name\t");
printf("Duefee\n\n");
fprintf(stdout,"\n%d\t%s\t%f\n",roll,name,duefee);
}
}
fclose(fp);
getch();
}
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
146
PU2002 Consumed charged data merged with file handling: WAP that stores following data
of customer of electricity authority in file ‘elect.dat’: id, name, old reading, new reading and amount
to be paid.
ELECRTIC DATA MERGED WITH FILE HANDLING
WAP that stores following data of customer of electricity authority in file ‘elect.dat’:
Id Name Old reading New reading Amount to be
paid
Hints: The amount to be paid is calculated by calculating the units consumed by subtracting ‘New
reading’ to ‘Old reading’ and following given list shows the range of units and rate as:
Range of units Rate per unit
0-200 4.5
201-400 5.5
400-above 7.5
Use this file to store data from user until user supplies ‘0’ as Id then after display the above list.
#include<stdio.h>
#include<conio.h>
struct customer{
int id;
char name[40];
int old_reading;
int new_reading;
float amount;
}cus[1000];
float calculation(int x){
float amount;
if(x<=200) {
amount=x*4.5;
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
147
}
else if(x>200 && x<=400) {
amount=200*4.5;
x=x-200;
amount=amount+(x*5.5);
}
else {
amount=200*4.5+200*5.5;
x=x-400;
amount=amount+x*7.5;
}
return (amount);
}
void main(){
int i=-1,value;
FILE*fp;
fp=fopen("elect.dat","w");
do {
i++;
printf("CUSTOMER ID\t");
scanf("%d",&cus[i].id);
printf("Name\t");
scanf("%s",&cus[i].name);
printf("Old Reading\t");
scanf("%d",&cus[i].old_reading);
printf("New Reading\t");
scanf("%d",&cus[i].new_reading);
value=cus[i].new_reading-cus[i].old_reading;
cus[i].amount=calculation(value);
fprintf(fp," %d %s %d %d
%.2f",cus[i].id,cus[i].name,cus[i].old_reading,cus[i].new_reading,cus[i].amount);/* we are using
double space as the string has scope over symbols like / or-*/
}
while((cus[i].id)!=0);
printf("\n\n");
fclose(fp);
fp=fopen("elect.dat","r");
printf("DATA STORED ABOUT CUSTOMERS OF ELECTRICITY AUTHORITY\n");
printf("ID\t");
printf("Name\t\t");
printf("Old reading\t\t");
printf("New reading\t\t");
printf("Amount to be paid\n\n");
i=0; /*previously 'i' was used to store to file now for reading from file so must be initialized as zero
or any value or nothing too works, even other variables can be declared but similar change to all
preceding program*/
while(!feof(fp)) {
fscanf(fp," %d %s %d %d
%f",&cus[i].id,&cus[i].name,&cus[i].old_reading,&cus[i].new_reading,&cus[i].amount);
printf("\n");
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
148
printf("%d\t%s\t%d\t%d\t%.2f",cus[i].id,cus[i].name,cus[i].old_reading,cus[i].new_reading,cus[i].am
ount);
}
fclose(fp);
getch();
}
Here ‘calculation()’ function returns amount to be paid in float type whereas it takes consumed units
as input. For calculation, here we the very simple process among the ways we discussed in
ELECRTICITY AUTHORITY sector.
As we see that do-while loop has condition to be checked which contains ‘i’ so here the value of ‘i’
must not increase or simply updated just before while-condition as this directly hampers the
condition of while so we have incremented ‘i’ in line following do-loop, but as we know ‘i’ must
starts from 0 and there is increment just after do-loop, so initially ‘i’ is assigned -1. The while-loop
only continues if the Id provided by user previously is not zero then continues with new input from
user saves it in file and then only checks if the id sent by user is zero or not, i.e. in file, we find that
the last stored data must have zero as id. Besides, it includes all data like name, readings, amount for
the customer to which our intension was not to be saved in file. This is the defect of the above
program.
This can be removed by adding a ‘if=statement’ checking whether the input Id is zero or not, if zero
then goto outside else continue by using goto inside:, like below:
#include<stdio.h>
#include<conio.h>
struct customer{
int id;
char name[40];
int old_reading;
int new_reading;
float amount;
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
149
}cus[100];
float calculation(int x){
float amount;
if(x<=200) {
amount=x*4.5;
}
else if(x>200 && x<=400) {
amount=200*4.5;
x=x-200;
amount=amount+(x*5.5);
}
else {
amount=200*4.5+200*5.5;
x=x-400;
amount=amount+x*7.5;
}
return (amount);
}
void main(){
int i=0,net_unit=0;
FILE*fp;
fp=fopen("elect.dat","w");
inside:
printf("CUSTOMER ID\t");
scanf("%d",&cus[i].id);
if((cus[i].id)==0) goto outside;
printf("Name\t");
scanf("%s",&cus[i].name);
printf("Old Reading\t");
scanf("%d",&cus[i].old_reading);
printf("New Reading\t");
scanf("%d",&cus[i].new_reading);
net_unit=cus[i].new_reading-cus[i].old_reading;
cus[i].amount=calculation(net_unit);
fprintf(fp," %d %s %d %d
%.2f",cus[i].id,cus[i].name,cus[i].old_reading,cus[i].new_reading,cus[i].amount);
goto inside;
outside:
printf("\n\n");
fclose(fp);
fp=fopen("elect.dat","r");
printf("DATA STORED ABOUT CUSTOMERS OF ELECTRICITY AUTHORITY\n");
printf("ID\t");
printf("Name\t\t");
printf("Old reading\t\t");
printf("New reading\t\t");
printf("Amount to be paid\n\n");
i=0; //here it is noted that i=0 for each time the loop of while so a static counter variable can be
usrd to store various data at varous steps
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
150
while(!feof(fp)) {
fscanf(fp," %d %s %d %d
%f",&cus[i].id,&cus[i].name,&cus[i].old_reading,&cus[i].new_reading,&cus[i].amount);
printf("%d\t%s\t%d\t%d\t%.2f\n",cus[i].id,cus[i].name,cus[i].old_reading,cus[i].new_reading,cus[i].
amount);
}
fclose(fp);
getch();
}
Study in above program; some changes taking place to value initialization of ‘i’ carefully.
PROJECTS
BOOKS
#include<stdio.h>
#include<conio.h>
void main(){
FILE *fp;
int n;
int code;
float price;
int i;
char name[50];
char book[50];
fp=fopen("booksinfo.txt","a");
printf("How many inputs?\t");
scanf("%d",&n);
for(i=0;i<n;i++) {
printf("Enter Book Code\n");
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
151
printf("Enter Author Name\n");
printf("Enter Book Name\n");
printf("Enter Cost Of Book\n");
fscanf(stdin,"%d",&code);
fscanf(stdin,"%s",&name);
fscanf(stdin,"%s",&book);
fscanf(stdin,"%f",&price);
fprintf(fp," %d %s %s %f",code,name,book,price);
}
printf("\n\n");
fclose(fp);
fp=fopen("booksinfo.txt","r");
printf("DATA STORED ABOUT BOOKS\n");
printf("CODE\t");
printf("NAME\t\t");
printf("BOOK\t\t");
printf("PRICE\n\n");
while(!feof(fp)){
fscanf(fp," %d %s %s %f",&code,&name,&book,&price);
fprintf(stdout,"\n%d\t%s\t%s\t%f\n",code,name,book,price);
}
fclose(fp);
getch();
}
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
152
PHONE BOOK
Store in a file “phonebook.txt” following:
Name Address Telephone
Using ‘switch-case’ statement, keep insert option and search option that searches info of the file in
regard to the number or string or even a character given by user. Here it means that few characters
also does working as an input for searching.
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<string.h>
int main() {
long double phone;/* these numbers have high range
unsigned long int range from 0 to 4294967295 i.e. 10 digits but lesser than mobile numbers
even float is small
so long double of 80 bits ranging 3.4e-4932 to 1.1e+4932
is used */
char phone_check[25]; // while comparing it is possible with string or character only
int num,found;
FILE *fp1a;
FILE*fp2a;
FILE*fp3a;
FILE*fp4a;
FILE*fp5a;
char name[25],add[50],name_check[25],add_check[50],phone_str[30];
printf("If you are using first time then goto option 1\n\n");
head:
found=0;// for each time head is referred a new initialization is required
printf("What do you want to do?\n");
printf("[1]\tto add info\n");
printf("[2]\tto look info list\n");
printf("[3]\tto search by name\n");
printf("[4]\tto search by address\n");
printf("[5]\tto search by telephone\n");
printf("[6]\tto exit\n");
printf("-------------------------------------------\n");
scanf("%d",&num);
printf("---------------------------------------------------------\n");
switch(num) {
case 1:
printf("Enter Name(ENTER Single name)\n");
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
153
printf("Enter Address\n");
printf("Enter Phone number\n");
fscanf(stdin,"%s",&name);
fscanf(stdin,"%s",&add);
fscanf(stdin,"%lf",&phone);
fp1a=fopen("phonebook.txt","a");
fprintf(fp1a," %s %s %.0lf",name,add,phone); //".0" as phone number has no value after
decimal
fclose(fp1a);
if(getch())goto head;
case 2:
printf("INFO OF FRIENDS YOU KNOW\n");
printf("\n\n--------------------------------------------------------------\n");
printf("NAME ");
printf("ADDRESS ");
printf("PHONE NUMBER\t\n");
fp2a=fopen("phonebook.txt","r");
while(!feof(fp2a)){
fscanf(fp2a," %s %s %lf",&name,&add,&phone);
fprintf(stdout,"\n%s\t%s\t%.0lf\n\n",name,add,phone);
}
fclose(fp2a);
if(getch())goto head;
case 3:
printf("Enter name to be searched\t");
scanf("%s",&name_check);
fp3a=fopen("phonebook.txt","r");
printf("\n\n\n\n INFO OF FRIENDS beginning with name \'%s\'\t\n",name_check);
printf("\n\n--------------------------------------------------------------\n");
printf("NAME ");
printf("ADDRESS ");
printf("PHONE\t");
while(!feof(fp3a)){
fscanf(fp3a," %s %s %lf",&name,&add,&phone);
if(strncmp(name,name_check,strlen(name_check))==0) {
fprintf(stdout,"\n%s\t%s\t%.0lf\n\n",name,add,phone);
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
154
found++;
}
}
fclose(fp3a);
if(found==0) {
printf("\nNOT FOUND\n");
}
if(getch())goto head;
case 4:
printf("Enter address to be searched\t");
scanf("%s",&add_check);
fp4a=fopen("phonebook.txt","r");
printf("\n\n\n\n INFO OF FRIENDS beginning with address \'%s\'\t\n",add_check);
printf("\n\n--------------------------------------------------------------\n");
printf("NAME ");
printf("ADDRESS ");
printf("PHONE\t");
while(!feof(fp4a)){
fscanf(fp4a," %s %s %lf",&name,&add,&phone);
if(strncmp(add,add_check,strlen(add_check))==0) {
fprintf(stdout,"\n%s\t%s\t%.0lf\n\n",name,add,phone);
found++;
}
}
fclose(fp4a);
if(found==0) {
printf("\nNOT FOUND\n");
}
if(getch())goto head;
case 5:
printf("Enter phone to be searched\t");
scanf("%s",&phone_check);
fp5a=fopen("phonebook.txt","r");
printf("\n\n\n\n INFO OF FREIENDS beginning with phone \'%s\'\t\n",phone_check);
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
155
printf("\n\n--------------------------------------------------------------\n");
printf("NAME ");
printf("ADDRESS ");
printf("PHONE\t");
while(!feof(fp5a)){
fscanf(fp5a," %s %s %s",&name,&add,&phone_str); //here '%s' at last of format works
because numbers can be string but string cannot be numbers
if(strncmp(phone_str,phone_check,strlen(phone_check))==0) {
fprintf(stdout,"\n%s\t%s\t%s\n\n",name,add,phone_str);
found++;
}
}
fclose(fp5a);
if(found==0) {
printf("\nNOT FOUND\n");
}
if(getch())goto head;
case 6:
printf("THANKS TO YOU\n GOOD BYE !");
if(getch()){
exit(0);
}
}
return 1;
}
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
156
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
157
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
158
MARKSHEET BY HARDER
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
FILE *fp;
FILE *fp1;
FILE*fp2;
int num;
int number,a;
int roll;
int roll_array[1000];
int j=0,k=0;
int i=0;
int roll_t;float mark1_t;float mark2_t;float mark3_t;float mark4_t;float mark5_t;float perct_t;
int rol;
int abc=1;
float mark1,mark2,mark3,mark4,mark5,percent;
float
mark1_array[100],mark2_array[100],mark3_array[100],mark4_array[100],mark5_array[100],perct_
array[100];
float mar1,mar2,mar3,mar4,mar5,perc;
char name[100];
char nam[30];
char name_array[1000][30];
char dummy[20];
char nam[30];
int main() {
printf("If it is your first time then goto option 1\n\n");
head:
printf("What do you want to do?\n");
printf("[1]\tto add mark list\n");
printf("[2]\tto look mark list\n");
printf("[3]\tto exit\n");
printf("-------------------------------------------\n");
scanf("%d",&num);
printf("-------------------------------------------\n");
switch(num) {
case 1:
printf("Enter the number of input student's marks?\t");
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
159
scanf("%d",&number);
fp=fopen("marksheet.txt","a");
for(a=0;a<number;a++) {
printf("Enter Roll\n");
printf("Enter Name(ENTER Single name)\n");
printf("Enter Marks in Computer\n");
printf("Enter Marks in Maths\n");
printf("Enter Marks in Electrical\n");
printf("Enter Marks in Thermal\n");
printf("Enter Marks in Physics\n");
fscanf(stdin,"%d",&roll);
fscanf(stdin,"%s",&name);
fscanf(stdin,"%f",&mark1);
fscanf(stdin,"%f",&mark2);
fscanf(stdin,"%f",&mark3);
fscanf(stdin,"%f",&mark4);
fscanf(stdin,"%f",&mark5);
percent=(mark1+mark2+mark3+mark4+mark5)/5;
fprintf(fp," %d %s %f %f %f %f %f
%f",roll,name,mark1,mark2,mark3,mark4,mark5,percent);
}
fclose(fp);
if(getch()) goto head;
case 2:
fp=fopen("marksheet.txt","r");
while(!feof(fp)){
fscanf(fp," %d %s %f %f %f %f %f
%f",&roll_array[i],&name_array[i],&mark1_array[i],&mark2_array[i],&mark3_array[i],&mark4_arra
y[i],&mark5_array[i],&perct_array[i]);
i++;
}
fclose(fp);
//Sorting begins-descending by bubble method
for(j=1;j<i;j++) {
for(k=1;k<=i-j;k++) {
if(perct_array[k-1]<perct_array[k]) {
roll_t=roll_array[k-1];
roll_array[k-1]=roll_array[k];
roll_array[k]=roll_t;
strcpy(dummy,name_array[k-1]);
strcpy(name_array[k-1],name_array[k]);
strcpy(name_array[k],dummy);
mark1_t=mark1_array[k-1];
mark1_array[k-1]=mark1_array[k];
mark1_array[k]=mark1_t;
mark2_t=mark2_array[k-1];
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
160
mark2_array[k-1]=mark2_array[k];
mark2_array[k]=mark2_t;
mark3_t=mark3_array[k-1];
mark3_array[k-1]=mark3_array[k];
mark3_array[k]=mark3_t;
mark4_t=mark4_array[k-1];
mark4_array[k-1]=mark4_array[k];
mark4_array[k]=mark4_t;
mark5_t=mark5_array[k-1];
mark5_array[k-1]=mark5_array[k];
mark5_array[k]=mark5_t;
perct_t=perct_array[k-1];
perct_array[k-1]=perct_array[k];
perct_array[k]=perct_t;
}
}
}
// Rank List
fp1=fopen("ascending list of mark_sheet.txt","w");
for(j=0;j<i;j++) {
fprintf(fp1," %d %s %f %f %f %f %f
%f",roll_array[j],name_array[j],mark1_array[j],mark2_array[j],mark3_array[j],mark4_array[j],mark5
_array[j],perct_array[j]);
}
fclose(fp1);
printf("MARKSHEET OF STUDENTS\t(RANK WISE)\n\n");
printf("\n\n--------------------------------------------------------------\n");
printf("RANK ");
printf("ROLL ");
printf("NAME\t");
printf("Computer ");
printf("Maths ");
printf("Electrical ");
printf("Thermal ");
printf("Physics ");
printf("PERCENT");
fp2=fopen("ascending list of mark_sheet.txt","r");
while(!feof(fp)){
fscanf(fp," %d %s %f %f %f %f %f %f",&rol,&nam,&mar1,&mar2,&mar3,&mar4,&mar5,&perc);
fprintf(stdout,"\n%d\t%d %s\t %.2f\t %.2f %.2f %.2f \t%.2f
%.2f\n\n\n",abc,rol,nam,mar1,mar2,mar3,mar4,mar5,perc);
abc++;
}
if(getch()) goto head;
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
161
case 3:
printf("Thanks for your attention , please also refer 'by easier' and 'updated' method");
if(getch()) exit(0);
}
getch();
return 1;
}
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
162
MARKSHEET BY EASIER
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<string.h>
FILE*fp;
FILE*fp1;
FILE *fp3;
FILE*fp4;
int rola;
int num;
int rol;
int check;
int rol3;
int number,a;
int roll;
int abca;
int founda;
int count;
int abc3;
int found3;
int abc;
float mara1,mara2,mara3,mara4,mara5,perca;
float mark1,mark2,mark3,mark4,mark5,percent;
float mar31,mar32,mar33,mar34,mar35,perc3;
float mar1,mar2,mar3,mar4,mar5,perc;
char nama[30];
char name[100];
char c;
char nam3[30];
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
163
char nam[30];
char checkk[30];
char file_status[10]="old";
int main() {
fp=fopen("marksheet.txt","r");
if(fp==NULL) { printf("No file was created till now\nNow created...\n\n");
fclose(fp);
fp=fopen("marksheet.txt","w");
fclose(fp);
strcpy(file_status,"new");
}
A:
printf("What do you want to do?\n");
printf("[1]\tto add mark list\n");
printf("[2]\tto look mark list\n");
printf("[3]\tto search by roll\n");
printf("[4]\tto search by name\n");
printf("[5]\tto exit\n");
abca=0;
founda=0;
abc3=0;
found3=0;
abc=1;
printf("-------------------------------------------\n");
scanf("%d",&num);
printf("-------------------------------------------\n");
switch(num) {
case 1:
printf("Enter the number of input student's marks?\t");
scanf("%d",&number);
for(a=0;a<number;a++) {
count=0; //for each new entered number or each new loop of 'i' count=0
printf("Enter Roll\n");
printf("Enter Name(ENTER Single name)\n");
printf("Enter Marks in Computer\n");
printf("Enter Marks in Maths\n");
printf("Enter Marks in Electrical\n");
printf("Enter Marks in Thermal\n");
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
164
printf("Enter Marks in Physics\n");
fscanf(stdin,"%d",&roll);
fscanf(stdin,"%s",&name);
fscanf(stdin,"%f",&mark1);
fscanf(stdin,"%f",&mark2);
fscanf(stdin,"%f",&mark3);
fscanf(stdin,"%f",&mark4);
fscanf(stdin,"%f",&mark5);
percent=(mark1+mark2+mark3+mark4+mark5)/5;
fp=fopen("marksheet.txt","r");
fp1=fopen("temp of mark_sheet.txt","w");
if(strcmp(file_status,"old")==0){
while(!feof(fp)){
fscanf(fp," %d %s %f %f %f %f
%f %f",&rol,&nam,&mar1,&mar2,&mar3,&mar4,&mar5,&perc);
if(count==0){
if(percent<perc) {
fprintf(fp1," %d %s %f %f %f %f %f
%f",rol,nam,mar1,mar2,mar3,mar4,mar5,perc);
}
else {
count++;
fprintf(fp1," %d %s %f %f %f %f %f
%f",roll,name,mark1,mark2,mark3,mark4,mark5,percent); //this means that new data is entered
fprintf(fp1," %d %s %f %f %f %f %f %f",rol,nam,mar1,mar2,mar3,mar4,mar5,perc);
}
}
else {
fprintf(fp1," %d %s %f %f %f %f %f
%f",rol,nam,mar1,mar2,mar3,mar4,mar5,perc);
}
} //while-loop brace
if(count==0) fprintf(fp1," %d %s %f %f %f %f %f
%f",roll,name,mark1,mark2,mark3,mark4,mark5,percent); /*this means that new data is entered
for the case comparison is done to all values of files but all data of files if found descending than
this new value thewn at last new value is added i.e. in this case after while loop terminates*/
}
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
165
else { /* if file is new then just print it the value as fp in reading newly created file gives some
unnecessary old values so it is done*/
fprintf(fp1," %d %s %f %f %f %f %f %f",roll,name,mark1,mark2,mark3,mark4,mark5,percent);
//this means that new data is entered
strcpy(file_status,"old");
}
fclose(fp);
fclose(fp1);
fp=fopen("marksheet.txt","w");
fp1=fopen("temp of mark_sheet.txt","r");
while((c=getc(fp1))!=EOF) {
putc(c,fp);
}
fclose(fp);
fclose(fp1);
}
if(getch())goto A;
case 2:
printf("MARKSHEET OF STUDENTS\t(RANK WISE)\n\n");
printf("\n\n--------------------------------------------------------------\n");
printf("RANK ");
printf("ROLL ");
printf("NAME\t");
printf("Computer ");
printf("Maths ");
printf("Electrical ");
printf("Thermal ");
printf("Physics ");
printf("PERCENT");
fp=fopen("marksheet.txt","r");
while(!feof(fp)){
fscanf(fp," %d %s %f %f %f %f %f %f",&rol,&nam,&mar1,&mar2,&mar3,&mar4,&mar5,&perc);
fprintf(stdout,"\n%d\t%d %s\t %.2f\t %.2f %.2f %.2f \t%.2f
%.2f\n\n\n",abc,rol,nam,mar1,mar2,mar3,mar4,mar5,perc);
abc++;
}
fclose(fp);
if(getch())goto A;
case 3:
printf("Enter roll number\t");
scanf("%d",&check);
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
166
fp3=fopen("marksheet.txt","r");
printf("\n\n\n\n MARKSHEET OF STUDENTS with roll \'%d\'\t\n",check);
printf("\n\n--------------------------------------------------------------\n");
printf("RANK ");
printf("ROLL ");
printf("NAME\t");
printf("Computer ");
printf("Maths ");
printf("Electrical ");
printf("Thermal ");
printf("Physics ");
printf("PERCENT");
while(!feof(fp3)){
abc3++;
fscanf(fp3," %d %s %f %f %f %f %f
%f",&rol3,&nam3,&mar31,&mar32,&mar33,&mar34,&mar35,&perc3);
if(rol3==check) {
fprintf(stdout,"\n%d\t%d %s\t %.2f\t %.2f %.2f %.2f \t%.2f
%.2f\n\n\n",abc3,rol3,nam3,mar31,mar32,mar33,mar34,mar35,perc3);
found3++;
}
}
fclose(fp3);
if(found3==0) {
printf("\nNOT FOUND\n");
}
if(getch())goto A;
case 4:
printf("Enter name\t");
scanf("%s",&checkk);
fp4=fopen("marksheet.txt","r");
printf("\n\n\n\n MARKSHEET OF STUDENTS beginning with name \'%s\'\t(RANK
WISE)\n",checkk);
printf("\n\n--------------------------------------------------------------\n");
printf("RANK ");
printf("ROLL ");
printf("NAME\t");
printf("Computer ");
printf("Maths ");
printf("Electrical ");
printf("Thermal ");
printf("Physics ");
printf("PERCENT");
while(!feof(fp4)){
abca++;
fscanf(fp4," %d %s %f %f %f %f %f
%f",&rola,&nama,&mara1,&mara2,&mara3,&mara4,&mara5,&perca);
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
167
if(strncmp(nama,checkk,(strlen(checkk)))==0) {
fprintf(stdout,"\n%d\t%d %s\t %.2f\t %.2f %.2f %.2f \t%.2f
%.2f\n\n\n",abca,rola,nama,mara1,mara2,mara3,mara4,mara5,perca);
founda++;
}
}
fclose(fp4);
if(founda==0) {
printf("\nNOT FOUND\n");
}
if(getch())goto A;
case 5:
printf("THANKS TO YOU FOR VISITING THIS MARKSHEET PROGRAM");
if(getch()){
exit(0);
}
}
getch();
return 1;
}
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
168
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
169
UPDATED MARKSHEET
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<string.h>
FILE *fp;
FILE *fp1a;
FILE*fp1b;
FILE*fp1c;
FILE *fp2a;
FILE*fp1d;
FILE *fp3a;
FILE *fp4a;
FILE *fp5a;
FILE *fp5b;
FILE *fp5c;
FILE *fp5d;
FILE *fp6a;
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
170
FILE *fp6b;
FILE *fp6c;
FILE *fp6d;
int num,number,a,roll,rol,roll_check,roll_delete;
float mar1,mar2,mar3,mar4,mar5,perc,mark1,mark2,mark3,mark4,mark5,percent;
char c,nam[30],name[100],name_check[30],name_delete[15],file_status[5]="old";
int main() {
fp=fopen("marksheet.txt","r");
if(fp==NULL) { printf("No file was created till now\nNow created...\n\n");
fclose(fp);
fp=fopen("marksheet.txt","w");
fclose(fp);
strcpy(file_status,"new");
}
printf("If your are using first time then goto option 1\n\n");
head:
printf("What do you want to do?\n");
printf("[1]\tto add mark list\n");
printf("[2]\tto look mark list\n");
printf("[3]\tto search by roll\n");
printf("[4]\tto search by name\n");
printf("[5]\tto delete by roll\n");
printf("[6]\tto delete by name\n");
printf("[7]\tto exit\n");
printf("-------------------------------------------\n");
int count,found=0,abc=1;
scanf("%d",&num);
printf("---------------------------------------------------------\n");
switch(num) {
case 1:
printf("Enter the number of input student's marks?\t");
scanf("%d",&number);
for(a=0;a<number;a++) {
count=0; //same to previous 'easier method' refer it
printf("Enter Roll\n");
printf("Enter Name(ENTER Single name)\n");
printf("Enter Marks in Computer\n");
printf("Enter Marks in Maths\n");
printf("Enter Marks in Electrical\n");
printf("Enter Marks in Thermal\n");
printf("Enter Marks in Physics\n");
fscanf(stdin,"%d",&roll);
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
171
fscanf(stdin,"%s",&name);
fscanf(stdin,"%f",&mark1);
fscanf(stdin,"%f",&mark2);
fscanf(stdin,"%f",&mark3);
fscanf(stdin,"%f",&mark4);
fscanf(stdin,"%f",&mark5);
percent=(mark1+mark2+mark3+mark4+mark5)/5;
fp1a=fopen("marksheet.txt","r");
fp1b=fopen("temp of mark_sheet.txt","w");
if(strcmp(file_status,"old")==0){
while(!feof(fp1a)){
fscanf(fp1a," %d %s %f %f %f %f %f
%f",&rol,&nam,&mar1,&mar2,&mar3,&mar4,&mar5,&perc);
if(count==0){
if(percent<perc) {
fprintf(fp1b," %d %s %f %f %f %f %f
%f",rol,nam,mar1,mar2,mar3,mar4,mar5,perc);
}
else {
count++;
fprintf(fp1b," %d %s %f %f %f %f %f
%f",roll,name,mark1,mark2,mark3,mark4,mark5,percent);
fprintf(fp1b," %d
%s %f %f %f %f %f %f",rol,nam,mar1,mar2,mar3,mar4,mar5,perc);
}
}
else fprintf(fp1b," %d %s %f %f
%f %f %f %f",rol,nam,mar1,mar2,mar3,mar4,mar5,perc);
} //while-loop terminal brace
if(count==0) fprintf(fp1b," %d %s %f %f %f %f
%f %f",roll,name,mark1,mark2,mark3,mark4,mark5,percent); /* same to old method: this means
that new data is entered for the case comparison is done to all values of files but all data of files if
found descending than this new value thewn at last new value is added i.e. in this case after while
loop terminates*/
}
else { /* if file is new then just print it the value as fp in reading
newly created file gives some unnecessary old values so it is done*/
fprintf(fp1b," %d %s %f %f %f %f %f
%f",roll,name,mark1,mark2,mark3,mark4,mark5,percent); //this means that new data is entered
strcpy(file_status,"old");
}
fclose(fp1a);
fclose(fp1b);
fp1c=fopen("marksheet.txt","w");
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
172
fp1d=fopen("temp of mark_sheet.txt","r");
while((c=getc(fp1d))!=EOF) {
putc(c,fp1c);
}
fclose(fp1c);
fclose(fp1d);
} // terminal of for-loop
if(getch())goto head;
case 2:
printf("MARKSHEET OF STUDENTS\t(RANK WISE)\n\n");
printf("\n\n--------------------------------------------------------------\n");
printf("RANK ");
printf("ROLL ");
printf("NAME\t");
printf("Computer ");
printf("Maths ");
printf("Electrical ");
printf("Thermal ");
printf("Physics ");
printf("PERCENT");
fp2a=fopen("marksheet.txt","r");
while(!feof(fp2a)){
fscanf(fp2a," %d %s %f %f %f %f %f
%f",&rol,&nam,&mar1,&mar2,&mar3,&mar4,&mar5,&perc);
fprintf(stdout,"\n%d\t%d %s\t %.2f\t %.2f %.2f %.2f \t%.2f
%.2f\n\n\n",abc,rol,nam,mar1,mar2,mar3,mar4,mar5,perc);
}
fclose(fp2a);
if(getch())goto head;
case 3:
printf("Enter roll number\t");
scanf("%d",&roll_check);
printf("\n\n\n\n MARKSHEET OF STUDENTS beginning with \'%d\'\t(RANK
WISE)\n",roll_check);
printf("\n\n--------------------------------------------------------------\n");
printf("RANK ");
printf("ROLL ");
printf("NAME\t");
printf("Computer ");
printf("Maths ");
printf("Electrical ");
printf("Thermal ");
printf("Physics ");
printf("PERCENT");
fp3a=fopen("marksheet.txt","r");
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
173
while(!feof(fp3a)){
count++;
fscanf(fp3a," %d %s %f %f %f %f %f
%f",&rol,&nam,&mar1,&mar2,&mar3,&mar4,&mar5,&perc);
if(rol==roll_check) {
fprintf(stdout,"\n%d\t%d %s\t %.2f\t %.2f %.2f %.2f \t%.2f
%.2f\n\n\n",count,rol,nam,mar1,mar2,mar3,mar4,mar5,perc);
found++;
}
}
fclose(fp3a);
if(found==0) {
printf("\nNOT FOUND\n");
}
if(getch())goto head;
case 4:
printf("Enter name\t");
scanf("%s",&name_check);
fp4a=fopen("marksheet.txt","r");
printf("\n\n\n\n MARKSHEET OF STUDENTS beginning with \'%s\'\t(RANK
WISE)\n",name_check);
printf("\n\n--------------------------------------------------------------\n");
printf("RANK ");
printf("ROLL ");
printf("NAME\t");
printf("Computer ");
printf("Maths ");
printf("Electrical ");
printf("Thermal ");
printf("Physics ");
printf("PERCENT");
while(!feof(fp4a)){
count++;
fscanf(fp4a," %d %s %f %f %f %f %f
%f",&rol,&nam,&mar1,&mar2,&mar3,&mar4,&mar5,&perc);
if(strncmp(nam,name_check,(strlen(name_check)))==0) {
fprintf(stdout,"\n%d\t%d %s\t %.2f\t %.2f %.2f %.2f \t%.2f
%.2f\n\n\n",count,rol,nam,mar1,mar2,mar3,mar4,mar5,perc);
found++;
}
}
fclose(fp4a);
if(found==0) {
printf("\nNOT FOUND\n");
}
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
174
if(getch())goto head;
case 5:
printf("Enter Roll number whose marksheet is to be deleted");
scanf("%d",&roll_delete);
fp5a=fopen("marksheet.txt","r");
fp5b=fopen("temp of mark_sheet.txt","w");
while(!feof(fp5a)){
fscanf(fp5a," %d %s %f %f %f %f %f
%f",&rol,&nam,&mar1,&mar2,&mar3,&mar4,&mar5,&perc);
if(roll_delete==rol){
printf("Marksheet is updated\n");
}
else {
fprintf(fp5b," %d %s %f %f %f %f %f %f",rol,nam,mar1,mar2,mar3,mar4,mar5,perc);
}
}
fclose(fp5a);
fclose(fp5b);
fp5c=fopen("marksheet.txt","w");
fp5d=fopen("temp of mark_sheet.txt","r");
while((c=getc(fp5d))!=EOF) {
putc(c,fp5c);
}
fclose(fp5c);
fclose(fp5d);
if(getch()){ goto head;
}
case 6:
printf("Enter name beginning with to be deleted");
scanf("%s",name_delete);
fp6a=fopen("marksheet.txt","r");
fp6b=fopen("temp of mark_sheet.txt","w");
while(!feof(fp6a)){
fscanf(fp6a," %d %s %f %f %f %f %f
%f",&rol,&nam,&mar1,&mar2,&mar3,&mar4,&mar5,&perc);
if(strncmp(nam,name_delete,strlen(name_delete))==0){
printf("Marksheet is updated\n");
}
else {
fprintf(fp6b," %d %s %f %f %f %f %f %f",rol,nam,mar1,mar2,mar3,mar4,mar5,perc);
}
}
fclose(fp6a);
fclose(fp6b);
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
175
fp6c=fopen("marksheet.txt","w");
fp6d=fopen("temp of mark_sheet.txt","r");
while((c=getc(fp6d))!=EOF) {
putc(c,fp6c);
}
fclose(fp6c);
fclose(fp6d);
if(getch()){ goto head;
}
case 7:
printf("THANKS TO YOU\n GOOD BYE !");
if(getch()){
exit(0);
}
}
return 1;
}
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
176
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
177
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
178
STORES
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<string.h>
FILE *fp;
FILE*fp1;
FILE*fp2;
FILE*fp3;
FILE*fp11;
struct tempcalculation {
char tempname[40];
int tempquantity;
float temprate;
}temp[100];
int num;
int code;
int stock;
int costcode;
int costquantity;
int new;
int n,i;
int code;
int na;
int naa;
int neew;
int tempi;
float price;
float rate;
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
179
float total;
char item[100];
char name[40];
char item[100];
char file_status[10]="old";
int main(){
fp=fopen("stores.txt","r");
if(fp==NULL) { printf("No stores file was created till now\nNow created...\n\n");
fclose(fp);
fp=fopen("stores.txt","w");
fclose(fp);
strcpy(file_status,"new");
}
printf("****************************************WELCOME TO
STORES*****************************\n\n\n");
printf("-----------------------------------------------------------------------------------\n");
printf("Enter your full name:-\t");
scanf("%[^\n]",name);
main:
printf("\n\n----------------------------------\n");
printf("What do you want to do?\n");
printf("[1]\tto look list\n");
printf("[2]\tto calculate\n");
printf("[3]\tto add items\n");
printf("[4]\tto change stock\n");
printf("[5]\tto add stock\n");
printf("[6]\tto exit\n\n");
printf("---------------------------------------------\n");
scanf("%d",&num);
printf("---------------------------------------\n");
tempi=0;//this must be initialized for each new install of calculation
switch (num) {
case 1:
fp=fopen("stores.txt","r");
printf("DATA STORED ABOUT ITEMS\n\n");
printf("\n\n-----------------------------------------------------------------------------------\n");
printf("CODE\t");
printf("ITEM NAME\t\t");
printf("PRICE\t\t");
printf("STOCK\n\n");
while(!feof(fp)){
fscanf(fp," %d %s %f %d",&code,&item,&price,&stock);
fprintf(stdout,"\n%d\t%s\t\t%f\t\t%d\n",code,item,price,stock);
}
fclose(fp);
if(getch()){
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
180
goto main;
}
case 2:
printf("CALCULATION\n");
tempcheck:
printf("Enter[0/0] to end\n");
printf("Enter [code]/[quantity]\t\t");
scanf("%d/%d",&costcode,&costquantity);
if(costcode==0 && costquantity==0 ) {
total=0;
printf("YOUR COST\n\n");
printf("-----------------------------------------------------------------------------\n");
printf("ITEMS\t\t\tRATE\t\t\tQUANTITY\t\tSUM\n");
printf("----------------------------------------------------------------------------\n");
for(i=0;i<tempi;i++) {
printf("%s\t\t",temp[i].tempname);
printf("%f\t\t",temp[i].temprate);
printf("%d\t\t",temp[i].tempquantity);
printf("%f\n",temp[i].temprate*temp[i].tempquantity);
total=total+(temp[i].temprate*temp[i].tempquantity);
}
printf("--------------------------------------------------\n");
printf("\t\t\t\t\t\tTOTAL==Rs.%.2f\n",total);
printf("Checked by :\t%s",name);
if(getch()){
goto main;
}
}
else {
fp=fopen("stores.txt","r");
fp1=fopen("tempofstore.txt","w");
while(!feof(fp)) {
fscanf(fp," %d %s %f %d",&code,&item,&price,&stock);
if(costcode==code){
if(costquantity>stock){
printf("\n%s is not in stock\n",item);
fprintf(fp1," %d %s %f %d",code,item,price,stock);
continue;
}
new=stock-costquantity;
fprintf(fp1," %d %s %f %d",code,item,price,new);
strcpy(temp[tempi].tempname,item);//temp[tempi].tempname=item;
temp[tempi].temprate=price;
temp[tempi].tempquantity=costquantity;
tempi++;
}
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
181
else {
fprintf(fp1," %d %s %f %d",code,item,price,stock);
}
}
fclose(fp);
fclose(fp1);
fp3=fopen("tempofstore.txt","r");
fp2=fopen("stores.txt","w");
while(!feof(fp3)){
fscanf(fp3," %d %s %f %d",&code,&item,&price,&stock);
fprintf(fp2," %d %s %f %d",code,item,price,stock);
}
fclose(fp3);
fclose(fp2);
goto tempcheck;
}
case 3:
fp=fopen("stores.txt","a");
printf("How many inputs?\t");
scanf("%d",&n);
for(i=0;i<n;i++) {
printf("Enter Code\n");
printf("Enter Item Name\n");
printf("Enter Rate\n");
printf("Enter Stocks\n");
fscanf(stdin,"%d",&code);
fscanf(stdin,"%s",&item);
fscanf(stdin,"%f",&rate);
fscanf(stdin,"%d",&stock);
fprintf(fp," %d %s %f %d",code,item,rate,stock);
}
fclose(fp);
if(getch()){
goto main;
}
case 4:
printf("Enter code\t");
scanf("%d",&na);
printf("Change it by\t");
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
182
scanf("%d",&new);
fp=fopen("stores.txt","r");
fp1=fopen("tempofstore.txt","w");
while(!feof(fp)){
fscanf(fp," %d %s %f %d",&code,&item,&price,&stock);
if(na==code){
fprintf(fp1," %d %s %f %d",code,item,price,new);
}
else
fprintf(fp1," %d %s %f %d",code,item,price,stock);
}
fclose(fp);
fclose(fp1);
fp1=fopen("tempofstore.txt","r");
fp=fopen("stores.txt","w");
while(!feof(fp1)){
fscanf(fp1," %d %s %f %d",&code,&item,&price,&stock);
fprintf(fp," %d %s %f %d",code,item,price,stock);
}
fclose(fp);
fclose(fp1);
if(getch()){
goto main;
}
case 5:
printf("Enter code\t");
scanf("%d",&naa);
printf("Add it by\t");
scanf("%d",&neew);
fp=fopen("stores.txt","r");
fp11=fopen("tempofstore.txt","w");
while(!feof(fp)){
fscanf(fp," %d %s %f %d",&code,&item,&price,&stock);
if(naa==code){
neew=stock+neew;
fprintf(fp11," %d %s %f %d",code,item,price,neew);
}
else
fprintf(fp11," %d %s %f %d",code,item,price,stock);
}
fclose(fp);
fclose(fp11);
fp1=fopen("tempofstore.txt","r");
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
183
fp=fopen("stores.txt","w");
while(!feof(fp1)){
fscanf(fp1," %d %s %f %d",&code,&item,&price,&stock);
fprintf(fp," %d %s %f %d",code,item,price,stock);
}
fclose(fp);
fclose(fp1);
if(getch()){
goto main;
}
case 6:
printf("\n\n------------------------------------------------------\n");
printf("THANKS %s FOR YOUR SERVICE",name);
printf("\n\n----------------------------------------\n");
if(getch()){
exit(1); } }return 1;}
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
184
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
185
UPDATED STORES
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<string.h>
FILE *fp;
FILE *fp1a;
FILE *fp2a;
FILE*fp2b;
FILE*fp2c;
FILE*fp2d;
FILE*fp3aa;
FILE*fp3a;
FILE*fp3b;
FILE*fp3c;
FILE*fp3d;
FILE*fp4a;
FILE*fp4b;
FILE*fp4c;
FILE*fp4d;
FILE*fp5a;
FILE*fp5b;
FILE*fp5c;
FILE*fp5d;
FILE*fp6a;
FILE*fp6b;
FILE*fp6c;
FILE*fp6d;
FILE*fp7a;
FILE*fp8a;
struct tempcalculation {
char tempname[40];
int tempquantity;
float temprate;
}temp[100];
int num;
int code;
int stock;
int costcode;
int costquantity;
int new;
int n,i;
int code;
int na;
int naa;
int neew;
int tempi;
int new_stock,count=0,codef,stockf,del,na,naa,neew,code_search;
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
186
float price;
float rate;
float total;
float ratef;
float vat;
char item[100];
char name[40];
char itemf[100],c,item_search[15];
char file_status[10]="old";
int main(){
fp=fopen("stores.txt","r");
if(fp==NULL) { printf("No stores file was created till now\nNow created...\n\n");
fclose(fp);
fp=fopen("stores.txt","w");
fclose(fp);
strcpy(file_status,"new");
}
printf("***********************************WELCOME TO
STORES*****************************\n\n\n");
printf("**********************Programmer-Devendra Man
Palikhe**************************\n\n");
printf("------------------------------------------------------------------------------\n");
printf("Enter your full name:-\t");
scanf("%[^\n]",&name);
main:
printf("\n\n----------------------------------------\n");
printf("What do you want to do?\n");
printf("[1]\tto look list\n");
printf("[2]\tto calculate\n");
printf("[3]\tto add items\n");
printf("[4]\tto delete item\n");
printf("[5]\tto change stock\n");
printf("[6]\tto add stock\n");
printf("[7]\tto search item by code\n");
printf("[8]\tto search item by item_name\n");
printf("[9]\tto exit\n\n");
printf("-------------------------------------------\n");
scanf("%d",&num);
printf("-------------------------------------------\n");
tempi=0;//this must be initialized for each new install of calculation
vat=0;
switch (num) {
case 1:
printf("\n");
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
187
fp1a=fopen("stores.txt","r");
printf("DATA STORED ABOUT ITEMS\n\n");
printf("\n\n--------------------------------------------------------------\n");
printf("CODE\t");
printf("ITEM NAME\t\t");
printf("PRICE\t\t");
printf("STOCK\n\n");
while(!feof(fp1a)){
fscanf(fp1a," %d %s %f %d",&code,&item,&price,&stock);
fprintf(stdout,"\n%d\t%s\t\t%f\t\t%d\n",code,item,price,stock);
}
fclose(fp1a);
if(getch()){
goto main;
}
case 2:
printf("CALCULATION\n");
tempcheck:
printf("Enter[0/0] to end\n");
printf("Enter [code]/[quantity]\t\t");
scanf("%d/%d",&costcode,&costquantity);
if(costcode==0 && costquantity==0 ) {
total=0;
printf("YOUR COST\n\n");
printf("--------------------------------------------------\n");
printf("ITEMS\t\t\tRATE\t\t\tQUANTITY\tSUM\n");
printf("--------------------------------------------------\n");
for(i=0;i<tempi;i++) {
printf("%s\t\t",temp[i].tempname);
printf("%.2f\t\t",temp[i].temprate);
printf("%d\n",temp[i].tempquantity);
printf("%.2f\n",temp[i].temprate*temp[i].tempquantity);
total=total+(temp[i].temprate*temp[i].tempquantity);
}
printf("--------------------------------------------------\n");
printf("If any, then include VAT:\t");
scanf("%f",&vat);
printf("\t\t\t\t\t\tNET TOTAL==Rs.%.2f\n",total+(total*vat/100));
printf("\t\t\t\t\t\tVAT==Rs.%.2f\n",total*vat/100);
printf("\t\t\t\t\t\tTOTAL==Rs.%.2f\n",total+(total*vat/100));
printf("Checked by :\t%s",name);
if(getch()){
goto main;
}
}
else {
fp2a=fopen("stores.txt","r");
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
188
fp2b=fopen("temp of stores.txt","w");
while(!feof(fp2a)){
fscanf(fp2a," %d %s %f %d",&code,&item,&price,&stock);
if(costcode==code){
if(costquantity>stock){
printf("\n%s is not in stock\n",item);
fprintf(fp2b," %d %s %f %d",code,item,price,stock);
continue;
}
new_stock=stock-costquantity;
fprintf(fp2b," %d %s %f %d",code,item,price,new_stock);
strcpy(temp[tempi].tempname,item);//temp[tempi].tempname=item;
temp[tempi].temprate=price;
temp[tempi].tempquantity=costquantity;
tempi++;
}
else {
fprintf(fp2b," %d %s %f %d",code,item,price,stock);
}
}
fclose(fp2a);
fclose(fp2b);
fp2c=fopen("temp of stores.txt","r");
fp2d=fopen("stores.txt","w");
while(!feof(fp2c)){
fscanf(fp2c," %d %s %f %d",&code,&item,&price,&stock);
fprintf(fp2d," %d %s %f %d",code,item,price,stock);
}
fclose(fp2c);
fclose(fp2d);
goto tempcheck;
}
case 3:
printf("How many inputs?\t");
scanf("%d",&n);
for(i=0;i<n;i++) {
next:
count=0; //for each new entered input or each new loop of 'i' count=0
printf("Enter Code\t");
printf("Enter Item Name\t");
printf("Enter Rate\t");
printf("Enter Stocks\n\n");
fscanf(stdin,"%d",&code);
fscanf(stdin,"%s",&item);
fscanf(stdin,"%f",&rate);
fscanf(stdin,"%d",&stock);
fp3aa=fopen("stores.txt","r");
while(!feof(fp3aa)){
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
189
fscanf(fp3aa," %d %s %f %d",&codef,&itemf,&ratef,&stockf);
if(code==codef) {
printf("%d code is already in used, so it is invalid and not responded\n",code);
i++;
goto next;
}
}
fclose(fp3aa);
fp3a=fopen("temp of stores.txt","w");
fp3b=fopen("stores.txt","r");
if(strcmp(file_status,"old")==0){
while(!feof(fp3b)){
fscanf(fp3b," %d %s %f %d",&codef,&itemf,&ratef,&stockf);
if(count==0){
if(code<codef) { /*previously in markshhet data of file were only printed here both
because here it is ascending purpose but in marksheet just opposite or to maintain static we can
change '<' to '>'*/
fprintf(fp3a," %d %s %f %d",code,item,rate,stock);
fprintf(fp3a," %d %s %f %d",codef,itemf,ratef,stockf);/*we can directly print the
data from file too as if in a assecnding list a new number is added then the position of previous
value replaced by new number changes by +1 and similarly for others but here to others we do by
illogical way that is one by one*/
count++;
}
else {/*it is also reverse to marksehet*/
fprintf(fp3a," %d %s %f %d",codef,itemf,ratef,stockf);
}
}
else fprintf(fp3a," %d %s %f %d",codef,itemf,ratef,stockf);/*when the new data is
already insetred given by count=1 then just copying data from file to another file*/
} //while loop's terminal
if(count==0) fprintf(fp3a," %d %s %f %d",code,item,rate,stock); /*this statement is also
found in marksheet both work for same purpose; the statement executes when the new data has
no position in between or infront of data of file; here for ascending case and in marksheet for
descending*/
}
else {
fprintf(fp3a," %d %s %f %d",code,item,rate,stock);
strcpy(file_status,"old");
}
fclose(fp3a);
fclose(fp3b);
fp3c=fopen("stores.txt","w");
fp3d=fopen("temp of stores.txt","r");
while((c=getc(fp3d))!=EOF) {
putc(c,fp3c);
}
fclose(fp3c);
fclose(fp3d);
}
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
190
if(getch()){
goto main;
}
case 4:
printf("enter code of item to be deleted\t");
scanf("%d",&del);
fp4a=fopen("stores.txt","r");
fp4b=fopen("temp of stores.txt","w");
while(!feof(fp4a)){
fscanf(fp4a," %d %s %f %d",&codef,&itemf,&ratef,&stockf);
if(del==codef){ }
else
{
fprintf(fp4b," %d %s %f %d",codef,itemf,ratef,stockf);
}
}
fclose(fp4b);
fclose(fp4a);
fp4c=fopen("stores.txt","w");
fp4d=fopen("temp of stores.txt","r");
while((c=getc(fp4d))!=EOF) {
putc(c,fp4c);
}
fclose(fp4c);
fclose(fp4d);
if(getch()){
goto main;
}
case 5:
printf("Enter code\t");
scanf("%d",&na);
printf("Change it by\t");
scanf("%d",&new_stock);
fp5a=fopen("stores.txt","r");
fp5b=fopen("temp of stores.txt","w");
while(!feof(fp5a)){
fscanf(fp5a," %d %s %f %d",&code,&item,&price,&stock);
if(na==code){
fprintf(fp5b," %d %s %f %d",code,item,price,new_stock);
}
else
fprintf(fp5b," %d %s %f %d",code,item,price,stock);
}
fclose(fp5a);
fclose(fp5b);
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
191
fp5c=fopen("temp of stores.txt","r");
fp5d=fopen("stores.txt","w");
while(!feof(fp5c)){
fscanf(fp5c," %d %s %f %d",&code,&item,&price,&stock);
fprintf(fp5d," %d %s %f %d",code,item,price,stock);
}
fclose(fp5c);
fclose(fp5d);
if(getch()){
goto main;
}
case 6:
printf("Enter code\t");
scanf("%d",&naa);
printf("Add it by\t");
scanf("%d",&neew);
fp6a=fopen("stores.txt","r");
fp6b=fopen("temp of stores.txt","w");
while(!feof(fp6a)){
fscanf(fp6a," %d %s %f %d",&code,&item,&price,&stock);
if(naa==code){
neew=stock+neew;
fprintf(fp6b," %d %s %f %d",code,item,price,neew);
}
else
fprintf(fp6b," %d %s %f %d",code,item,price,stock);
}
fclose(fp6a);
fclose(fp6b);
fp6c=fopen("temp of stores.txt","r");
fp6d=fopen("stores.txt","w");
while(!feof(fp6c)){
fscanf(fp6c," %d %s %f %d",&code,&item,&price,&stock);
fprintf(fp6d," %d %s %f %d",code,item,price,stock);
}
fclose(fp6c);
fclose(fp6d);
if(getch()){
goto main;
}
case 7:
printf("Enter Code to be searched");
scanf("%d",&code_search);
fp7a=fopen("stores.txt","r");
printf("DATA STORED ABOUT ITEM YOUR SEARCHED\n\n");
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
192
printf("\n\n--------------------------------------------------------------\n");
printf("CODE\t");
printf("ITEM NAME\t\t");
printf("PRICE\t\t");
printf("STOCK\n\n");
while(!feof(fp7a))
{
fscanf(fp7a," %d %s %f %d",&code,&item,&price,&stock);
if(code==code_search){
fprintf(stdout,"\n%d\t%s\t\t%f\t\t%d\n",code,item,price,stock);
count++;
}
}
if(count==0){
printf("Sorry, your inquiry is not available !");
}
fclose(fp7a);
if (getch()){
goto main;
}
case 8:
printf("Enter Code_name to be searched");
scanf("%s",&item_search);
fp8a=fopen("stores.txt","r");
printf("DATA STORED ABOUT ITEM YOUR SEARCHED BEGINNING WITH NAME
\%s\\n\n",item_search);
printf("\n\n--------------------------------------------------------------\n");
printf("CODE\t");
printf("ITEM NAME\t\t");
printf("PRICE\t\t");
printf("STOCK\n\n");
while(!feof(fp8a))
{
fscanf(fp8a," %d %s %f %d",&code,&item,&price,&stock);
if(strncmp(item,item_search,strlen(item_search))==0){
fprintf(stdout,"\n%d\t%s\t\t%f\t\t%d\n",code,item,price,stock);
count++;
}
}
if(count==0){
printf("Sorry, your inquiry is not available !");
}
fclose(fp8a);
if (getch()){
goto main;
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
193
}
case 9:
printf("\n\n----------------------------------------\n");
printf("------------------THANKS FOR YOUR SERVICE-----%s",name);
printf("\n\n----------------------------------------\n");
if(getch()){
exit(1);
}
}
return 1;
}
PROGRAMMING ANALYSIS IN C
By Devendra Man Palikhe
194
/*THE END*/
*******
You can get soft copy of this book @ www.scribd.com/dpalikhe
This book is an open book with an analysis of C-
Programming. In market we can only get text books
based on syllabus and curriculum with definitions
and repeated ideas. This book is an example to show
that it is important to analyze topics rather than
following the old tracks. Studying is not only to be
based upon the books but also to modify it into
different forms with different ideas according to
time and situation, which is the main theme of
understanding the topic.