a. m. joshi...methods, question-answers etc. the students get good knowledge of language syntax,...

134
Programming A New Approach * Notes * A.M.Joshi [1] Notes, for private circulation only A. M. Joshi BE(Mech), M.Tech. (Ind. Engg) Lect in Mech. Engg. P.L.Govt. Polytechnic, Latur. 1. Introduction 2 2. Let’s Start…..! 3 3. Computer Languages 5 4. Bit & Byte 7 5. Variables & Expressions 11 6. Branching 22 7. Looping……! 40 8. Functions 64 9. Arrays 76 10. Pointers……! 92 11. Strings 97 12. File Handling 104 13. Preprocessor, Structures in C 112 14. Tips, Tricks and Traps 116 15. Re-view….! 120

Upload: others

Post on 31-Jul-2020

1 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [1]

N o t e s , f o r p r i v a t e c i r c u l a t i o n o n l y

A. M. Joshi

BE(Mech), M.Tech. (Ind. Engg)

Lect in Mech. Engg.

P.L.Govt. Polytechnic, Latur.

1. Introduction 2

2. Let’s Start…..! 3

3. Computer Languages 5

4. Bit & Byte 7

5. Variables & Expressions 11

6. Branching 22

7. Looping……! 40

8. Functions 64

9. Arrays 76

10. Pointers……! 92

11. Strings 97

12. File Handling 104

13. Preprocessor, Structures in C 112

14. Tips, Tricks and Traps 116

15. Re-view….! 120

Page 2: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [2]

IInnttrroodduuccttiioonn

Programming…..yet another book ? If the complete world is to be divided in to two groups, then it can be grouped in many

ways, like the Rich-poor, Male-female, Literate –illiterate etc. I think now one more type

has emerged : those who know computers and those who don‟t!

Today it is difficult to imagine the world without this word „Computer‟, and everyone

(including yourself) has become aware of this. The subjects of „Computer‟ are taught in

almost all educational institutes like engineering colleges, polytechnics, MCA, BCA,

BCS, ITI even in schools! Lot of students are learning computers. Obviously there are lot

of computer institutes, courses and books.

There are lot of books on computer programming also. But most of them are too difficult

to understand at least when you are quite new to the subject. May be this is because those

books are written by the experts for the experts. My intention is to write a book for a

beginner.

There are lot of confusions about programming. Like programming is „tooooo‟ difficult.

Programs should be remembered by heart. Developing a new program is work of a

genius, etc. But fortunately none of this is true! Just a small change in thought pattern

will make this very easy! No, I am not joking, after you go through this book you will

also agree.

Today education has become „pattern‟ oriented. More emphasis is given on memory. In

schools, even the „essays‟ are remembered and reproduced in exam. The subject of

computer programming is also taught in the same way. Exams of this subject again

concentrate on history of computers, types, advantages-disadvantages, rules, procedures,

methods, question-answers etc. The students get good knowledge of language syntax,

they “pass” the subject, may even get very good marks; but developing a new program

without any help still remains difficult for them!

I have seen some students who say I have learnt “this” language and now I am going to

join a course of “that” language; as if programming language is a language like German

or Russian language! Most of these fellows learn to write a program displaying “Hello!

World!” in many languages.

Actually rather than learning a programming “language”, it is more important to learn

programming “techniques”. For this, it is enough to learn one language. After that

learning new language is just to learn the syntax of any new language.

Second, if you are not going to write a program in a particular language in your entire

life, then why learn all such languages? There are lot of languages c, c++, basic, fortran,

Pascal etc. Of course, first of all you should learn one language to learn the programming

techniques.

From this point of view in this book more emphasis is given on programming logic rather

than language syntax. These logics will be there with you when you will learn C++, C#,

VB, dot-Net, Java, ASP, PHP, Javascript, vbscript or whatever.

The (English) language in this book is also deliberately kept very simple, so you will

concentrate more on „logic‟.

Page 3: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [3]

LLeett’’ss SSttaarrtt……....!! “Program” means a list of instructions (and a software is a set of programs). Lets take an

example to understand how to make a list of instructions. Suppose we want to develop a

program to “Cross a road”. Certainly for such a simple task it is really foolish to write a

“program”. But, to understand the importance of sequence and clarity of instructions, lets

do this.

1. Stand by (near) the road.

2. Look on (your) Right Hand Side.

3. (Ask yourself) Is any vehicle coming ?

4. If „Yes‟ then go to step 3.

5. else cross half part of the road.

6. Now Look on (your) Left Hand Side.

7. (Ask yourself) Is any vehicle coming ?

8. If „Yes‟ then go to step 7.

9. else cross (remaining) half part of the road.

10. Over!

Go through the instructions carefully. Remember, Computer is definitely going to

precisely follow the instructions. What will happen if sequence in these instructions is

changed? What will happen If an „animal‟ is coming instead of „vehicle‟?

Such mistakes (errors) in program are called a s „bug(s)‟, and finding and removing these

errors is called „debuggin‟.

Exercise :

Make a list of instructions for any „day to day‟ activity, for example make a list of

instructions for a salesman working in a shop. Remember these examples may look funny

at first sight, but they are very essential for developing „logical thinking‟.

Flow Chart “A picture tells more than what thousand words could say”. A graph for example quickly

gives the idea about the data written on many pages. A caricature tells lot about an event.

What if the instructions could be pictured in the same way?

A “Flow chart” is used to display list of instructions in graphical format. Considering the

importance of sequence of instructions (and mistakes due to that), it is (sometimes)

convenient to draw a flow chart of a program (list of instructions). Generally following

shapes are used in flow chart.

Instruction Symbol Example

Input /

Output

Get input from user or

Output some message

to user

Decision If …somehting ….

Page 4: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [4]

then take this route

…… otherwise….

Process Carry out some

calculations

Start / End

(Terminal) Start/ end of program

For example the following flow chart displays sequence of instructions in a program

which calculates percentage of marks and displays the result of a student.

No

start

Get marks from user

Calculate % marks p

stop

if p<40

Display “Fail” Display “Pass”

Yes

Page 5: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [5]

CCoommppuutteerr LLaanngguuaaggeess If we tell the instructions in the program of „Crossing the Road‟ in the previous chapter

to a human, then he would simply laugh at it. These instructions will appear very funny,

childish. At the same time a computer would never understand these. Not because they

are difficult or simple, but because the computer does not at all understand English

language!

Then the next question arises, Which language does the computer understand?

Basically computer is a machine. So it does not understand any language. Just like we

send signals to start and stop a machine by pressing a switch, computer also understand

the language of signals.

In case of a swith there can be two types of signals. On and Off. If we represent 1 for on

and 0 for off, then in a language of computer there will be only 1 and 0. Such a language

is called as machine language.

if we write a program using such a machine language, the computer will definitely

understand it. But, writing such a program and making changes in it would be almost

impossible.

To solve this problem, another language was developed which had commands for set of

instructions in machine language. The commands like „ADD‟, „MOV‟ are there in this

language. Writing program in this language became (relatively) easy. This language is

called „Assembly Level language‟.

But how the computer can understand „Assembly Level Language‟? Again a program

(software) was developed which would convert assembly level language program in to

machine language program. Such a (conversion) software program is called as

“assembler”.

Even though writing „Assembly level language‟ program became a bit easy, it was still

much „technical‟. Therefore for general purpose use, another type of languages were

developed. In these languages English Like commands were used. For example Input,

Print etc. Of course, writing a program became more easy. Such languages are called

„Higher Level Language(s)‟ or „HLL‟.

Again another program is required which should convert this program written in HLL to

a program in machine language. (So that computer can understand it). Such a

(conversion) software program is called as „Compiler‟.

Different HLLs were developed for different purposes like cobol was developed for

business work., BASIC for beginners, ForTran for scientists, Pascal, C etc. Out of these C

language became popular because of some of its features.

print, input…. COMPILER 10101001101

11

ADD, MOV,

….

ASSEMBL

ER 1010 1001

Page 6: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [6]

After C language many languages were developed C++, C#, VB,VC, Java. To learn all or

some of these it is better to start with C language.

These are all language processors, that is they convert the english like language to

machine language. Some of them are compiler and some are interpreter but basically they

help to bridge the gap between a human and a machine.

One more thing I would like to make clear, If you just want to USE computer, it is not

necessary to learn any of the above mentioned languages. Like to drive a vehicle, you

need not know how engine works.

If you want to use the computer for a particular task, there are lot of (thousands of)

software available in market. Following is a very small list of these.

Task Type Software

Tables, Calculations,

graphs, data analysis

Spread Sheet Excel, Lotus123

Letter Typing, DTP,

Report Making

Word Processor Word

Presentation,

Demonstartion,

Teaching

Presentation Power Point

Drafting, Designing CAD, 3D Modelling,

CAM

Auto CAD, UG, Pro-

E, CATIA,

MasterCAM

Data management DBMS Access, Oracle,

Sybase, Ingress, SQL

Server

Artistic design, Book

Printing

DTP Page maker, Corel

Animation Animation Macromedia Director

But suppose you want to use computer for a specific task for which software is not

available, that time you can develop your own program (software). Apart from this,

„programming logic‟ will help you almost every where in life.

Page 7: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [7]

BBiitt && BByyttee We all know that today computers can store text, photos, songs, video etc. Whatever may

be the data it is basically stored in the form of 1 and 0. Different programs are used to

convert that pictures, songs etc to 1 and 0 and vice versa.

On hard disk/ floppy disk, very small N and S magnetic poles are created to store 1 and 0.

On a CD small peaks and valleys are created to store 1 and 0.

It would be quite interesting to know some more about this 1 and 0, also it is essential for

a C language programmer.

Bit – (Binary Digit) : A Bit can store a signal, either On (1) or off (0). You can think of

an electric switch which will be either off or on, not half way on or off.

If we use a single bit we can store only two types of signals, for example yes or no.

Using such two bits, it would be possible to store four types of signals (four

combinations). Lets take a funny example. Suppose two friends are living in two adjacent

rooms, and we are able to see the lights from some distance. Just by watching which

bulbs are on, we can understand four different things (without the use of words) :

Both are sleeping -Bits : 0 0

First is awake and second is sleeping. -Bits : 1 0

First is sleeping and second is awake. –Bits : 0 1

Both are awake. –Bits : 1 1

Using three bits there will be eight combinations. 000, 001, 010, 011, 100, 101, 110, 111.

That is, using such three bits we can store / send 8 types of signals.

In general, using „n‟ bits, we can store or send 2n signals.

If such 8 bits are taken together, then we can store / send 28 = 256 signals. In this group

of 8 bits some will be on (1) and some off (0). Like 00000000, 00000001, 00000010,

…… , 11111111. (You may visualize 8 friends living in a hostel in adjacent rooms!)

Byte: A group of 8 bits is collectively called as a „Byte‟. That means there will be 8 bits

in a byte, each of them can store 1 or 0.

There can be 256 combinations of 0 and 1 on different bits. That is, using this one Byte

we can store 256 bit patterns, and hence numbers between 0 to 255. Following table will

make it clear.

Bit Pattern Pattern Number

0000 0000 0

0000 0001 1

0000 0010 2

……. …

1111 1111 255

Use of byte to store a number :

Page 8: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [8]

Extending the same logic, if we use two bytes to store a number, there will be 65536

combinations! That means we can store a number between 0 and 65535.

Out of these 16 bits, if leftmost is utilized to store sign( + or -), then using these two

bytes, we can store a number between -32768 to 32767.

This number stored using two bytes, is called as integer type data (or int or short int or

simply short) in C language.

For example, suppose you want to store your age (which is suppose 20) in computer, then

you can use int data type. And when you will store it, internally it will be stored using

combinations of 1and 0 of 16 bits.

If you want to store a number bigger than this (32767), then four bytes are used. This is

called as long integer data type (or long int, or simply long) in C language.

To store a number smaller than 32767, either a short int or even a long integer can be

used. But short int would be proper. If long int is used memory utilization would not be

effective.

We shall learn how to use these short, long data types while writing C programs later.

Using these short int, long int data types we can store integer numbers. That is, the

numbers which are full numbers without fraction (no decimal).

In C language numbers with decimal (fraction) are called „float‟. It takes four bytes to

store such a number. The float data type can store a number between -3.4 x 10 38 and

+3.4x10 38. To store even bigger number with decimal, „double‟ data type is used. This

„double‟ data type needs 8 bytes to store a number.

When short int is enough then long int should not be used. Similarly when „float‟ is

enough then „double‟ should not be used.

Use of byte to store „Alphabets‟ (Names/letters etc.) :

We have seen using 8 bits, 256 combinations of 1 and 0 can be created. If we assign a

character to each of these combinations, computer can understand (store and display) 256

types of characters (alphabets, letters, signs).

The (serial) number of these 8 bit patterns is called ASCII-code, and the character

associated with that bit pattern is called as ASCII character. For example ASCII code

associated with character „A‟ is 65.

Pattern Number Character

0000 0000 0

0000 0001 1

0100 0001 65 A

66 B

90 Z

97 A

Page 9: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [9]

98 B

122 Z

1111 1111 255

Using this bit pattern– ASCII code- character association; following characters are

associated with these 256 bit patterns:

26 Uppercase (Capital letters) A ..to Z,

26 Lower case (small letters) a…to…z,

0 to 9 (10) numbers

Characters like !@* ? + etc.

Some more special characters like space, new line, end of file etc.

In short if you store a word “ANT” in memory of computer, it will be stored in the form

of 3 x 8 = 24 bits, some bits holding 0 and some holding 1.

In C language to store characters, „char‟ data type is used. Each character takes one byte.

For example to store a name like „Raju‟, 4 bytes are required.

This same „char‟ data type can also be used for storing a number. But in that case it can

store numbers between 0 to 255 (ASCII code number or pattern number).

Data types and their use will be discussed at length later, right now this much only !

Top to bottom a new approach….! In our child hood we all have heard the story of a fool (“sangkamya bandu”), who

literally follows every word and gets into trouble. A Computer also behaves like that.

Computers do not have common sense. Whatever you tell, computer will do that and

what you forget to tell, computer will never do that (how much simple it may be)!

Basically there are two approaches of learning a language. In the first, we learn the

words, their meaning, grammar, rules, exceptions etc. Then start using that language.

Generally we try to learn the English language like this.

In the second approach, we take very small information and “START” using that. Slowly

we learn the rules, etiquettes etc. In this method, we learn new things when they are

required. Sometimes we learn from our mistakes! Generally we learn our mother-tongue

like this.

Most of the computer experts won‟t agree but my experience is that it is better to follow

second approach, even for learning C programming. Of course we are going to learn all

those rules, grammar, syntax and all that, but Step By Step. In C language there are lot of

rules, syntax and those appear very difficult at first sight. So let‟s learn few things first,

and start.

But even before that, let‟s concentrate on logic. Let‟s select a „task‟ and try to break it up.

We can‟t take a task like „Crossing the road‟, as the computer on your desk can not walk!

So let‟s take some task which will help us to learn programming.

Page 10: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [10]

Suppose we want to find sum (total) of marks obtained in three different subjects. Using a

computer instead of calculator for such simple task itself is foolishness. But for the sake

of learning, let‟s do it. First let‟s clearly define our task.

Task : Add three numbers and show the result.

Wait, wait one more thing, here we are going to use „Last thing first‟ approach. Meaning

first we are going to decide what (output) exactly is required at the end. What should be

done for that. Then what should be done for this and at the end what should be done at

first.

Let‟s make one more thing clear. We are NOT going to find total of marks in three

subjects (Then ..?). We are going to write a program which will do that. This program

(list of instructions) we are going to give to the computer, and computer will do that task.

Programmer Computer User

Page 11: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [11]

VVaarriiaabblleess && EExxpprreessssiioonnss What is variable ? Vary means „change‟, and variable = able to vary. In programming a

variable works like a container (a pot). The pot will remain same its content may change.

For example in algebra and programming when we say a=97, we mean that number

(value) 97 is stored inside the variable a.

a 97

In this example an integer 97 is stored in variable „a‟. {You can visualize pot whose name

is „a‟ and contains 97 objects}

In C language you should declare a variable before using it. For example to store integer

in a variable you should declare so that computer can reserve two bytes. Similarly all

types of variables like float, caracter etc. must be first declared.

For example to declare variables a as integer type, b as float and c as character type, write

following lines:

int a;

float b;

char c;

Developing the logic:

Before we write a program let‟s first have some „self talk‟. Which will help us to develop

the logic of program..

Finally what the user wants ? Sum of three numbers (on screen/print).

What to do for that ? Display on screen the Sum.

What to do for that ? Sum up three numbers.

What to do for that ? Get three numbers from user.

What to do for that ? Ask the user to type three numbers.

Lets learn ONLY those commands which are required for all these steps. Go through the

following table VERY CAREFULLY. Details about these commands/functions will be

learnt later, but for today concentrate on this much only! In K.G. or first standard you are

told to write 1, 2 like this, what is 1, what is 2, and what is counting, maths etc and all

that comes much later !

Task Command / function Remarks

To show some

message to the user printf(“..message..”);

For example to show a message

“How are you?” on screen type:

printf(“How Are You ?”);

Declaring a

Variable

int a,x;

float y;

char z;

You should declare a variable before

using.

Getting some data

from user and store scanf();

Computer will stop and wait so that

user will enter data (through

Page 12: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [12]

in a variable. keyboard)

scanf(“%d”,&x);

Number entered by user will be

stored in integer variable „x‟

%d for integer

scanf(“%f”,&y);

Number entered by user will be

stored in float variable „y‟ %f for

float

scanf(“%c”,&z);

Number entered by user will be

stored in float variable „z‟

%c for char

Display the

contents of a

variable to the user

printf(“%d”,x);

printf(“%f”,y);

printf(“%c”,z);

Displays content of variable on

screen for example if x=7,

y=5.9,z=”B” then 7, 5.9 and „B‟ will

be displayed on screen

Display the

contents as well as

message of a

variable to the user

printf(“…message …

%d….message…. ”,x);

For example following line will

display “Length=9cms” on screen If

L=9:

printf (“ length = %d cms.”, L);

%d, %f, %c are called as format specifiers. They specify the format of input so that

computer can understand that it is integer, float and character respectively. More about

this will be discussed later.

In every program, there will be a „main‟ function. More about this will be discussed in

details later. Right now lets just „remember‟ that the lines of the program we are going to

write should be typed between the curly braces { and }. In C language, at the end of

(almost) each line there is semicolon “;” .

The general format of a program in C language will be like this:

main( )

{

…….All the lines in the program.

}

Now lets write the program :

main( )

{

int a,b,c,t;

printf(“Please Enter the marks of three subjects “);

scanf(“%d”,&a);

scanf(“%d”,&b);

scanf(“%d”,&c);

t=a+b+c;

printf(“Total of the marks of three subjects : “);

Page 13: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [13]

printf(“%d”,t);

}

In the above program, the instructions in the table are used. The first line of this program

[ int a,b,c,t; ] declares variable a,b,c and t as integer variables, so that four places in the

memory will be reserved, which can store integer data.

The second line in the program will display “Please Enter the marks of three subjects” on

screen, so that user will know that now data is to be entered.

At the third line, [ scanf(“%d”,&a); ] computer will wait. Computer will stop everything

and wait foruser input. Then the number typed (enterd) by user will be stored in variable

„a‟. Suppose the user types 49, then this 49 will be stored in variable „a‟.

In the same way next two lines will store numbers enterd by user in variables b and c.

Next line [t = a + b + c ;] will sum the numbers in a,b and c and store that sum in variable

t. In these types of lines, right hand side (a+b+c) is first evaluated, and stored in variable

on left hand side (t). This is assignment statement.

Last two lines will show “Total of the marks of three subjects :” and the value (number)

in variable t.

Please Enter the marks of three subjects

50

60

70

Total of the marks of three subjects : 180

Running a program:

Once you write the program on paper, to run it on PC, follow these steps:

First of all start the C language compiler. If you are running it on windows, click on the

corresponding icon. Or go to DOS prompt and type :

CD\TC <Enter>

TC <Enter>

Then compiler will start.

In the editor (place to write the new program) type down the program. Then Save it. Then

to run the program, go to Compile/Run menu.

Note:

If you see that a program is already there in editor (typed by someone else), then click on

Window -> Close.

Click on File->New to start a new file (program).

Short cut keys Alt+F9 (Compile) and Ctrl+F9 (Run) may be used.

Making it simple ...! Now you have tried to run the first program on PC. What will happen if your friend opens

this program, or you yourself open it after six months? He (or you) will first wonder what

for this program is? What for these variable a,b,c and t have been used ? etc. if he gets

answers to theses questions there only, then he can quickly understand the program.

Page 14: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [14]

To avoid such problems, let‟s make certain rules and follow them. These simple rules

will help you and others too. This will be more important particularly if you are working

on a project where more than one persons are working.

Giving a meaningful name to the program file: For example if you name the above

program as prog1, ABC, XYZ, Rajesh etc., then it does not tell anything about what is

this program for. Instead the name of the file should carry some meaning (say

“totmarks”).

Writing some information about the program, logic, variables etc in the program itself:

These pieces of information are called „comments‟. The comments should be written

between /* ……and ….. */. The C compiler skips these comments, because these

comments are for us, not for the computer. But if you forget to type /* and */ then

compiler will try to find meaning for it and will give errors. The following lines at

appropriate place in the program will make the program more readable for human.

/* Program for Adding marks of 3 subjects */

/* t - variable to store total marks */

Giving proper names to the variables: Instead of a,b,c, t it would be good idea to use

names like sub1, sub2, sub3, total etc. The names of the variables should be self-

explanatory. Habit of using handy variable names like x, i everywhere in program is bad

practice.

Write clrscr( ); at the beginning of program: This is a command (actually function) in C,

which clears screen. What ever is there on screen (may be the output of the previous

program), is first cleared.

Write getch(); as the last line of the program: This is “get-character” functions. When

executing this line, computer will simply wait for a keystroke from user. Until the user

presses any key, the computer waits. This helps us to read the output of the program. If

this line is not included, the user does not get time to read the output of the program.

Use \n in every printf ( );: This „\n‟ is a new-line-character in C language. If this is added

at the start of printf ( ); then the message is shown on the next line, which makes it more

readable. For example : printf(“\n Please Enter radius of circle”);

Overall structure of the program will be as follows :

/* Program for … …. … … */

main()

{

clrscr();

…….all lines in the program….

getch();

}

If you are using c++ compiler (to run c programs) then following changes should be

made:

#include <stdio.h>

#include <conio.h>

Page 15: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [15]

/* Program for … …. … … */

void main(void)

{

clrscr();

…….all lines in the program….

getch();

}

We shall learn what is #include, void in due course of time.

Expression Evaluation In algebra when we say x = 5 we mean the value of x is 5. But in programming when we

say x = 5; then we are asking the computer to store value 5 in variable x. That is „=‟ is an

assignment operator. Now if the variable is declared integer, then value 5 will be stored

in it. Where as if x is declared float, then value 5.0 will be stored in it.

If the line in a program is x=5.9; and x is declared float then number 5.9 will be stored in

it, but if it is declared as integer, then the decimal fraction part will be removed, and

value 5 will be stored in it. Note that value is not rounded off, it is truncated.

When there is line like t= a + b + c ; that time first computer will calculate the value of

right hand side and then that value will be assigned to the left hand side. There are simple

rules in programming for evaluating (finding the value) of right hand side. Can you recall

BODMAS (Bracket-Of-Division-Multiplication-Addition-Subtraction) we learnt long

back in schools? There are similar priority rules in C language. This priority of operators

is called 'hierarchy':

First the expression in bracket.

Then Multiplication and Division

Then Addition and Subtraction

Out of these if there are two operators of same priority, then solve it Left to Right. More

about the other operators and their priority will be discussed later.

In C language + - * / are used for addition, subtraction, multiplication and division

respectively. But ^ is not used for raised to (power). Here we have to use pow( ) function.

For example, to write x=y3 we should type x = pow(y,3);. Similarly to find square root

we have to use sqrt( ); function. For example to write y=x we have to type y=sqrt(x);.

% is yet another C language operator. This operator finds remainder after division. For

example 15 % 3 will be evaluated 0. 16%3 will be 1, 17%3 will be 2. Again 18%3 will be

zero.

Expression Value stored

in x

x = 4 + 5 * 2 ; 14

x = (4 + 5) * 2 ; 18

X= 10 % 3 1

X= 10 % 2 0

Page 16: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [16]

In addition, subtraction, multiplication, division of two numbers (or variables) if any one

is float, then the result will be float. If both are integer then result will be integer.

Integer * integer => Integer

Integer * float => float

Integer / integer => Integer

Integer / float => float

Float * float => float

Float / float => float

Considering these rules for expression evaluation, now let‟s re-write our first program in

C language. In addition let‟s change the program so that it finds average (percentage) too.

Program 1. Write down a C program which will find average (Percentage) of marks in

three subjects.

#include <stdio.h>

#include <conio.h>

main()

{

/* Program for finding out average of marks of 3 subjects */

clrscr();

int sub1,sub2,sub3,total;

float avg;

printf(“Please Enter the marks of three subjects “);

scanf(“%d”,&sub1);

scanf(“%d”,&sub2);

scanf(“%d”,&sub3);

total=sub1+ sub2+ sub3;

avg= (sub1+ sub2+ sub3) / 3.0 ;

printf(“Total of the marks of three subjects : “);

printf(“%d”,total);

printf(“Average of the marks of three subjects : “);

printf(“%f”,avg);

getch();

}

In the above program, what would happen if bracket ( ) is not used in line number 9

[avg= (sub1+ sub2+ sub3) / 3.0 ;] ?

The compiler would first divide sub3 by 3 and then add sub1 and sub2 to that!

Similarly what would happen if instead of 3.0 if 3 is used ?

In that case it would be integer division and the answer would be integer. For example,

suppose the marks are 60, 60 and 62. Then addition would be 182, and division 182/3

would be 60 instead of 60.666 (because of integer division). Now even if that is stored in

float variable „t‟ then it would be 60.0 and not 60.666 !

Page 17: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [17]

Another method of avoiding integer division is “type cast”. In type casting one type of

data is temporarily converted (casted) to another type. For example (int) x means integer

equivalent of x. Similarly (float) y is float equivalent of y.

Therefore in the line number 9 of the above program we could cast the total to flaot and

divide it by integer 3. [avg= ( (float) (sub1+ sub2+ sub3) ) / 3 ;]

Skip this following program (no 2) in the first reading.

The following program helps to clearly understand the idea of variable.

Program 2. Write down a „C‟ program which will ask two numbers to the user, store

them in two variables a and b then interchange their values.

Here we are going to write a program which should take two numbers from the user store

them in two variables and then interchange the contents of those two variables. Suppose

user has typed the values 5 and 7 and they are stored in variables a and b, respectively.

a 5 b 7

Now it should be

a 7 b 5

At first sight the program appears too simple just two statements a=b; and b=a; will

interchange the contents, but….

main( )

{

int a,b;

printf(“Please enter two numbers”);

scanf(“%d%d”, &a,&b);

printf(“Before interchange a=%d b=%d”,a,b);

a=b;

b=a;

printf(“After interchange a=%d b=%d”,a,b);

getch();

}

Let‟s visualize (imagine) what will happen at every step.

First two numbers entered by user will be stored in two variables a and b. Suppose user

has type 5 and 7.

a 5 b 7

The next line a=b; will store the value of b (7) in variable a.

a 7 b 7

The next line b=a; will store the value of a (now 7) in the variable b! That means the

value 5 in variable a has lost!

This is somewhat like interchanging the contents of the two pots. Here a third empty pot

is required. In the program also, we need to take a new variable (of course we must

declare it like int c;). Now the whatever is there in first pot (a) should be kept safely in

this new pot (c=a;). Contents of the second pot (b) are now transferred to first pot (a=b;).

Page 18: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [18]

In the last step, transfer the contents of new pot (c) to second pot (b), ie. (b=c;). Just look

at the following figure:

Therefore the program should be changed as follows:

/* Interchange contents of two variables */

#include <stdio.h>

#include <conio.h>

main()

{

clrscr();

int a,b,c;

printf(“Please enter two numbers”);

scanf(“%d%d”, &a,&b);

printf(“Before interchange a=%d b=%d”,a,b);

c=a ;

a=b ;

b=c ;

printf(“After interchange a=%d b=%d”,a,b);

getch();

}

In the above program the variables are written in cycle, starting from c. That is c=a; a=b;

and b=c;. The cycle can be run in reverse order (again starting from c). That is c=b; then

b=a; and last a=c;.

Program 3. Write down a program which will find simple interest on given principle at

given rate of interest for a given period.

Logic :

Finally we want interst.

To calculate this we have the formula i= p x n x r /100

That means we should get the values of p,n,r from user. [3 scanf ].

To do this some appropriate message to user like “Please enter …”

Before that variables should be declared. (float).

/* Program Interest calculation (Simple Interst) */

c

b

a

Page 19: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [19]

#include <stdio.h>

#include <conio.h>

void main(void)

{

clrscr();

float p,n,r,i;

printf("\n Please enter Principle, Rate of Int, Period ");

printf("\n Principle ");

scanf("%f",&p);

printf("\n Period years ");

scanf("%f",&n);

printf("\n Rate of Int");

scanf("%f",&r);

i=p*n*r/100;

printf("\n Interst = %f",i);

getch();

}

Program 4. Write down a program which will find compound interest on given principle

at given rate of interest for a given period.

Logic :

Logic will be same, only formula will change

Formula is i = p x (1 + r/100)n –p

/* Program Interest calculation (Compound Interst) */

#include <stdio.h>

#include <conio.h>

#include <math.h>

main( )

{

clrscr();

float p,n,r,i;

printf("\n Pl. enter Principle,Rate of Int,Period");

printf("\n Principle ");

scanf("%f",&p);

printf("\n Period years ");

scanf("%f",&n);

printf("\n Rate of Int");

scanf("%f",&r);

i=p*pow((1+r/100),n)-p;

Page 20: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [20]

printf("\n Interst = %f",i);

getch();

}

Note: To use the function pow(); the line #include <math.h> should be added.

Program 5. Write down a program which will display the ascii code and corresponding

character of a given number.

In the last chapter we have seen that corresponding to a bit pattern, there is a number

(ASCII code), and a character associated with that bit pattern.

Pattern Number Character

0100 0001 65 A

To display a number we have seen that %d format is used in printf, and to display a

character we use %c. If the same number is displayed with %d and %c, we get the Ascii

code and the character associated with it.

Finally we want ascii code and corresponding character.

To display this lets use printf with %d and %c format specifiers.

The number for which the ascii code and character are required should be asked to user

[scanf].

Again some appropriate message to user like “Please enter num bet 0 to 255…”

At the beginning the [integer] variable to hold this number should be declared.

/* Program: ASCII code and character */

#include <stdio.h>

#include <conio.h>

int main(void)

{

clrscr();

int n;

printf("Enter a number between 0 to 255 ");

scanf("%d",&n);

printf("\n The Ascii character for %d is %c ",n,n);

getch();

}

You may skip the following program (no 6) in the first reading.

Program 6. Write down a program to interchange contents of two variables without

using third variable.

Here we want to interchange the contents of two variables without using the third

variable. The logic of this program is quite different. To understand this logic, you should

Page 21: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [21]

have some experience of developing programs; therefore it is recommended to skip it in

first reading.

First number (a) is added to second. (Second becomes sum of two)

From this, if first (a) is subtracted we get second, and if second is subtracted we get first.

/* Program: swap contents of two variables w/o using third variable */

#include <stdio.h>

#include <conio.h>

int main(void)

{

clrscr();

int a=5,b=7;

printf("\na=%d b=%d",a,b);

b=a+b; /* b=12 */

a=b-a; /* a=7 */

b=b-a; /* b=5 */

printf("\na=%d b=%d",a,b);

getch();

}

Output:

a=5 b=7

a=7 b=5

Exercise :

Write down a „C‟ program to find area, circumference of a circle when its radius

is entered.

Write down a „C‟ program to find area, perimeter of a rectangle when its length

and width are entered.

Write down a „C‟ program to convert temp from oF to oC . [ c= (f-32) * 5 /9 ]

Write down a „C‟ program to convert distance from Miles to Km

Find Gross salary when basic is enterd. Gross Salary = Basic + HRA + DA.

(Given HRA=15% of basic, DA=25% of basic)

Write down a „C‟ program to find equivalet single resistance, when two

resistances are connected in parallel.

Page 22: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [22]

BBrraanncchhiinngg

if statement : In previous chapters we saw how to write a program to do a simple calculation work. The

instructions in these programs were straight sequential. More often, the calculations

require some decision. For example :

If the total purchase is worth more than 2000, customer will get discount of Rs 100.

If the percentage of marks is more than 60, print „First class‟ in result column.

If the income is less than 1 lac, no income tax, if the income isabove 1 lac, tax is 10 % of

income above 1 lac.

This is written in C language (syntax) as follows:

if (condition)

{

…..Lines to follow if condition is TRUE …

}

If the given condition is true then only the commands in the block are executed,

otherwise the compiler skips these lines. That means, the program control will enter the

block only if the condition is true.

For example, Suppose we want to give a discount of Rs100 when the total_cost is greater

than 2000; it is written in C as follows:

if (Total_cost > 2000)

{

No

if tot_cost >

2000

Yes

Discount =100

Page 23: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [23]

discount = 100;

Total_cost = Total_cost – discount;

}

Following operators are used in C language in „condition‟ part of the statement:

> Greater Than

< Less Than

>= Greater Than or equal to

<= Less Than or equal to

= = Equal to

!= Not equal to

&& AND

|| OR

Note : = = is used in if statement, for example if(x= =10). Here we mean „if x is equal to

10, then do something. Single = is assignment operator. When we say x=10; we mean

assign value 10 to variable x.

We can join two condition by and/ or operator. Suppose in an exam the passing marks are

40, but a grace of maximum 3 marks is given. In that case the marks obtained should be

written 40 even if the candidate gets 37,28 or 39 marks. This can be written as follows:

if (marks>=37 && marks<40)

{

marks = 40;

}

printf(“%d”, marks);

if …. else statement:

No

if p<40

Display “Fail” Display “Pass”

Yes

Page 24: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [24]

But sometimes, we need to tell what to do when the condition is true, and what to do

otherwise. In such situations, following statement is available.

if (condition)

{

…..Lines to follow if condition is TRUE …

}

else

{

…..Lines to follow if condition is FALSE …

}

For example the result is to be displayed as „Fail‟ if the marks obtained are less than 40,

and „Pass‟ otherwise (i.e. when marks are more than 40).

if (marks<40)

{

printf (“Fail”);

}

else

{

printf (“Pass”);

}

When there is only one line in the block, the curly braces { } are optional. (No need to

use curly braces when ther is single line under if or else ).Therefore the above example

could be written as follows:

if (marks<40)

printf (“Fail”);

else

printf (“Pass”);

if … else .. if ladder There are situations, when there will be more branches, like :

If …..x….. is there then do …this…..

Else If …..y….. is there then do …this…..

Else If …..z….. is there then do …this…..

In short there are multiple branches which are mutually exclusive, (meaning only one of

them can be true ). For example, suppose we want to display the result and the result

should be either fail, II class, I class, Distinction:

If the marks obtained are less than 40 then display “Fail”

Else if marks obtained are less than 60 then display “II class”

Else if marks obtained are less than 75 then display “I class”

Else display “Distinction”

Page 25: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [25]

if (marks < 40)

printf (“ Fail ”);

else if (marks <60 )

printf (“ II Class ”);

else if (marks <75 )

printf (“I Class ”);

else

printf (“Distinction”);

Tips :

Note down : there is no semicolon after if (condition)

When there is a single line (instruction/command) in the block of if or else then there is

no need to type { }

When there are more than one conditions, then these can be joined using AND/ OR. For

example (marks>40 && marks <60)

We can put an if…else inside an if block or else block. This is called as nesting.

The if … else .. if ladder described above is actually an example of nesting.

if (marks < 40)

printf (“ Fail ”);

else

if (marks <60 )

printf (“ Il Class ”);

else

if (marks <75 )

printf (“I Class ”);

else

printf (“Distinction”);

Only the next if (inside the else block) is written on the same line. This program can be

simplified by using AND operator :

if (marks < 40)

printf (“ Fail ”);

if (marks >= 40 && marks <60)

printf (“ Il Class ”);

if (marks >= 60 && marks <75)

printf (“I Class ”);

if (marks >= 75)

printf (“Distinction”);

Page 26: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [26]

Note that, in the first method when we write “if (marks<60)”that time we do not (and

need not) specify “marks>=40”. The reasons is, we use “else” in the first method.

Program 7. Write down a C language program which will accept a number and print

whether that is odd or even.

Logic:

Finally we want the answer “Odd” or “Even” on screen.

These message “Odd” should be displayed when the (given) number is NOT

divisible by 2, and “Even” when it is divisible by 2.

To check the divisibility we have % operator, which gives remainder after

division.

When [if] the remainde is zero it is even, otherwise [else] it is odd.

Remained can be found using statement : r = n % 2;

Number „n‟ will be entered by user. [scanf( )]

/* Program to check Even or Odd */

#include <stdio.h>

#include <conio.h>

main()

{

int n,r; /* n- given number r- remainder*/

printf(“Please Enter a number :”);

scanf(“%d”,&n);

r= n % 2;

/*Note no “;” also note double = = is equal to*/

if (r = = 0)

printf(“Number is even “);

else

printf(“Number is odd “);

getch();

}

Program 8. Write down a program which will accept an year- number and print

whether that year is Leap or not.

The leap year comes once in every four years. When the „year‟ number is divisible by

four it is a leap year, else not. Logic of this program is quite like the previous program.

Instead of „Even‟ here we have to display „Leap Year‟, when the remainder after division

is 0. Note that the remainder in this program would be either 0,1,2 or 3. Try to write (and

run) this program first.

But, in the above logic there is a „bug‟. This logic (checking divisibility by 4) is

applicable only to the years when the last two digits are non-zero. For example when the

year is not like 1600,1700,1800,1900,2000,2100.

Page 27: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [27]

The criteria for these (century) years is „divisible by 400‟. That means among 1600,

1700,… ,2100; only 1600 and 2000 are leap years.

So lets change the program:

Logic:

First we are going to decide whether it is „century‟ year.

[if] the year is divisible by 100,

„Leap‟ if divisible by 400

Otherwise „Not Leap‟

[else] (the year is NOT divisible by 100)

„Leap‟ if divisible by 4

Otherwise „Not Leap‟

The program would look like this :

/* Program for Leap Year */

#include <stdio.h>

#include <conio.h>

main()

{

int y; /* y- given year */

printf(“Please Enter a year :”);

scanf(“%d”,&n);

if (y%100 == 0) /* Century Year like 1900,2000*/

{

if(y%400 ==0) /* Year like 1600,2000,2400*/

printf(“Leap Year “);

else /* Year like 1900,2100*/

printf(“Not a Leap Year“);

}

else /* Non Century Year like 2001,2004*/

{

if(y%4 ==0) /* Year like 1996,2004*/

printf(“Leap Year “);

else /* Non Century Year like 2001,2007*/

printf(“Not a Leap Year“);

}

getch();

}

Note that we are using „nesting‟ here. Proper „indentation‟ (TABs) will make the program

readable. For example the „else‟ of „if‟ should be at the same level. The nested if/else

should be typed with „TABs‟.

Page 28: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [28]

This program can be made still compact (and little complex) using logical AND/OR

operators. The logic for this would be:

The year is Leap if divisible by 400, OR

If not divisible by 100 AND divisible by 4.

In C syntax :

if ( (y%400 ==0) || (y%100!=0 && y%4==0) )

printf(“Leap Year “);

else

printf(“Not a Leap Year “);

Program 9. Write down a program to find the biggest of three numbers.

Though this „task‟ of finding the biggest of three numbers is too simple, asking the

computer to do so, is critical. Many algorithm can be used for this program.

Method 1 : In this algorithm, nested if is used. In the „first‟ if there is one „if-else‟ and in

the „else‟ part of it (first if), another „if-else‟ is used.

Logic:

Compare „a‟ and „b‟

If „a‟ is bigger

Compare „a‟ and „c‟

Display the bigger of „a‟ and „c‟

Else (meaning : „a‟ is not bigger, „b‟ is bigger)

Compare „b‟ and „c‟

Display the bigger of „b‟ and „c‟

The (part of) program would be like this :

if(a>b) /* a > b Means a is Bigger of a & b */

if(a>c) /* a > b and a> c also */

printf(“%d”,a);

else /* a > b but a < c Means C is biggest */

printf(“%d”,c);

else /* b>a Means b is Bigger of a & b */

if(b>c) /* b > a and b>c also */

printf(“%d”,b);

else /* b > a but b < c Means C is biggest */

printf(“%d”,c);

Method 2 : Instead of nesting we can use AND (&&). If „a‟ is bigger than „b‟ and „c‟ it is

biggest. Like wise „b (or) c‟ bigger than remaing two, that is biggest.

if(a>b && a>c)

printf(“%d”,a);

if(b>a && b>c)

Page 29: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [29]

printf(“%d”,b);

if(c>a && c>b)

printf(“%d”,c);

Note that there is a bug in the above logic. When all a,b and c are equal the program

would not display anything ! Just think how can we remove the bug ?

Both of the above algotihms would be too complex when we want to find biggest among

the 4,5… „n‟ numbers. Developing such a complex program for this simple task would be

like „using a gun for killing a rat!‟.

Method 3 : Self replacement technique algorithm. This method is pretty simple one. In

this method the technique used is similar to one used by us (human).

Suppose someone tells us three numbers one-by-one (say 4,7,and 3). What we do? We

keep the first number (4) in mind. After that when the second number (7) is told, we

replace that number in mind and concentrate on this (7). Next, when the third number (3)

is told, we simply ignore it! Lets summarize :

First take a variable to store the answer (biggest number). Lets name it „m‟

Store the first number in it [m=a;]

Then take the second (next) number. If this is bigger than the previous, put this in the

variable „m‟. But if this second (next) number is smaller than the previous, just ignore it.

That is, if (b>m) then m=b;

Same process is to be repeated for the third number. That is, if (c>m) then m=c;

Finally „m‟ will contain the biggest.

/* Biggest of three numbers */

#include <stdio.h>

#include <conio.h>

main()

{

m=a;

if(b>m)

m=b;

if(c>m)

m=c;

printf(“%d”,m);

getch();

}

This algorithm is quite easy, also it can be easily extended for finding biggest of four,

five…or more numbers.

Program 10. Write down a program which will find square roots of a quadratic equation.

Page 30: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [30]

Quadratic equation is of the form ax² + bx + c = 0. For example 2x² + 7x -9= 0. Here,

a=2, b=7, c= -9. Now we want to find the value(s) of x, which will give “ax² + bx + c”

equal to zero. These values are called “roots of the quadratic equation”. These roots are

found using the following formula:

x1= -b ± (b² - 4ac)

2a

We already know the rules for writing this in C language:

x1 = (-b + sqrt (b*b – 4*a*c) ) / (2*a) ;

x2 = (-b - sqrt (b*b – 4*a*c) ) / (2*a) ;

Program should have the statements for the following:

Getting three values (a,b, and c) form the user.[scanf]

Calculating the values of x1 and x2 as above.

Displaying these valuse. [printf]

If we write the program like this, the program will work well. But it will give error in

certain events. For example, when the value of (b*b-4*a*c) is negative, the program will

give error. The reason is, square root of a negative number can not be calculated. (It is

imaginary number).

In these situation (when the value of “b*b-4*a*c” is negative), the program should

display “ Sorry, Imaginary roots”, instead of error. To do this we shall have to use one

“if” statement. Again to make the program more simple and readable lets use another

variable „d‟ to store the value of “b*b-4*a*c”. That is d=( b*b-4*a*c);. Now we can write

if (d<0)….

/* Program to find square roots of a quadratic equation */

#include <stdio.h>

#include <conio.h>

#include <math.h>

main()

{

int a,b,c;

float d, x1,x2;

printf(“ \n Please Enter values of a, b, c “);

scanf( “ %d %d %d”, &a, &b, &c);

d= (b*b – 4*a*c);

if (d<0)

{

printf(“ \n Sorry, Imaginary roots “);

Page 31: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [31]

}

else

{

x1 = (-b + sqrt (d) ) / (2*a) ;

x2 = (-b - sqrt (d) ) / (2*a) ;

printf(“ \n Roots will be “);

printf(“ %f %f”, x1, x2);

}

getch();

}

We have seen :

„if‟ is used to conditionally execute some statemnts.

„if –else‟ is used to select a „branch‟ and execute statements in that branch.

„if-else-if‟ ladder for multiple branches.

Switch Statement Now we are going to learn yet another branching statement. That is „switch‟. In many

software, a menu is used which shows different options. Once the user selects an options

(by typing or clicking), the related part of program is executed. For example :

Telephone Directory Program

1. Add Record

2. Search

3. Edit names

4. Delete Record

5. Exit

Enter your Choice :

How to write such a program in „C‟? Using some „printf‟ the matter can be displayed on

screen. Then to ask the users option, one scanf may be used. After that further branching

can be done using if-else-if ladder.

In C language there is a special branching statement for such situations. It is “switch”

statement. Depending upon the “switch” you put on, corresponding bulb will glow! That

is: Switch is a control statement used to make decision from number of choices.

The syntax of this control statement is :

switch(index)

{

case 1:

……Tasks…. when index is 1 …..

Page 32: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [32]

break;

case 2:

……Tasks…. when index is 2 …..

break;

case n:

……Tasks…. when index is n …..

break;

default:

……Tasks…. when index is none of above..

}

Rules of swithc statement : There are few (?) rules to be followed while using switch

statements:

1. Index must be integer or char. (It can‟t be float)

2. case n : Here the n should be constant. [For example case 2 ]. It can not be a condition

like that used in if. For example case x>60 : is not allowed.

3. Statements in the case need not have braces { }.

4. „break‟ statement is not necessary. If it is there, then control will be transferred to

next statement after (out of ) „switch‟.

5. When „break‟ statement is not there in a block, then the program will flow through

the next block. Sometimes there will be bug if we forget the break, but it can be used

constructively in some situations.

6. Cases need not be in sequence. For example, First case 5: then case 2: and after that

case 9: like that any sequence will do.

Now (after learning so many rules), lets take an example. Suppose we want to write the

program for the menu, discussed above.

main( )

{

int x;

printf(“Telephone Directory Program \n”);

printf(“1. Add Record \n”);

printf(“2. Search \n”);

printf(“3. Edit Names \n”);

printf(“4. Delete Record \n”);

printf(“5. Exit \n”);

printf(“Enter your Choice :”);

scanf(“%d”,&x);

Page 33: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [33]

switch(x)

{

case 1:

… Lines to add records when index is 1 …..

break;

case 2:

… Lines to search a record when index is 2 ….

break;

case 3:

… Lines to edit records when index is 3 …..

break;

case 4:

… Lines to Delete records when index is 4 …..

break;

case 5:

… Lines to Exit when index is 5 …..

break;

default:

printf(“\n Please Enter a number between 1 to 5 “);

}

Program 11. Write down a program to add, subtract, multiply, divide given numbers

when keys +, -, *, / are pressed respectively.

/* Demonstration of switch command */

#include <stdio.h>

#include <conio.h>

main()

{

clrscr();

int x=15,y=5,z;

char p;

printf("\n Press a key '+' or '-' or '*' or '/' \n");

printf("\n to add, subtract, multiply, divide %d & %d \n ",x,y);

scanf("%c",&p);

switch(p)

{

case '+':

Page 34: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [34]

z=x+y;

break;

case '-':

z=x-y;

break;

case '*':

z=x*y;

break;

case '/':

z=x/y;

break;

default:

printf("\nPress a key '+' or '-' or '*' or '/' only ! ");

}

printf("\nResult=%d",z);

getch();

}

Note : When index is char, single quotes are used (not the double quotes).

Program 12. Write a function to accept month (1 to 12) and print name of month using

switch statement.

Note: The follwing program requires knowledge of Functions and switch statement. May

be skipped in first reading.

/* Demonstration of switch command */

#include <stdio.h>

#include <conio.h>

main()

{

clrscr();

int m;

void dispmonth(int); /* Function Prototype */

printf("\n Enter Month number \n");

scanf("%d",&m);

dispmonth(m);

getch();

}

void dispmonth(int n)

{

switch(n)

Page 35: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [35]

{

case 1:

printf("Jan");

break;

case 2:

printf("Feb");

break;

case 3:

printf("Mar");

break;

case 4:

printf("Apr");

break;

case 5:

printf("May");

break;

case 6:

printf("Jun");

break;

case 7:

printf("Jul");

break;

case 8:

printf("Aug");

break;

case 9:

printf("Sep");

break;

case 10:

printf("Oct");

break;

case 11:

printf("Nov");

break;

case 12:

printf("Dec");

break;

default:

Page 36: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [36]

printf("\nPress a number between 1 -12 ");

}

}

Conditional operator " ? : " In C language, an operator “? :” is available. This operator is one kind of if ..else

statement. The general format of this operator is :

condition ? expression1 : expression2 ;

In this operator, the condition consists of <,>,==,!=,>=,<=. For example (x<=10) or

(y%4= =0) etc.

When the condition is true, (just like „if‟), the expression1 will be executed. When the

condition is false, (just like „else‟), the expression2 will be executed.

In (place of ) expression1 or expression2, there can be a variable, constant, expression or

a function like printf( ).

For example, in the following line, when the value of „x‟ is less than 35, then 0 will be

stored in variable y. Otherwise 1 will be stored in variable y.

y=(x<35) ? 0 : 1 ;

Program 13. Write down a program which will display larger of two numbers using

conditional operator.

/* Larger of two numbers using conditional operator */

#include <stdio.h>

#include <conio.h>

main()

{

clrscr();

int a,b;

printf("\n Pl enter two numbers ");

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

(a>b) ? printf("\n%d",a) : printf("\n%d",b);

getch();

}

Page 37: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [37]

goto statement : Uptill now we have seen that when a program is run, all the lines are executed one by one

sequentially.

But in some situations we (deliberately) want to jump to another part of program. The

statement „goto‟ in C language is used for this.

There are no line numbers in C language program. Therefore to jump (transfer control) to

a particular part of program, there should be some „label‟. The general format of „goto‟

statement is as follows :

Forward Jump BackwordJump

goto label;

….

….

label:

statements;

label:

statements;

……

……

goto label;

The „label‟ is like name (like variable name) of that part of program. For example when

we want the program control to jump to start or end of the program then label like „begin‟

or „end‟ etc.

Lets take an example. In a program we want to get a value from user (like age of user).

The value enterd should be between 20 to 60. Now if the user enters a value beyond

range, then using goto statement, we can ask him to re-enter the value.

main()

{

int a;

getvalue:

printf(“Please enter a value between 1 to 100 “);

scanf(“%d”,&a);

if(a<0 || a>100)

goto getvalue;

…..

…..

getch();

}

For this type of control transfer it is possible to use „while‟ or „do…while‟ loops. We

shall learn about the loops later. Use of „goto‟ statements frequntly makes the program

difficult to read and debug.

Page 38: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [38]

Program 14. Write down a program which finds sum of three numbers a,b,c when their

values (entered by the user) are within range, and displays „Invalid Data‟

otherwise.

/* ADD a,b,c if within range */

/* a : 100 to 200 */

/* b : -50 to 50 */

/* c : 0 to 100 */

#include <stdio.h>

#include <conio.h>

main()

{

clrscr();

float a,b,c,t;

printf("\n Pl enter three numbers ");

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

if((a>=100 && a<=200) && (b>=-50 && b<=50) && (c>=0 && c<=100))

{

t=a+b+c;

printf("\n%f",t);

}

else

printf("\nInvalid Data");

getch();

}

Program 15. Write down a program which finds sum of three numbers a,b,c when their

values (entered by the user) are within range.

/* ADD a,b,c if within range */

/* a : 100 to 200 */

/* b : -50 to 50 */

/* c : 0 to 100 */

#include <stdio.h>

#include <conio.h>

main()

{

clrscr();

float a,b,c,t;

getval_a:

printf("\n Pl enter value of a ");

Page 39: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [39]

scanf("%f",&a);

if(a<100 || a>200)

goto getval_a;

getval_b:

printf("\n Pl enter value of b ");

scanf("%f",&b);

if(b<-50 || b>50)

goto getval_b;

getval_c:

printf("\n Pl enter value of c ");

scanf("%f",&c);

if(c<0 || c>100)

goto getval_c;

t=a+b+c;

printf("\n%f",t);

getch();

}

Exercise:

Write down a program to find income tax when income is enterd through

keyboard. (Tax is Nil for income less than 1 lac. It is 10 % for income between 1

to 2 lac, and 20% for the income above 2 lac).

Write down a program to calculate light bill, when the number of units are entered

through keyboard. [Rate per unit is Re. 1 for first 100 units, Rs.2 for next units].

Page 40: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [40]

LLooooppiinngg…………!! Just think that a tank, which can hold ten buckets of water, is to be filled. How to tell

such a work to a lay man (like computer) ?

Method 1:

(Fetch and) pour first bucket.

Pour the second bucket.

Pour the third bucket.

…..

Pour the tenth bucket.

Method 2:

Repeat the (following) task ten times :

Fetch the water and pour in tank

Which method is easy to tell? What would happen to first method when the tank is of 50

buckets ? Obviously, the method2 is better (short and sweet).

When we want to tell “Repeat x times”. This method is called looping in programming.

There are three types of loops available in C language.

First of all why there is need of repeating a task ? for any human repeating a task is

definitely boring. But in programming such situations are very common. For example :

Suppose our first program (of finding total and percentage) is to be used for 10

students, then we will have to run that program 10 times. Or we can use a loop to

repeate this program 10 times.

To find biggest number from a list of numbers, loop can be used.

Some programs ask the user type the password. If the user types wrong password

three types, the program automatically ends. In such situation to count how many

times the user has typed the password, we can use loops.

While checking whether a number is prime or not, we have to divide that number

by 2,3,4…etc. For this purpose loop should be used.

To find sum of digits we have to separate digits, for this also we have to use loop.

There are three types of loops in C language, namely for loop, do…while loop and while

loop. Though these can be used interchangeably, each is suitable for certain situation. For

example though we can use while loop, sometimes it is better to use for loop and vice

versa.

for loop Some part of program is to be repeated certain number of times (for example 5 times, 10

times etc) then „for loop‟ is used. Lets first try to understand the for loop in its simplest

form.

for(start;end,increment)

Page 41: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [41]

{

….. Tasks to be Repeated…

}

For example, if we want to print „C is easy‟ 10 times…..

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

{

printf(“C is easy”);

}

What the computer (C language compiler) will do at the time of executing these lines?

First it will store 1 in the variable x. Imagine that a number 1 is written on a plain

paper.

After that all the lines in the block (between { and }) will be executed ONCE.

Next the x = x+1; will add 1 to x and store it in x again. Here, initially x was 1 it

will become 2. Again visualise erasing the number 1 on that paper and writing 2

there.

After that it will check whether x<=10. If „yes‟ then the lines between { and } will

be repeated once again.

Next again the “x= x + 1;” will increment the value of x. Again whether x<=10

will be checeked. Again if „yes‟ then the lines between { and } will be repeated.

This will contine till x=10. Next x will become 11. This time x<=10 is false, so

the loop ends. Control will be transferred to next line beyond loop.

That means, at the end of loop, the value of x will be 11.

In c language x=x+1; is written so often that a shortcut x++; is available. Actuallay ++ is

called as increment operator.

while loop There are situations when a task is to be repeated, but it is not sure, how many times.

What would happen to the tank (in the first example) if it is already half filled ? If you

just tell „repeate … ten times‟, the tank would overflow. Here we shall have to tell

„repeat..till the tank is not full.‟

In its simplest form, the while loop looks like this:

while (condition)

{

….. Lines (tasks) to be Repeated…..

}

For example the following program gets PIN number (password) from the user till he

enters the correct number. Suppose the correct PIN number is „1234‟. Variable x is used

to get (store) the user input.

Program 16. Write a C program that asks PIN number and repeates it till user types

correct PIN number.

Page 42: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [42]

/* Program to demonstrate use of while */

#include <conio.h>

#include <stdio.h>

main()

{

int x;

x=0;

while(x != 1234)

{

printf("Please Enter your four digit PIN ");

scanf("%d",&x);

}

/* lines to be executed after the user types 1234 */

printf("Ok");

getch();

}

The line “while(x !=1234)” repeatedly execute all the line between { and }. A little

consideration will show that, if the value of x is initially 1234, then the loop will not

execute even once. As the line “while(x !=1234)” repeats the task as long as x is not

equal to 1234, the condition is already false. Similarly if the user never types the

required answer (1234) then the loop would repeat indefinitely.

The „while‟ loop does not keep track of the counter. Therefore (generally) it is not used to

repeat fixed number of times (like for loop). If at all this „while‟ loop is to beused for

fixed number of repeatations, we shall have to use a counter variable (say „c‟). The

counter variable should be „set‟ to start value (c=1) then it should be increamented

(c=c+1;) till the condition (c<=10) is true.

/* Part of program. Demo of while */

c=1;

while(c <= 10)

{

printf(“C is easy“);

c=c+1;

}

Page 43: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [43]

do…. while loop The „do…while‟ loop in C language is much like the „while‟ loop. In this loop the

condition is checked at the end of loop. That is, the loop will repeat / executed at least

once.

The syntax of this „do…while‟ loop is as follows:

do

{

….. Lines (tasks) to be Repeated…..

} while (condition);

Using this loop, the program of PIN number (password) would become bit simple.

main()

{

int x;

do

{

printf(“Please Enter your four digit PIN “);

scanf(“%d”,&x);

} while(x != 1234);

getch();

}

Note that we did not „set‟ the initial value of x. The condition is checked at the end,

therefore the loop executes at-least once. Therefore the „do..while‟ loop is called as “do

and check”, whereas the „while‟ loop is called as “check and do” loop.

“break;” statement

Today the word „break‟ reminds us the TV break for ads. But here in C language this is a

statement. This break statement is used to break the loop. The program control is shifted

to the next line beyond (out of) the loop. For example the following program segment

will ask “do you want to repeat ? Press y or n” and untill the user types „n‟, the loop will

repeat indefinitely. Once the user types „n‟ (or any thing other than „y‟) the program will

display “OK! See you ! ”.

char ans;

ans = „y‟;

while (ans= =‟y‟)

{

……

/* lines for the task to be repeated */

……

printf(“Do you Want to repeat ? Type n or y “);

scanf (“%c”,&ans);

Page 44: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [44]

if (ans= =‟N‟)

break;

}

printf( “Ok ! See you !”) ;

In every language there is a command to quit the loop. The goto command can also be

used to exit or break the loop.

while(1) Sometimes while(1) is used to indefinitely repeat the loop. Here the condition part is 1,

meaning „true‟. Forever true! So the loop repeats continuously. There must be an if

statement to break the loop. Lets take an example.

In the program of PIN (password) the condition was “while(x !=1234)”. The value of x is

entered by the user. But the scanf statement is inside the loop. [It is like a door keeper

asking for ticket to enter and the tickets are sold inside!]. There must be some initial

value of x for checking “while(x !=1234)”. When x =0; (or any thing other than 1234),

the progrma control will enter the loop.

In this situation, the while(1) loop may be used. And how to come out of the loop?

Simple! Use a break statement :

while(1)

{

printf(“Please Enter your four digit PIN “);

scanf(“%d”,&x);

if (x= =1234)

break;

}

Program 17. Write down a C language program to find the sum of first 50 natural

numbers.

Lets first develop the logic of this program:

Finally what we want ? 1+2+3+…..+50

What should be done for this ?

The sum (total) may be found in a variable (say „t‟).

t=1+2+3+……

This line would be too long. Can we use loop here?

See, here we are repeating the task of taking NEXT number and adding it.

We can have a funny idea. We have a big empty pot (t=0). In this pot first we

pour 1 liter water. Now there is 1 liter water in it (t=0+1).

Next we pour two liters of water in it. Now there are t=1 +2 = 3 liters of water in

the pot.

Page 45: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [45]

Now we pour three liters of water in the same. Now there are 1 +2+3 = 6 liters of

water in the pot.

That is, everytime we are adding NEXT number to the (previous) addition.

(t=t+x;) This task we are repeating 50 times.

t=0;

for(x=1;x<=50;x=x+1)

t = t + x ;

At first sight, this would look bit funny. Second, this equation would be true only if x is

equal to zero. If x is non-zero, mathematically t=t+x; is incorrect. (Even if t=0 or any

thing, t can not be t+x). But this line is used very frequently in programming. Now let‟s

write the program:

/* add first 50 natural numbers */

#include <stdio.h>

#include <conio.h>

int main()

{

clrscr();

int x,t;

t=0;

for(x=1;x<=50;x=x+1)

t=t+x;

printf("%d",t);

getch();

}

Program 18. Write down a C language program to find factorial of a number.

Before we begin, first lets develop the logic. The program is similar to the previous

program:

Finally what we want 1 x 2 x 3 x…..n

For that Get the number „n‟ from user.

One variable should be used to find the product (say „p‟ for product).

p=1 x 2 x 3……n

It is quite like theprevious program, just we have to use p = p*x;.

The initial value of p should be set to 1. (What will happen if we use p=0 ?)

Now lets write the program:

/* Factorial of a number */

#include <stdio.h>

#include <conio.h>

int main()

Page 46: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [46]

{

clrscr();

int p,n,x;

printf("Please Enter a number ");

scanf("%d",&n);

p=1;

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

p=p*x;

printf("%d",p);

getch();

}

Here the loop will multiply numbers from 1 to n.

Program 19. Write down program to find sum of digits of a number.

In this program, we are going to find the sum of digits of the number. Suppose the

number is 738, then our program should find 7+3+8=18.

The logic:

Finally what do we want sum of digits

For that get the number from user [scanf]

After that separate the digits. It will be easier to separate the digits from right.

Suppose we want to separate the number at unit place (8 in this example).

For this Just find the remainder after dividing it by 10!

That is last digit d = n % 10;

Once we separate the last digit lets remove it. This can be done by dividing the

number by 10 (integer division). That is [n=n/10;], this will reduce the number „n‟

to 73. Now again separate the last digit (now 3), by using, same logic,

last digit d=n%10;.

Now how many times this should be repeated ? Three times for 3 digit number,

Four times for 4 digit number.

Or we can say till the 'n‟ reduces to zero. [do...while(n>0)] or [while(n>0)].

Now writting the program is quite easy. Read the above lines carefully once again

so that you will never need to remember this program, it can be quickly generated.

The digit 'd‟ could also be found by using d= n- n/10*10;. Note that n/10*10

makes integer division first, then multiplies it by 10. In this example n=738, so

n/10 is 73 [and not 73.8]. Then n/10*10 is 730. Therefore d=738-730=8.

/* Sum of digits a number */

#include <stdio.h>

#include <conio.h>

main()

{

Page 47: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [47]

int n,d,s; /* n – given number, d – digit , s – sum */

clrscr();

printf(“\n Please enter a number “);

scanf (“%d”, & n);

s=0 ;

while(n>0)

{

d = n % 10 ;

s = s + d ;

n= n/10 ;

}

printf(“\n Sum of the digits of the number = %d “, s);

getch();

}

Program 20. Write down program to check wheteher a number is Armstrong number or

not.

Logic : An armstrong number is a number whose sum of cubes of its digits is the same

number. For example numbers like 371,407 or 153 etc. Sum cubes of digits of 153 = 1 +

125 + 27. The program would be quite like the previous programs except instead of

s=s+d; here it should be s= s + (d*d*d);.

Note that, while seperating the digits, the given number reduces. But the given (original)

number is required (to check wheter sum is equal to original number). Therefore it is

stored in another variable.

#include <stdio.h>

#include <conio.h>

void main(void)

{

int n,m,d,s;

/* n,m Original Number */

/* s sum of cubes */

/* d seperated digit */

clrscr();

printf("\n Please Enter a number :");

scanf("%d",&n);

m=n; /*Save for future comparison */

s=0;

while(n>0)

{

Page 48: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [48]

d=n%10;

s=s+(d*d*d);

n=n/10;

}

printf("\nOriginal Number %d",m);

printf("\nSum of cubes of digits %d",s);

if(m= =s)

printf("\n %d is Armstrong Number",m);

else

printf("\n %d is NOT an Armstrong Number",m);

getch();

}

Program 21. Write down program to find whether a number is prime or not.

In this program, user will enter a number. The program should tell whether it is prime or

not. A prime number is that number, which is not divisible by any number (except 1 and

itself).

For example if the user types 13 then the program should display “Number is Prime” and

if user types 14, it should display “ Number is Not prime”. As usual lets first develop the

logic.

Finally what we want Message “Prime” / “Not Prime”

What should be done to decide that?

First we should check if given number is divisible by 2. If so, that is if n%2= =0 it

is divisible by 2. In that case obviously it is “Not a prime Number”.

Otherwise it should be checked for (divisible by) 3,4,5 etc. While dividing,

everytime if n%3, n%4, n%5 (that is remainder) is zero then number is “Not

prime”.

Starting from 2, we should check the divisibility by 3, then 4,5 ….etc. How long?

If the number is 13 then we should check up to 12, if it is 17 we should check up

to 16. In short, from 2 up to n-1. If we use „x‟ as divisor, it should go from 2 to

n-1. That is, for(x=2;x<=n-1;x=x+1) [or while(x<=n-1).]

Of course, during that, if the remainder is zero for division by any number, then

definitely number is “Not prime”. Therefore no need to further check whether it is

divisible by next numbers. That is we must „break‟ the loop. For example if n is

25, it is not divisible by 2,3,4 but it is divisible by 5. Thereafter there is no need to

check for divisibility by 6,7..etc.

But if it is not divisible by all the numbers, the loop will go up to n-1. Then after

the loop completes, the value of x would be equal to n.

Looking carefully, it is obvious that program comes out of the loop. Either by

completing or by breaking the loop.

Page 49: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [49]

If loop is „completed‟ (Not divisible up to the end), the number is „Prime‟. In

such case the value of x has increased up to x. (x = =n).

Otherwise the loop has encounterd „break‟. In that case x is less than n.

That is, if(x= =n) then number is „Prime‟, else it is „Not Prime‟.

/* Prime Number */

#include <stdio.h>

#include <conio.h>

main()

{

int n,x;

clrscr();

printf(“Please Enter a number “);

scanf(“%d”,&n);

/*Check divisibility by „x‟ from 2 to n-1 */

for(x=2;x<=n-1;x=x+1)

{

if (n%x ==0) /* Divisible by x */

break; /* Not Prime */

}

if(x= =n) /*Not divisible by any number from 2 to n-1 */

printf(“The number is Prime “);

else /* x < n, Divisible by x */

printf(“The number is Not Prime “);

getch();

}

Program 22. Write down a program which will print following pattern:

* * * * * * * *

Logic :

At first sight, we may tempt to use single line “printf (“* * * * * * * *”);”. But looking

carefully, it is also repeatation of the task [print * ], 8 times.

/* Pattern of stars */

#include <stdio.h>

#include <conio.h>

main()

{

Page 50: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [50]

int x;

for(x=1;x<=8;x=x+1)

printf(“*”);

getch();

}

Program 23. Write down a program which will print following pattern:

* * * * * * * *

* * * * * * * *

* * * * * * * *

Logic: Here the task of “printing * 8 times”, is to be repeated 3 times. This can be done

by using a for loop (to print * 8 times) inside another for loop which repeats it 3 times.

Such a loop inside another loop is called a nesting.

Two loops will need two counter variables. Lets use a variable „h‟ (for horizontal) to print

* 8 times and a variable „v‟ (for vertical) to repeate that line 3 times. Instead of h,v we

could use variable „r‟ for row and „c‟ for column.

/* Pattern */

#include <stdio.h>

#include <conio.h>

main()

{

int v,h;

for(v=1;v<=3;v++)

{

for(h=1;h<=8;h++)

printf(“*”);

printf(“\n”);

}

}

After printing * 8 times, there should be one “printf(“\n”);” line. What will happen if we

forget this line?

Program 24. Write down a program which will print following pattern:

*

* *

* * *

* * * *

* * * * *

* * * * * *

This program is similar to previous program. The counter „v‟ should be varied from 1 to

6, as there are six lines. On the first line one *, on second two, one third three * are there.

Page 51: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [51]

That is, there are stars equal to line number. Therefore the counter „h‟ should vary from 1

to v.

/* Pattern */

#include <stdio.h>

#include <conio.h>

main()

{

int v,h;

for(v=1;v<=6;v++)

{

for(h=1;h<=v;h++)

printf(“*”);

printf(“\n”);

}

getch();

}

Program 25. Write down a program which will print following pattern:

= = = = = *

= = = = * *

= = = * * *

= = * * * *

= * * * * *

* * * * * *

In this program, there are 5 „=‟ and 1 „*‟ on first line. 4 „=‟ and 2 „*‟ on second line. That

is the count of = is reducing by one whereas count of „*‟ is increasing by one.

/* Pattern */

#include <stdio.h>

#include <conio.h>

int main()

{

clrscr();

int h,v;

for(v=1;v<=6;v=v+1)

{

for(h=1;h<=6-v;h=h+1)

printf("=");

for(h=1;h<=v;h=h+1)

printf("*");

printf("\n");

Page 52: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [52]

}

getch();

}

Program 26. Write down a program which will print the following pattern:

1

2 2

3 3 3

4 4 4 4

5 5 5 5 5

Logic : This is another program similar to previous programs. Just instead of „*‟ there is

row number. Therefore instead of prinf(“*”); there should be printf(“%2d”,r);.

“%2” is format specifier which prints the number in two columns (spaces). We shall learn

more about it later.

/* Program: Display the following pattern */

/* 1 */

/* 2 2 */

/* 3 3 3 */

/* 4 4 4 4 */

/* 5 5 5 5 5 */

#include <stdio.h>

#include <conio.h>

int main(void)

{

clrscr();

int r,c,n;

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

{

for(c=1;c<=r;c++)

{

printf("%2d",r);

}

printf("\n");

}

getch();

Page 53: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [53]

}

“continue” Statement : There will be some situations when loop is to repeated, but in a specific situation, the

block is to „skipped‟. Just imagine a computer is playing cricket and we are telling him to

throw exactly six balls in an over. “Every time count the ball thrown. But don‟t count the

„NO Balls‟”. How this program will look like.

n=0;

while(1)

{

…Throw the ball…

…if it is no ball …

continue;

…else

n=n+1;

if n= =6;

break;

}

Program 27. Write down a program which will repeatedly accept a number and display

its square root till user enters 0.

The program should ask for a number and display its sqaure root, till the user enters „0‟.

This can be done easily by using indefinite loop [while (1)] and „break;‟ when user enters

„0‟.

But in this program, if the user enters a negative number, program will give error

message. Therefore one more „if‟ is required to skip the remaing part of loop and contine.

/* Program which Repeats till user enters 0 */

# include <stdio.h>

# include <conio.h>

# include <math.h>

main(void)

{

clrscr( );

int x;

float y;

while(1)

{

printf("\nPlease enter a number :");

scanf("%d",&x);

if(x==0)

Page 54: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [54]

break;

if(x<0)

{

printf("\n..No negative number please...");

continue;

}

y=sqrt(x);

printf("\nSquare root = %f",y);

}

getch();

printf("\nOK..!!”);

}

Note, in the above program both statements „break‟ and „continue‟ are used to avoid the

loop. But the „break;‟ statement transfers the program control out of (beyond) the loop

whereas the „continue‟ statement transfers the program control at the beginning of the

loop.

while(1)

{

……

……

if (…..)

continue;

if (…..)

break;

}

Program 28. Write down a program which uses do..while loop to repeatedly find square

root of numbers untill user enters 0.

/* Print square root of a number */

#include <stdio.h>

#include <conio.h>

#include <math.h>

main()

{

clrscr();

int n;

float m;

Page 55: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [55]

do

{

get_value:

printf("Pl enter a number");

scanf("%d",&n);

if(n<0)

goto get_value;

m=sqrt(n);

printf("\n%f",m);

}while(n>0);

getch();

}

Program 29. Write down a program which will find average of set of n numbers.

Logic :

Finally we want the average.

For the same we need total. (average = total / count of numbers )

How many numbers? User will decide.

Suppose the user decides to average 10 numbers, then-

Ten times ask a number (n), and add it up in „s‟ [s=s+n;]

For this we need a for loop and a counter which will vary from 1 to 10 (or 5 if the

user has decide to average five numbers).

In general the counter going from 1 to c [for(x=1;x<=c;x++)]

That is we need varaibles c,s,n,x.

If all the variables are declared integer, then to avoid integer division, we need

type casting. [Writting (float) before a variable.]

/* Average of set of n numbers */

#include <stdio.h>

#include <conio.h>

int main(void)

{

clrscr();

int c,s=0,x,n;

float a;

printf("\n How many numbers ?");

scanf("%d",&c);

Page 56: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [56]

s=0;

for(x=1;x<=c;x++)

{

printf("Please enter the next number : ");

scanf("%d",&n);

s=s+n;

}

a=(float) s /c;

printf("\n Sum of these numbers %d",s);

printf("\n Average of these numbers %f",a);

getch();

}

Program 30. Write down a program which will print the multiplication tables of numbers

from 1 to 10.

Logic :

Finally we want:

Columns (c)

Row

s (r

)

1 2 3 4 5 6 7 8 9 10

2 4

3 6 15

4 8 36

5 10 20

6 12 42

7 14 21 rxc

8 16 64

9 18

10 20 100

Every number is product of row number and column number. (r x c)

For the row variable r, [ for(r=1;r<=10,r++) ]

For the column variable „c‟ [for(c=1;c<=10,c++)]

One printf(“\n”); to start a new row.

/* Program Multiplication Table */

#include <stdio.h>

#include <conio.h>

Page 57: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [57]

int main(void)

{

clrscr();

int r,c;

printf("\n Multiplication table 1- 10 \n\n");

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

{

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

{

printf("%4d",r*c);

}

printf("\n");

}

getch();

}

Program 31. Write down a program which will find the sum of first 10 numbers of the

following series:

s=1 + ½ +1/3 + ¼ + 1/5 + …..

/* Program: 1 + 1/2 + 1/3 + 1/4 + 1/5 +....+ 1/10 */

#include <stdio.h>

#include <conio.h>

int main(void)

{

clrscr();

float s, x;

printf("\n Program finds 1+ 1/2+ 1/3+....+1/10 \n\n");

s=0;

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

{

s= s + 1/x;

}

printf("Sum = %f",s);

getch();

}

Program 32. Write down a program which will find a b without using pow function.

Page 58: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [58]

Logic: In this program we want to find a x a x a…..b times. That is the line p=p*a;

should be repeated b times.

/* Program: x raised to y without using pow function */

#include <stdio.h>

#include <conio.h>

int main(void)

{

clrscr();

int p,x,y,c;

printf("\n Prog.s to find x^y x-base y-quotient \n");

printf("\n Please Enter x = ");

scanf("%d",&x);

printf("\n Please Enter y = ");

scanf("%d",&y);

p=1;

for(c=1;c<=y;c++)

{

p= p *x;

}

printf("\n x^y = %d",p);

getch();

}

Program 33. Write down a program which will get ages of 10 persons and count the

number of persons with age between 15 to 20.

/* Program: Counting the persons between age 15 to 20 */

#include <stdio.h>

#include <conio.h>

void main(void)

{

clrscr();

int a,n=0,c;

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

{

printf("Enter the age of person number %d : ",c);

scanf("%d",&a);

if(a>=15 && a<=20)

Page 59: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [59]

n=n+1;

}

printf("\n No.of persons in age group 15 to 20 is =%d",n);

getch();

}

Program 34. Write down a program which will display all the ascii codes and their

corresponding character. (ASCII Table)

/* Program: ASCII code and character */

#include <stdio.h>

#include <conio.h>

int main(void)

{

clrscr();

int x;

printf("ASCII Table ");

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

printf("\n The Ascii code %d character %c ",x,x);

getch();

}

Program 35. Write down a program which will generate and print first n fibonocci

numbers.

Fibonacci numbers is a series of numbers having next number as sum of the previous two

numbers. First two numbers 1,1.

1, 1, 2, 3, 5, 8, 13, 21…..

Logic:

First two numbers are 1 each. a=1; b=1;

The third number c is sum of first two numbers [c=a+b;]

If the same logic [c=a+b;] is to be used for next numbers then,

New values of a,b should be previous values of b,c respectively.

1 1 2 3 5 8 13 21

Step1 a b c

Step2 a b c

a b c

Page 60: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [60]

Next it is enough to print value of variable „c‟. Only first time values of a and b are

printed. Next value of b is previous c and next value of a is previous value of b.:

a=b; /* New a is old b */

b=c; /* New b is old c */

But here :

b=c;

a=b;

will not work ! why ?

/* Program: Fibonacci Numbers */

#include <stdio.h>

#include <conio.h>

int main(void)

{

clrscr();

int a=1,b=1,c,x;

printf("%4d",a);

printf("%4d",b);

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

{

c=a+b;

printf("%4d",c);

a=b;

b=c;

}

getch();

}

Program 36. Write down a program to display a circle which increases in size.

Logic: A for loop is used to change radius. But note, to draw graphic entities, graphics

mode (of screen) is required to be initialised.

#include <stdio.h>

#include <conio.h>

#include <graphics.h>

main()

Page 61: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [61]

{

/* initialize the graphics system */

int r;

int graphdriver = DETECT, graphmode;

initgraph(&graphdriver, &graphmode, "..\\bgi");

for(r=0;r<=240;r=r+10)

circle(320,240,r);

getch();

}

Program 37. Write down a program to check whether a number is palindrome or not.

Logic: Palindrome is a number which remains the same when written in revers order. For

example 1221. To find reversed number, we need the logic of „seperating the digits‟.

Once the digit is seperated, that number should be multiplied by 10, 100, 1000….so that

the right-most seperated digit moves to left, and it should be added to generate reversed

number. [p= p*10 +d;]

/* Program to check if given number is palindrome */

#include <stdio.h>

#include <conio.h>

main()

{

int n,m,d,p=0;

clrscr();

printf(" \n Please Enter a number: ");

scanf( "%d", &n);

/* store (save) to compare original and new no. */

m=n;

while(n>0)

{

d=n %10;

p=p*10+d;

n=n/10;

}

printf("\n Reversed Number %d ",p);

if(p==m)

printf("\nGiven number is palindrome");

else

Page 62: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [62]

printf("\nGiven number is NOT a palindrome");

getch();

}

Program 38. Write down a program which displays all four digit numbers which are

even and divisible by 7.

/*All four digit no.s, Even & divisible by 7*/

#include <stdio.h>

#include <conio.h>

main()

{

clrscr();

int x;

for(x=1000;x<=9999;x++)

if(x%2= =0 && x%7= =0)

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

getch();

}

Program 39. Write down a program display a number in binary format.

Hint : Given number is successively divided by 2 until it becomes 1 and at each stage the

remainder after division by 2 is collected.

Logic:

To write a number in binary format, we keep on dividing the number by two and

get the remainder.

Because of dividing by two, the number will become smalled and smaller.

This is to be repeated till the number >=1.

If we write the remainder (n%2) from right to left, we get the binary number.

To move this remainder towards left, multiply it by 10,100,1000…that is,

multiply it by 10x (Ten raised to x).

/*Decimal to binary conversion */

#include <stdio.h>

#include <conio.h>

#include <math.h>

main()

{

clrscr();

Page 63: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [63]

int n,r,b=0,x=0;

printf("Pl enter a number ");

scanf("%d",&n);

while(n>=1)

{

r=n%2;

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

b=b+r*pow(10,x);

n=n/2;

x++;

}

printf("\nBinary Number = %d",b);

getch();

}

Exercise:

Write down a program to print all prime numbers between 1 to 100.

Write down a program which will print all even numbers between 1 to 100.

Write down a program which will print numbers between 1 to 100 except those

which are divisible by 7.

Page 64: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [64]

FFuunnccttiioonnss Function is quite like a small program. Generally, a program takes some input, processes

on it and gives output (result). Just like that a function also takes input and returns some

output. Function is “called” (from main program or other function).

Just as we give „cloth‟ to the tailor and he returns the „shirt‟, the function takes some

„parameter(s)‟ and „returns‟ the result.

Apart from this, some functions do not take any parameter. Some function donot „return‟

anything. They just follow the instructions like displaying some text.

Lets take a funny example. A manager in an organisation has to take lot of meetings. For

that there are lot of things to be done. For example arrange chairs, projector, call the

participants (phone/fax/mail) etc.

The manager does not do all the work. His assistant carries out some of these. The

manager concentrates on the main important tasks. The manager should just tell the

assistant “which people (dept/ cadre ) are to be invited, when (date/time) the meeting is.”

The work of managerr is like main( ) in „c‟ program. The work of assistant is another

function. The main / manager function will call other function / assistant.

main( )

{

……….

Assistant_call_the_meeting(Production,Supervisors,12 Jan);

…Details of meeting of prod dept/supervisors on 12 Jan…

………

Assistant_call_the_meeting (Design,Draftsman,16 Jan);

…Details of meeting of design dept/dtaftsmen on 16 Jan…

……….

}

Assistant_call_the_meeting (DeptName, Cadre, Date)

{

…call [phone/fax/mail] the people of

given DeptName (Production/Design)

of given Cadre (Supervisor/Draftsman)

asked by main/manager

}

In the above program, the function „Assistant_call_the_meeting‟ is called two times (but

written only once). At the time of first call, this function will arrange the meeting of

Production-Supervisor on 12 th Jan. Where as at the time of second call, the same

function will arrange the meeting of Design-Draftsmen on 16 th Jan. The same function

is given different parameters at different calls. For example “Production Dept”,

“Supervisors”, “12 Jan” will stand for DeptName, Cadre, Date respectively at the time of

first call.

Page 65: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [65]

Now why and when we should use function ? Typically when some task is required again

and again, or when some task is a bit complicated, then it is better to use the function. For

a very simple task it is rather „unafforadable‟.

Advantages of function Why use function? What are the advantages of function?

1) As the task is broken up in parts; the program becomes simple, compact.

2) Use of function avoids repeatation. In the above example, if function were not used,

the lines for calling meeting would be repeated two times.

3) Program becomes easy to edit. It is enough to make changes in function at one place

only.

4) Once a function is written, the same can be used in many programs by many

programmers. So it improves productivity.

Lets first know the rules (in C language) for functions. Some of these rules at first sight

may appear difficult. Just don‟t worry.

Function… Some rules…!

The functions has a type like int, float etc (just like a variable). This is the type of the

returned value of the function. For example, when the function is returning float

value, then the type of that function is float.

The default type of a function is „int‟. Meaning if you do not declare the type of a

function, its type will be „int‟.

The function must also be declared (just like a variable). For example, if xyz is a

function which takes three integer values and returns a flaot value, it should be

declared as follows. This is also called as function prototype. :

float xyz(int , int , int);

Some of the functions do not return any value. They just carry out some task. The

type of such functions is called „void‟. For example : void xyz( );

Some functions donot take any parameter, then the parameter is said to be „void‟. For

example

void xyz(void); or int xyz(void);

main( ) is also a function. The program begins with main function.

One function can call another function. Generally main function calls some other

function. But this function may call yet another function. It can even call main( ).

A function may call to itself. Such a function is called „Recursive Function‟.

While calling a function, the numbers and sequence of the parameters must match

with the function declaration/ defination.

While declaring function, they are declared at the beginning in main. Only the type of

parameters may be written: For example: int xyzfn( flaot, int, char); Here the function

xyzfn takes three parameters whose types are float, int and char respectively. The

function xyzfn returns integer.

Page 66: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [66]

The value returned by function may be stored in a variable if required. For example:

v=getpercentage(sub1,sub2,sub3);

Or value returned by function can even be used directly in an expression. For

example:

printf(“%f”, getpercentage(sub1,sub2,sub3))

Generally a function can return only one value. [Using pointers we can get the effect

of returning more than one variables].

The variables declared in the (block of) a function are available in that function only.

Such variables are called as local variables. These variables are not available outside

that function.

main( )

{

int a,b;

….

….

}

fun_1()

{

int x,b;

….

….

}

In the above program, the variable „a‟ is available only in main( ) function. The

variable „x‟ is available in fun_1 only. There will be two seperate „b‟ variables.

Therefore the value of variable „b‟ will be different in main and fun_1. Each is

available in that function only. This is called as 'scope of the variable'.

The variables declared clearly outside all functions (including main), are called as

„global variables‟. These are available (can be used) in all functions. Generally these

global varialbes are declared at the beginning of the program.

#include <stdio.h>

int p;

float q;

main()

{

int a,b;

….

….

}

Page 67: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [67]

fun_1()

{

int x,b;

….

….

}

In the above program the variables „p‟ and „q‟ are available in main as well as fun_1

function.

The variables in a function are „reset‟ every time. For example, in the following

program, even if we want to increment the value of variable x, the value will be

displayed as 1 only.

main( )

{

int a;

….

….

fun_2();

…….

…..

fun_2();

}

fun_2( )

{

int x=0;

x=x+1;

printf(“%d”,x);

….

}

In this program, if we want to increment the value of x variable, there are two options:

Declare the variable „x‟ as „global‟ variable. [Declare it outside the functions, even

before the main function]

Declare it as static variable. [Just write static before the variable name, like static int

x=0;]. Once it is declared as static, its value does not reset. Even if the line “int x=0;”

is there, this line is executed only once.

main( )

Page 68: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [68]

{

int a;

….

….

fun_2( );

…….

…..

fun_2( );

}

fun_2( )

{

static int x=0;

x=x+1;

printf(“%d”,x);

….

}

In this case, when variable is declared static, the value of x would not reset. Therefore

it will be increased by one, at the time of every call.

Now after learning so many rules, lets take an example. Lets use our first program, which

takesmarks of three subjects and calculates average.

Function Demonstartion main()

{

/* Program for average of marks of 3 subjects */

int sub1,sub2,sub3,total;

float avg;

/* Following line is function declaration */

/* or Function Prototype */

float getaverage(int,int,int);

printf(“Please Enter the marks of three subjects “);

scanf(“%d%d%d”,&sub1, &sub2, &sub3);

/* Following line is function call */

avg= getpercentage(sub1,sub2,sub3);

printf(“%f”,avg);

getch();

}

Page 69: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [69]

/* Function Definition */

float getpercentage(int a, int b, int c)

{

float d;

d = (a+b+c)/3.0;

return(d);

}

In the above program, when getpercentage function is called:

The value of sub1 is copied (given) to the variable a, sub2 to „b‟ and sub3 to „c‟.

sub1 a

sub2 b

sub3 c

Then the lines in the function are executed.

At the end of function ( „return‟ line), the program control will go back to main function.

Here the value of „d‟ is returned to the main or calling function. This value will be

received and stored in variable avg of the main function, because of the line : [avg=

getpercentage(sub1,sub2,sub3);]

Function Arguments The parameters of a functions are called as function arguments. Those

arguments/parameters which are passed to a variables (in the above example sub1, sub2,

sub3) are called actual arguments. The corresponding variables/ arguments in the

function (here a,b,c) are called formal arguments.

Even if we use same names, for actual and formal arguments, these will be distinct

variables. It is better to use separate names for actual and formal arguments (ofcourse for

our convinience, to avoid our confusion; not for the Compiler/ computer)

For example, in the above program even if the values of a,b,c are changed, there will be

NO CHANGE in the corresponding sub1, sub2, sub3 variables.

sub1, sub2, sub3 a,b,c

Data moves from Actual arguments to formal arguments.

Whereas, data DOES NOT move from formal arguments to Actual arguments.

a,b,c x sub1, sub2, sub3

To make this point clear, lets take an example. In the following program, a function is

written, which is for interchanging the values of two variables. But this will NOT work.

Though the values of variables x and y interchange, the corresponding variables a,b

would not interchange. The reason: changes in formal arguments inside the function do

not affect the corresponding actual arguments.

/* Program DOES NOT swap contents of two variables */

#include <stdio.h>

Page 70: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [70]

#include <conio.h>

int main(void)

{

clrscr();

int a=5,b=7,t;

void ichange(int, int); /*Function Prototype */

printf("\na=%d b=%d",a,b);

ichange(a,b);

printf("\na=%d b=%d",a,b);

getch();

}

void ichange(int x, int y)

{

int t;

t=x;

x=y;

y=t;

printf("\nx=%d y=%d",x,y);

}

Output

a=5 b=7

x=7 y=5

a=5 b=7

Can we not write such a function ? We can, but after we learn the pointers!

Function calling another function : Now lets see an example where a function calls

another function.

Program demonstating function calls.

#include <stdio.h>

#include <conio.h>

void abc(void); /* Function prototype */

void xyz(void); /* Function prototype */

Page 71: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [71]

main()

{

clrscr();

printf("\n Welcome ! ");

abc();

printf("\n OK Bye! ");

}

void abc(void)

{

printf("\n Now in abc");

xyz();

printf("\n Back in abc again");

}

void xyz(void)

{

printf("\n Now in xyz");

}

Output:

Welcome…!

Now in abc

Now in xyz

Back in abc again

OK Bye…!

In the above program the main function calls „abc‟ function. This „abc‟ function in turn

calls „‟xyz‟ function. On the return route, xyz function will transfer control to function

abc and abc to main.

Function calling itself (Function Recursion) : Just as a function calls another function, the

function can call to itself. This is called as function recursion. Recursion is a process

where a function calls itself.The following program is a good example of function

recursion.

Program 40. Write down a program which will find factorial of a number using recursive

function.

Page 72: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [72]

/* Factorial using Recursive function */

#include <stdio.h>

#include <conio.h>

void main(void)

{

int x,y;

int fnfact (int); /*Function Prototype */

clrscr();

scanf("%d",&x);

y= fnfact (x); /* Call to the function */

printf("%d",y);

getch();

}

int fnfact (int n)

{

int f;

if (n= =1)

return(1);

else

f =n* fnfact (n-1);

return(f);

}

In this program, fnfact( ) function is used to find the factorial of a number. Factorial is

product of all numbers from one up to that number. For example factorial of 5 = 1 x 2 x 3

x 4 x 5. OR

factorial of 5 = 5 x 4 x 3 x 2 x 1

Looking at the above sequence we can say,

factorial of 5 = 5 x Factorial of 4

Similarly,

factorial of 4 = 4 x Factorial of 3

Similarly,

factorial of 3 = 3 x Factorial of 2

Similarly,

factorial of 2 = 2 x Factorial of 1 = 2 x 1 (Because Factorial of 1=1)

Page 73: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [73]

Here while finding factorial we are repating the same task for the next smaller number,

till it is 1. That is when n= = 1 it will start the return journey. In short, in the recursive

function there must be one “if statement”!

It is not necessary to use recursive function (Thank God!). Without recursive function

also we can easily write such program using for loop. But in exam if it is asked to write

program using recursive function, there is no option. Anyway, the recursive function is

not as difficult as we feel at first sight.

Program 41. Write down a program to display a number in binary format using a

recursive function.

Hint : Given number is successively divided by 2 until it becomes 1 and at each stage the

remainder after division by 2 is collected.

/*Decimal to binary conversion */

#include <stdio.h>

#include <conio.h>

#include <math.h>

int r,n,b=0,x=0,bf; /* bf- Binary Format */

/* Function prototype dtob = decimal-to-binary */

int dtob(int);

void main()

{

clrscr();

int n;

printf("Pl enter a number ");

scanf("%d",&n);

bf=dtob(n);

printf("\nBinary Number = %d",bf);

getch();

}

int dtob(int n)

{

if(n= =0)

return(b); /*return in last call */

else

{

r=n%2;

b=b+r*pow(10,x);

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

Page 74: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [74]

n=n/2;

x++;

dtob(n); /*recursive call*/

}

}

Program 42. Write down a program which will accept marks in three different subjects

and show the result as pass or fail. Use functions to find average and

minimum.

Deciding „pass‟ or „fail‟ using just the average marks can be misleading. For example if a

student has got 90,90 and 30 marks in three subjects, his average would be 70. Still he is

„fail‟. This bug can be easily fixed by using minimum marks for deciding „pass/fail‟. So

let‟s use a function which gets marks of three subjects and returns the minimum.

/* Program for finding out avg of marks display result */

#include <stdio.h>

#include <conio.h>

main()

{

int sub1,sub2,sub3,total, minmks ;

float avg;

/* Following lines are Function Prototype */

float getaverage (int, int, int);

float getmin (int, int, int);

printf(“Please Enter the marks of three subjects “);

scanf(“%d%d%d”,&sub1, &sub2, &sub3);

/* Following line is function call */

avg= getpercentage(sub1,sub2,sub3);

printf(“%f”,avg);

minmks = getmin (sub1,sub2,sub3);

if (minmks < 40)

printf(“\n Fail”);

else

printf(“\n Pass”);

getch();

}

/* Function Definition */

float getpercentage(int a, int b, int c)

Page 75: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [75]

{

float d;

d = (a+b+c)/3.0;

return(d);

}

/* Function Definition */

int getmin(int a, int b, int c)

{

int m;

m=a;

if(b<m)

m=b;

if(c<m)

m=c;

return(m);

}

Exercise:

Write down a program which will use a function to find the value of y=x²+3x+5; when

value of x is entered through keyboard.

Write down a program which will use a function to display values of squares of numbers

between 1 to 25.

Page 76: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [76]

AArrrraayyss We have seen that a variable is like a container, which can hold one value at one time.

For example when we say x=5; then the variable will hold value 5. Next if we write x=7;

then it will store this new value but the old value (5) is lost !

That is, a variable can not hold more than one values. Suppose we want to store the

marks of 10 studnets then we will need 10 different variables like a,b,c,d,…. etc.

Similarly lets imagine we want to store marks of 60 students. Obviously this method will

need 60 variables. Then if average of these 60 students is to be found, then typing a line

like avg=(a+b+c+d+….)/60.0; will be very tedious (almost impossible).

Offcourse this can be made simple by typeing a line like t=t+n; [Refer Program Number

27], but still some problems will remain. For example if marks of a specific roll number

(say number 51) are to be printed….

In such situations, only one variable can be used, with subscripts. For example m1, m2,

m3, m4…. etc. In C progrmming the scubscripts of the variables are written in square

bracket [ ]. Like m[1], m[2], m[3], m[4] …. etc. The chain of such variables is called as

ARRAY. Dictionary meaning array= marshal forces – to arrange soldiers.

In C language Arrays are declare as follows:

int m[60];

On the above line the number between square brackets [60] is called as dimension of

array. This line will ask the computer operating system to reserve 60 places in memory

which can hold integer numbers.

While declaring an array, you must decide the number of elements in the array. The

subscript must be an integer. It can not be a varaible. For example int m[x]; is not

allowed.

In these 60 variables first will be m[0], second will be m[1]. Third m[2]…. and the

sixtieth that is last will be m[59]. Here these numbers in the square brackets are called

subscript of that array. This subscript can be a variable but dimension can‟t be. Except

the subscript, there is no difference between an array variable and general variable. Like :

m[1]=7; a line like this can be used to store value in the variable.

scanf(“%d”,&m[1]); a line like this can be used to get data from the user through

keyboard.

printf(“%d”,m[1]); can be used to display the contents of variable.

Arrays (like a general variable) can hold (any one) int, long, float, char type data.

If the subscript [ ] is variable, like m[x] then we can use loop (for, while, do..while) with

the array. This can make the progrma compact. For example the following program

segment may be used to receive marks of ten subjects from user.

int sub[10], x; /* Declaration */

for(x=0,x<=9;x=x+1)

scanf(“%d”,&sub[x]);

Similarly, following two lines are enough to display these value on screen:

for(x=0,x<=9;x=x+1)

Page 77: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [77]

printf(“%d”,sub[x]);

To sum up all the elemnts of Array:

t=0;

for(x=0,x<=4;x=x+1)

t = t + sub[x];

printf(“%d”,t);

If arrays and loops were not available/ used, then we would require lot of lines.

In C language another method for declaring array is available. When the values of all the

element are fixed (not to be taken from user), following single line will declare and store

the values in array:

int sub[5] = {75,45,98,57,72};

or

int sub[ ] = {75,45,98,57,72};

Assigning the values to the array elements is called as 'initialization‟. Ofcourse instead of

this single line, with routine method we could write following 6 lines:

int sub[5];

sub[0]=75;

sub[1]=45;

sub[2]=98;

sub[3]=57;

sub[4]=72;

In C language, if we declare a variable and print its value (without initilizing) like :

int x, m[4];

printf(“%d”,x);

printf(“%d”,m[1]);

then we may find x, m[1] variables contain some unpredictable „random‟ value. (This

may not be 0). Such value is called as „garbage‟ value. A small program can be used to

see these „garbage‟ values:

int x,sub[5];

for(x=0;x<=4;x=x+1)

printf(“\n%d”,sub[x]);

OUTPUT:

64

3283

-29144

12803

-28683

Therefore, note that if the variables are used without initialization, the program does not

even give error message. But we get unexpected results.

Page 78: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [78]

Two Dimensional arrays: If the soldiers or students are standing in on ground for PT/Drill, then place of each

soldier or student can be specified using his row, column number. Generally the seat

numbers in a theater are like this. Row A,B,C… and seat nuber 1,2,3… in each row.

Two dimesnsional arrays in C language are like this. Suppose we want to store the marks

of three subjects sub1, sub2, sub3 and such five students are there. Here we can use a two

dimensional array.

sub1 sub2 sub3

stud1 99 44 55

stud2 64 87 45

stud3 59 83 56

stud4 77 46 58

stud5 34 28 45

The following line declares a two dimensional array which will have five rows and three

columns.

int m[5][3];

Here number of rows are specified in first square bracket [ ] and number of columns in

second square bracket [ ]. Similalrly while declaring and initializing the array at once :

int m[5][3] = {

{99,44,55},

{64,87,45},

{59,83,56},

{77,46,58},

{34,28,45}

};

Program 43. Write down a program which will ask 10 numbers, store them in an array

and find the biggest of these numbers.

Here we want to store 10 numbers in an array and then find and display the biggest

of them. How we (a human) would have done this? Just a look at the list of ten

numbers, and we immediately come to know which is biggest. But what if these

numbers are told to us one by one ? Lets suppose the numbrs are (4, 7, 3, 8, 22, 55,

11, 73, 1, 6).

We would first keep first number 4 in mind.

Then when the next (7) is told, we keep this in mind and leave the first (4).

Then when the next (3) number is told we would simply ignore it and go ahead.

In short when the next number is bigger then store it else ignore it.

Lets take a variable m (m for maximum) and store first number in it. (m = n[0] ;).

Page 79: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [79]

Next if second is bigger, put it in „m‟. That is : if(n[1]>m) then m = n[1];

Same process for the third, fourth… last number.

That is if(n[x]>m) tr m = n[x] ; Here x varies from 1 to 9.

Using this logic now lets write the program:

/* Program :Biggest number of an array */

#include <stdio.h>

#include <conio.h>

main()

{

int x,m, n[10] ;

/* x- counter, m-Maximum, n[10] array of 10 elements */

clrscr();

/*Loop to get 10 elements in the array */

for(x=0;x<=9;x=x+1)

scanf(“%d”, &n[x]);

m=n[0]; /* Store first element in m */

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

{

if (n[x]>m) /* Is next element bigger than m ? */

m=n[x] ; /* Replace m with new number */

}

printf(“Biggest Number : %d”, m);

getch();

}

If (by chance), the first number is biggest, then the „if block‟ would never get executed.

Otherwise the next number will be stored in variable „m‟ if it is bigger than the previous.

Program 44. Write down a program which will copy contents of one array to another

array.

#include <stdio.h>

#include <conio.h>

void main(void)

{

int a[10]={5,2,4,7,8,9,6,0,3,1};

int b[10],x;

clrscr();

Page 80: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [80]

printf("\n Copying array a to array b :");

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

{

b[x]=a[x];

}

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

printf("\n%d\t%d",a[x],b[x]);

getch();

}

Program 45. Write down a program which will sort 10 numbers in ascending sequence.,

You must have arranged the playing cards in sequence. How to tell such task to a

computer? This is called as „sorting‟. There are different algorithms for sorting numbers.

The first is selection sort. In this selection sort, the smallest number is „selected‟ and put

in first place.

First of all the FIRST (0th) number and second number are compared.

If the second (next) is smaller, interchange them.

Then the FIRST (0th) number and third number are compared.

If the third (next) is smaller, interchange them.

In this way FIRST number is compared with 3rd, 4th …etc. This way the first number is

sorted. To interchange the variables a temporary variable (t) is used:

if n[1] < n[0]

{

t= n[1] ;

n[1] = n[0];

n[0]= t;

}

Next, instead of first number n[0], n[1] then n[2] ...n[x] is used :

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

if (n[x] < n[0])

{

t= n[x] ;

n[x] = n[0];

n[0]= t;

}

In the next step, the first element is sorted, just leave it and start over again from second,

then third etc. Lets write the program now :

/* Sorting of array using Selection Sort */

Page 81: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [81]

#include <stdio.h>

#include <conio.h>

main()

{

clrscr();

int x,y,t,n[] = {54,21,66,34,42,89,23,61,11,5};

printf("\n Before sorting");

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

printf("\n n[%d]=%d",x,n[x]);

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

for(x=y+1;x<=9;x++)

if (n[x] < n[y])

{

t= n[x] ;

n[x] = n[y];

n[y]= t;

}

printf("\n After sorting");

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

printf("\n n[%d]=%d",x,n[x]);

getch();

}

OUTPUT :

Before sorting

n[0]=54

n[1]=21

n[2]=66

n[3]=34

n[4]=42

n[5]=89

n[6]=23

n[7]=61

n[8]=11

n[9]=5

Page 82: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [82]

After sorting

n[0]=5

n[1]=11

n[2]=21

n[3]=23

n[4]=34

n[5]=42

n[6]=54

n[7]=61

n[8]=66

n[9]=89

Program 46. Write down a program to store 1 to 10 numbers in an array and then find

sum of first 5 numbers using break statement.

/*Store 1 to 10 numbers in an array */

/* then disp sum of first 5 numbers using break */

#include <stdio.h>

#include <conio.h>

main()

{

clrscr();

int n[10],x,t;

/* store values 1,2…10 etc in x[0],x[1],x[2]…x[9]*/

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

n[x-1]=x;

/*Find sum of first 5 numbers */

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

{

t=t+n[x-1];

if(x==5)

break;

}

printf("%d",t);

getch();

}

Program 47. Write down a program to declare and display a two dimensional array in

matrix form.

Page 83: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [83]

Logic:

The elements of two dimensional array may be visualized as follows :

a[0] [0] a[0] [1] a[0] [2] a[0] [3]

a[1] [0] a[1] [1] a[1] [2] a[1] [3]

a[2] [0] a[2] [1] a[2] [2] a[2] [3]

While displaying the elements :

First display all elements in 0th row.

Then “\n” for new line.

Then the next row number 1…, 2…. Etc.

/* Program: Declaring and printing a two dim array */

#include <stdio.h>

#include <conio.h>

int main(void)

{

clrscr();

int a[3][4]= {

{2,3,5,7},

{6,8,4,2},

{1,5,7,9},

};

int r,c;

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

{

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

printf("%3d",a[r][c]);

printf("\n");

}

getch();

}

Page 84: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [84]

OUTPUT:

2 3 5 7

6 8 4 2

1 5 7 9

Program 48. Write down a program to add two, two-dimensional array in matrix

/* Program: Addition of Matrices */

#include <stdio.h>

#include <conio.h>

int main(void)

{

clrscr();

int a[3][4]= {

{2,3,5,7},

{6,8,4,2},

{1,5,7,9},

};

int b[3][4]= {

{1,6,7,9},

{2,3,4,7},

{0,4,2,8},

};

int r,c,d[3][4];

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

{

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

d[r][c]=a[r][c] + b[r][c];

}

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

{

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

printf("%3d",d[r][c]);

printf("\n");

Page 85: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [85]

}

getch();

}

Program 49. Write a function to initialize a square matrix of size 4 as unity matrix

(leading diagonal elements as 1 and other elements as 0).

v

h

1 0 0 0

0 1 0 0

0 0 1 0

0 0 0 1

Logic:

h and v variables are used for the horizontal and vertical elements respectively.

When h and v are same, a[h] [v] = 1;

All other elements are 0. a[h][v]=0;

/* Initialise array as unity matrix */

#include<stdio.h>

#include<conio.h>

/*Global variables available to all functions */

int a[4][4],h,v;

/* Function declaration */

void matini(void);

void printmat(void);

void main(void)

{

clrscr();

matini();

printmat();

getch();

}

void matini()

{

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

Page 86: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [86]

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

{

if(h= =v)

a[h][v]=1;

else

a[h][v]=0;

}

}

void printmat(void)

{

/* Printing Matrix */

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

{

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

{

printf("%4d",a[h][v]);

}

printf("\n");

}

}

Program 50. Write down a program which will use functions to read, print, transpose,

and find sum of all elements of a two dimensional matrix.

Logic :

Transpose of matrix is obtained by switching rows to columns. a[h][v] and a[v][h]; are

interchanged.

But the elements on one side of diagonal only should be interchanged.

Otherwise there will be problem like a=b; and b=a;. Same numbers will come on both

sides of diagonal. [Refer program number 2].

h should vary from 0 to 3 but v should vary from 0 to h.

v

h

2 1 4 5

3 4 4 7

5 6 7 9

9 5 1 8

/* Transpose of a matrix */

Page 87: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [87]

#include<stdio.h>

#include<conio.h>

#define m 4

#define n 4

/*Global variables available to all functions */

int a[m][n],h,v,t;

void readmat(void);

void printmat(void);

void transmat(void);

void sumall(void);

void main(void)

{

clrscr();

readmat();

printmat();

transmat();

printmat();

sumall();

getch();

}

void readmat()

{

for(h=0;h<=m-1;h++)

for(v=0;v<=n-1;v++)

{

gotoxy(5*v+1,3*h+1);

scanf("%d",&a[h][v]);

}

}

void printmat()

{

/* Printing Matrix */

printf("\n Matrix...\n");

for(h=0;h<=m-1;h++)

Page 88: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [88]

{

for(v=0;v<=n-1;v++)

{

printf("%6d",a[h][v]);

}

printf("\n");

}

}

void transmat(void)

{

for(h=0;h<=m-1;h++)

{

for(v=0;v<=h;v++)

{

t=a[h][v];

a[h][v]=a[v][h];

a[v][h]=t;

}

}

}

void sumall()

{

int t=0;

for(h=0;h<=m-1;h++)

for(v=0;v<=n-1;v++)

{

t=t+a[h][v];

}

printf("\n Sum of all elments = %d",t);

}

Program 51. Write down a program which will multiply two given matrices.

This program uses concepts of pointers, so may be skipped in the first reading.

Logic :

Page 89: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [89]

Suppose there are two matrices a [r1][c1] andb[r2][c2]. r1,c1 and r2,c2 are numberof

rows and columns of matrix a and b respectively.

Multiplication is possible only when c1=r2

fnaccept = function to get the matrix elements. fndisplay= function to display matrix on

screen.

The new matrix c contains elements which are sum of products of rows of first and

columns of second matrix. (a[i][k]*b[k][j]). Therefore c[i][j]=c[i][j]+(a[i][k]*b[k][j]);

p q x

t u =

pt +qv pu+qw

r s v w rt+sv ru+sw

In C language array name is same as address of its zeroth element: Therefore a = &a[0].

Here call by reference is used. The base address (address of 0th element of array) is

passed to function.

/* Matrix Multiplication */

#include<stdio.h>

#include<conio.h>

void fnAccept(int a[10][10],int r,int c)

{

int i,j;

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

{

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

scanf("\t%d",&a[i][j]);

printf("\n");

}

}

void fnDisplay(int a[10][10],int r,int c)

{

int i,j;

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

{

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

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

printf("\n");

Page 90: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [90]

}

}

void fnMultiply(int a[10][10],int r1,int c1,int b[10][10],int c2)

{

int i,j,k,c[10][10];

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

{

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

{

c[i][j]=0;

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

{

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

}

}

}

printf("\nThe multiplication is :\n");

fnDisplay(c,r1,c2);

}

void main(void)

{

int a[10][10],b[10][10],r1,c1,r2,c2,c[10][10];

char ans;

clrscr();

printf("Enter the number of rows of 1st matrix.");

scanf("%d",&r1);

printf("Enter the number of columns of 1st matrix.");

scanf("%d",&c1);

printf("Enter the elements.\n");

fnAccept(a,r1,c1);

fnDisplay(a,r1,c1);

printf("Enter the number of rows of 2nd matrix.");

scanf("%d",&r2);

printf("Enter the number of columns of 2nd matrix.");

scanf("%d",&c2);

printf("Enter the elements.\n");

Page 91: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [91]

fnAccept(b,r2,c2);

fnDisplay(b,r2,c2);

if(c1= =r2)

fnMultiply(a,r1,c1,b,c2);

else

printf("Multiplication is not possible.");

getch();

}

Page 92: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [92]

PPooiinntteerrss…………!! One of the many important features of C language is „pointers‟. The general concept

about the „pointers‟ is something like “This is too difficult! It is not for me!”. Actually

everyone of use feels the same while learning to ride a bicycle too! But with some

practice everything becomes easy. So Never, Never, Never Give Up!

Lets talk about the pointers a bit later. First I tell you my experience. In our college there

is a pegion hole cupboard.

o o o o o

o o o o o

o o o o o

It has many drawers. On each drawer there is a number. Apart from this, there is a sticker

of name on each drawer. If I ask someone to bring something from my drawer, I can refer

the drawer either by its name (on the sticker) or by its number.

Just like this, in the memory of computer, there are locations (places). Each location has

got a number. When we store some data in a variable, it is much like putting something in

a drawer. The „item‟ in the drawer is similar to content of variable. The (serial) number of

the drawer is „address‟ of variable, and the sticker is variable name.

Drawer = Variable

Items in the Drawer = Content of variable .

(serial) number of the Drawer = „address‟ of variable

sticker on the Drawer = variable name.

When we write x=5; in a program, then the computer writes number 5 at some

(convenient) location of its memory. (Like an amount Rs.5 is put in a drawer having

sticker name „x‟.) Now this „x‟ is actually a variable name of that memory location

(drawer). It has got a location number too. At which location number the data will be

stored is decided by the computer. Suppose the location number is 1234. (It can be

anything, and computer will decide that).

When we tell the C compiler to print the value stored in x variable, we can tell “print the

contents of variable x” or we can tell to “print the contents kept at memory location

number (address) 1234”.

& the “Address of” operator How to know this address (1234) ? For this, there is an operator “&” in the C language.

Lets NOT pronounce (call) it as ampersand. Lets call it as “address of”.

For example &x = address of x = 1234

Lets visualize it :

Variable name x

Content 5

Page 93: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [93]

Address 1234

When we write a line like scanf(“%d”,&x); we are actually telling the computer to get a

value from the user and store it at the “address of x” [&x].

The following program segment will print content and address of the variable x.

int x;

x=5;

printf(“content of x = %d”, x);

printf(“address of x = %u”, &x);

%u is a format string just like %d, %f, %c etc. The %u is used for “address of a variable”.

%u is also used for unsigned integer. This address 1234 is actually a number. Therefore

this number can be stored in yet another variable. Suppose we want to store that number

(1234) in variable „y‟. That is we want to ask the computer to “put the address of x

(1234) in variable y”. This can be done by simply typing y = &x;. This line is can be read

as y gets “address of x”.

x y

5 y=&x 1234

1234 5678

Here y is a variable. But it is not going to store any ordinary (integer) number. It is going

to store the “addres”. Therfore the variable „y‟ is not declared as “int y;”. It is declared as

int *y;

* the “Value at the address of” operator In C language * operator has two meanings. First is multiplication and second one which

is connected with pointers, is indirection. Generally * is pronounced as „star‟ or „asterics‟.

But here, lets not call it „star‟. As far as pointers is concerned, lets pronounce (call) the *

as “value at the address of”.

For example *y may be pronounced as value at the address of y = value at address of

1234 = 5. In short *y denotes 5.

But in declaration like int *y, the meaning is y is a variable which will store an address.

The address will be of a variable which holds integer.

The following program will print the contents, addresses of variables x,y.

Program to print content and address of variables.

main()

{

int x, *y;

x=5;

y=&x; /*creates link, stores address of x to y */

printf(“ content of x = %d “, x); /*will print 5 */

Page 94: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [94]

printf(“ address of x = %u “, &x); /*will print 1234 */

printf(“ content of y = %u “, y); /*will print 1234 */

printf(“ address of y = %u “, &y); /*will print 5678 */

printf(“ value at address of y = %d “,*y); /*prints 5 again*/

}

Go through the above program once more.

What will happen if pointer is incremented ? For example, in the above program if y is

incremented (y=y+1; or y++;), then the value of y will NOT be 1234 +1 =1235. Instead y

will now point to the next adjacent address.

Now suppose a[10] is an array, and suppose the address of its zeroth element &a[0] is

1234.

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

2 9 8 4 6 5 7 8 0 1

1234

Now, suppose this address 1234 is stored in another variable „b‟. This can be easily done

by writing b=&a[0]; . Pronounce it as “b = address of a[0]”. Variable b must be declared

as pointer using line like int *b;.

b

1234

5678

Once the connection b= &a[0] is established, the address of a[0] which is 1234, is stored

in pointer variable b. Then :

*b = value at the address of b

= value at the address of 1234

= 2.

In short, *b =2.

Now if b is incremented, by using b++ or b=b+1, then, *b will point to next element of

array that is 9. That is, *b will become 9.

Program 52. Write down a program to interchange contents of two variables using

function.

Logic: We have seen that if „formal argumnets‟ are interchanged, „actual arguments‟ do

not get interchanged. Therefore here the addresses of the variables are passed. This is

called as „call by reference‟. The values at the addresses are interchanged.

/* Program: Swap contents of two variables using Function */

Page 95: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [95]

#include <stdio.h>

#include <conio.h>

int main(void)

{

clrscr();

int a=5, b=7, t;

void ichange(int *, int *); /*Function Prototype */

printf("\na=%d b=%d",a,b);

ichange(&a,&b);

printf("\na=%d b=%d",a,b);

getch();

}

void ichange(int *x, int *y)

{

int t;

t=*x;

*x=*y;

*y=t;

}

Output:

a=5 b=7

a=7 b=5

Note, when function is called, x is assigned &a (address of a), y is asssigned &b (address

of b). It is just like saying x=&a; and y=&b;. Then in the function, the *x and *y (values

at the addresses of x and y) are interchanged. Therefore no return statement is used.

Program 53. Write down a program which will copy contents of one array to another

array using a function.

Logic :

In case of arrays, the arrayname = address of zeroth element of array. For example if

name of array is a[10], then when we type just “a” (without subscript), it is as good as

saying &a[0].

Therefore if we pass the arraname to a function, it is as good as passing the address of

zeroth element (base address) to the function.

In the function there should be a pointer to receive this base address.

The base addresses of a and b arrays are copied to the pointers c and d.

Page 96: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [96]

Now *c is value at the address of c = contents of zeroth element of array a.

And *c is value at the address of d = contents of zeroth element array b.

c++, and d++ will move the pointer to the next elements in respective arrays( a and b).

#include <stdio.h>

#include <conio.h>

void main(void)

{

/* Function Prototype*/

void fcopyary(int *c,int *d);

int a[10]={5,2,4,7,8,9,6,0,3,1};

int b[10],x;

clrscr();

fcopyary(a,b);

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

printf("\n%d\t%d",a[x],b[x]);

getch();

}

void fcopyary(int *c,int *d)

{

/* c,d are integer pointers */

/* c=a means c=&a[0] base address */

/* d=b means d=&b[0] base address */

/* c++,d++ means move the pointer */

/* to next array element */

/* The line *d=*c means */

/* copy the value at c into value at d */

int x;

printf("\n Copying array a(c) to array b(d) :");

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

{

*d=*c;

d++;

c++;

}

}

Page 97: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [97]

SSttrriinnggss We know, we can store numbers, characters, sounds, images, video clips etc in the

computer. When characters are put together, it becomes a „String‟. In programming, the

meaning of string is set of characters. For example “ABCD”, “India”, “Vishal” are all

strings. The string can be used to store noun or name (of men, objects,etc.) Lets now

learn to use string in C language.

String - set of characters, may be stored in a variable. For example, we can use a variable

x to store a string like “New Delhi”. Actually, a string is strored in the form of (set of)

individual characters. These characters one after the other are actually in the form of

array of characters.

Like integer, character, long, float etc „string‟ type data is available in almost all

languages, but unfortunately such data type is not available in C. In C you have to declare

a character array to store a string. That is, character data type is used for string. The

general syntax for this declaration is :

char stringname[size] ;

For example,

char x[10] ;

This declaration of array x[10] will create elements like x[0], x[1],…..x[9]. Each element

can hold one character. For example to store a name like “Raju”, characters „R‟, „a‟, „j‟,

„u‟ are stored in x[0], x[1], x[2], x[3]. Apart from this, a special character known as „\0‟ is

added at the end of string. That is „\0‟ is stored in element x[4] of the array.

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

R a j u \0

Because of this „\0‟ special character, computer can identify that it is string. Otherwise it

is just a collection of characters.

In case of array in C, the array name = address of its zeroth element. For example, if

“char x[10]” is an array, then x[0], x[1],….x[9] will be its elements. Here, when we type

only “x” (without subscript), it is as good as saying &x[0]. In short x=&x[0]. This

address is also called as base address.

Note : In C Array name = address of its zeroth element.

Now lets take an example. Suppose we want to write a program, which asks the user to

type his name. Then simply display “Welcome” + that name. Like “Welcome Raju”.

Using scanf, printf functions this program may be written. Here an array whose name is

vname is used. When using printf, scanf for strings, keep in mind the following two

things:

Use %s format string (instead of %c).

When using %s do not use &.

Page 98: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [98]

(Why? The reason is; Array-name = address of its zeroth element. Therefore if array

name is x[10], then only x (without subscript) = &x[0]. So even when we do not type &,

it is there- hidden in it…!)

Program 54. Write down a program which will ask name to the user and then display a

welcome message using scanf, printf.

main( )

{

char vname[10];

clrscr( );

printf(“Please Enter your Name :”);

scanf(“%s”, vname);

printf(“Hi, %s Welcome! ”,vname);

getch( );

}

String functions C language has many string functions. Few of them are listed as follows:

Function Header File Use

gets conio.h wait and get a string from user

puts conio.h Display a string on screen

fgets stdio.h Read a string from a file

fputs stdio.h Write a string to a file

strcpy stdio.h Copy strings

If any of these are to be used, just add following lines to the program:

#include <conio.h>

#include <stdio.h>

We could use gets, puts functions instead of scanf, printf in the above program. The

names of these functions are easy to remember. gets = get string, puts = put string.

strcpy is yet another useful function which is used to copy one string to another string.

For example, the following line will copy string ”Venkatesh” to x (array).

strcpy(x,”Venkatesh”);

Remember, we can not simply write x= “Venkatesh”; for doing this this.

Program 55. Write down a program which will ask name to the user and then display a

welcome message using string functions.

#include <conio.h>

#include <stdio.h>

main( )

{

Page 99: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [99]

char vname[10];

clrscr( );

printf(“Please Enter your Name :”);

gets(vname);

printf(“Welcome ”);

puts(vname);

getch( );

}

Important : using gets function, we can enter multi word strings for getting strings like

“New Delhi”. Instead of gets( ); if scanf is used, only “New” will be stored in the array

when “New Delhi” is typed.

Declaring and Initializing string variable: In C language, we can initialze and declare string at once. In the following example,

string “Pune” is stored in string variable (char array) “town”.

char town[5] = “Pune”;

or

char town [5] = {„P‟, „u‟, „n‟, „e‟, „\0‟};

We need not even specify the size (number of elements) in this case:

char town [ ] = {„P‟, „u‟, „n‟, „e‟, „\0‟};

Program 56. Write down a C language program which will convert given string to upper

case.

In this program we want to convert all the characters of given string to upper case

(capital). If some character is already capital, them keep it as it is. There is a readymade

function for this. But we want to write a program for this.

Looking carefully at ascii table, we find that ASCII codes of lower case (small) letters are

from 97 to 122. and for Upper case (capital) they are 65 to 90. That is, if (97-65) = 32 is

subtracted, from lower case character, it will become upper case character.

The next question is how to separate the characters? Actually the characters are already

separate. For example if a string “Raju” is stored in a string variable (char array) vname,

it is actually stored as „R‟, „a‟, „j‟, „u‟ ,„\0‟. That is

vname[0] =‟R‟

vname[1] =‟a‟

vname[2] =‟j‟

vname[3] =‟u‟

vname[4] =‟\0‟

Page 100: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [100]

The first letter will be array element number 0. and nth character will be element number

[n-1]. Now using a loop, we can convert the character to upper case till we find „\0‟.

Note: Even a „char‟ type variable is stored using bits 1 and 0. One byte (8 bits) is used to

store numbers between 0 to 255. If the same number (byte) is printed using %d it is

printed like a number. When the same byte is printed using %c it is printed as a character.

For example, if byte contains number 65, it is printed as „A‟ if %c is used and 65 if %d is

used. Therefore, arithmatic operations like add/ subtract are possible on „char‟ type also.

#include <conio.h>

#include <stdio.h>

main( )

{

char vname[10];

int x;

clrscr();

printf(“Please Enter your Name :”);

scanf(“%s”, vname);

x=0;

while(vname[x] != „\0‟)

{

if (vname[x] >=97)

vname[x]=vname[x]-32;

x=x+1;

}

puts(vname);

getch();

}

Program 57. Write down a program to find the length of a given string.

Logic: The last element of a string is „\0‟ character. To find string length, it is enough to

count the number of characters starting from first character till „\0‟ is encounterd. This

can be done using : while(vname[x] != „\0‟)

/* Find length of given string */

#include <stdio.h>

#include <conio.h>

main()

{

char vname[10];

int x;

clrscr();

printf("Please Enter a string :");

Page 101: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [101]

gets(vname);

x=0;

while(vname[x] != '\0')

{

x=x+1;

}

printf("Length of the string = %d",x);

getch();

}

Program 58. Write down a program to find length of a given string using function.

Note that there are readymade functions available in C, which return the length of string.

But for pure academic (logic development) purpose, we are writing our own function.

Logic :

Finally what we want ?

length of string (using function).

String should be passed to the Function.

Passing the string = passing the address of 0th element (base address) of string array.

Actual argument = &vname[0] = vname

Formal argument, which receives this base address, should be a pointer variable, lets

say p.

There after *p will be (value at the address of 1234) = „H‟.

p++ will point to next char. That is *p will now be = „a‟.

Next p++ will point to next character. Then *p will be = „p‟.

This should be repeated till „\0‟ is found. [while(*p != '\0') ]

vname[0] vname[1] vname[2] vname[3] … vname[9

]

p

H a p p p=vname 1234

1234 5678

/* Find length of given string using user function*/

#include <stdio.h>

#include <conio.h>

main( )

{

int fnlen(char *); /*Function Prototype */

Page 102: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [102]

char vname[10];

int x;

clrscr();

printf("Please Enter your Name :");

gets(vname);

x=fnlen(vname);

printf("%d",x);

getch();

}

int fnlen(char *p)

{

int y=0;

while(*p != '\0')

{

y=y+1;

p++;

}

return(y);

}

Program 59. Write down a program that displays a scrolling message.

Logic: To display some string at desired location of screen, gotoxy( ) function may be

used. This function takes two arguments/ parameters x,y (column, row) and then places

the cursor to that position. Now if puts is used, it will be displayed at giver position on

screen. Also note the space in puts(“ Hi”).

/* Scrolling Hi */

#include <stdio.h>

#include <conio.h>

#include <dos.h>

main()

{

clrscr();

int r=20,c;

for(c=1;c<=75;c++)

{

gotoxy(c,r);

puts(" Hi ");

delay(100);

}

Page 103: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [103]

getch();

}

Exercise:

Write down a program which will convert given string to lower case.

Write down a program which will encode a given string, print the encoded string then

decode the given string and print it again. [Hint : Add some constant number (say 5) to

each element of string to encode it.]

Page 104: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [104]

FFiillee HHaannddlliinngg Until now, we have seen the programs which use only RAM memory. (For example the

program to sort numbers or find square roots etc.) Once the program ends, or computer is

switched off, the data is lost.

If we want to store data in computer for later use, we must use secondary memory (hard

disk, floppy disk, pen drive etc.). The data in secondary memory is stored in the form of

files and directories (folders). Using C language we can write a program to read a file,

create new file, store data in a file.

For this, some I/O (input/output) functions are available. These functions can be divided

in two groups:

High level Disk I/O functions.

Low level Disk I/O functions

In this book only High level disk I/O functions are discussed. High level disk I/O

functions are further classified as Text and Binary.

High level TEXT disk I/O functions Using high level disk i/o functions we can open a file, read it, and write some data in it.

Functions like fopen, fclose, fgetc, fputc, fgets, fputs, fscanf, fprintf are available for this.

Obviously, we should tell which file is to be opened/ closed. Suppose the file to be

created/ opend/ closed is “employee.txt”.

The name of file is not directly given to the function, it is given indirectly. Meaning the

pointer of the file is given to the function. Suppose we are using pointer f1, which will

point to file “employee.txt”. That is instead of “employee.txt”, we will refer it by “f1”.

In a way, f1 is working quite like a variable. Let‟s think of it as a variable of type FILE .

(Actually it is not variable, it is a pointer to structure). Just think so for making it simple.

To declare it type:

FILE *f1;

File is not a variable, actually it is a structure, and it is defined in „stdio.h” header file.

Once such a structure is declared, it can be used just like a variable. If it appears difficult

at first sight, right now just remember that “FILE *f1; must be written to open a file”.

Second, we should connect f1 and “employee.txt”. But unfortunately in C, this can not be

done simply by typing f1=“employee.txt”;. For this (connection) a function is used.

Opening a file: The function fopen is used to open a file.

f1= fopen (“filename”,”mode”);

In place of “mode” one of the following string is used :“r”, “w”, “a”, “r+”, “w+”, “a+”

mode Purpose

r Open the file for

reading only

If the file is existing, it will be opened otherwise there will be

„error‟

w Open the file for If the file is not existing, it will be created. If a file already

Page 105: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [105]

writing only exists, a new of same name will be created (old existing file

will be replaced).

Use : for new file.

a Open the file for

adding data

If file exists, new data will be added to it. If file does not exist,

it will be created.

Use : for new and existing files.

r+ Like r but for reading and writing too

w+ Like w but for writing and reading too

a+ Like a but for reading and writing

For example :

FILE *f1;

f1 = fopen(“employee.txt”, “r”);

Here employee.txt file will be opened, this file will be opened for for “r” that is reading

only. After these lines, the file is now available and it can be refferred by f1. (As if

f1=employee.txt)

Closing a file: The function fclose is used to close a file. General syntax:

fclose(file pointer);

For example:

fclose(f1);

Character by character Input/Output Operations: Function fgetc( ) is used to read a file character by character. Ofcourse, the file must be

first opened by using fopen( ). The function fgetc( ) reads one character from the file.

Next time the function is called, it will read the next character. The file pointer moves

one character position everytime.

General syntax : variable = fgetc(file pointer);

For example

x=fgetc(f1);

The following line will fetch first character from that file. For example if the file contains

text “welcome to India”, then the first character „w‟ will be stored in the variable x. Next

time, the same line x=fgetc(f1); will store „e‟ in the variable x.

In the same way, fputc( ) function is used to write a single character to a file. The file

should be opend by using „w‟ (write) mode. This function needs two parameters. First,

the character to be written and second the file pointer (in which it is to be written).

General syntax : fputc(c, file pointer);

For example : fputc(c,fp1);

FILE *f1;

f1 = fopen(“employee.txt”, “w”);

fputc(c,fp1);

Page 106: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [106]

String or line Input / Output Operations in files : Just like character by character read/

write, the functions fgets( ) and fputs( ) are used to read/write a string (word by word or

line by line).

General syntax : fputs(string, file pointer);

For example

fputs(“How are you ? ”,f1);

This line will write the string “How are you ? ” to a file (directed by) f1.

General syntax : fgets(string_variable, length, file pointer);

For example

fgets(s,50,f1);

The above line will read 50 characters from a file shown by f1, and store it in a string

(char array) named „s‟. This „s‟ string is actually a char array. It must be declared in

advance like : char s[100];.

Formatted integer/float/char/string I/O Operations: The function fgetc, fputc, fgets, fputs read/ write character data. Similarly to read/ write

numbers, char, strings in a file or from a file fprintf, and fscanf functions are available.

Function fprintf( ) is quite like printf, only here we have to specify the name of file on

which data is to be written.

General syntax : fprintf(file pointer, “%formatstrings” , variables);

For example

fprintf(f1,”%d,%f%s”,x,y,z);

This line will write the contents of varaibles x, y, z to the file, directed by f1.

Similarly, fscanf( ) function will read numbers, chars, strings from a file. This function

again is quit like scanf function, except we have to specify the name of file from which

data is to be fetched.

General syntax : fscanf(file pointer, “%formatstrings” , &variables);

For example

fscanf(f1, “%d,%f%s”,&x,&y,z);

The above line reads a file (directed by f1), and gets the integer, float and character data

and stores that data to the varaibles x,y and z (char array) respectively.

Program 60. Write a program to read data from keyboard, write it to a file.

Logic: The user will type some characters, our program should receive those and write

that on a file. Though the task appears very simple, but let‟s be careful. First let‟s think

step by step what should be done:

Get data from user through keyboard. To get the data character by character, lets use

function getche( );. This function getche( ); gets character from user and displays

them on screen. The character enterd by user should be received in some char

variable (say x). The line x=getche( ); will do this. For example if the user presses the

key „V‟, then this character will be stored in variable x. [x= „V‟].

Page 107: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [107]

Before that, x variable should be declared [char x;]

This character is to be written to a file. Therefore lets use fopen to open a file. The

line f1=fopen(“sample1”,”w”); will open the file sample1 in “w” (write) mode.

Therafter, we can refer to the file using pointer f1.

Again f1 must be declared before that. [FILE *f1;]

The step1 is to be repeated again and again. How far? as long as users wants, this

should be repeated. After that, the user will press Ctrl+Z. The “Ctrl+Z” keystroke

sends a special character through keyboard. This special character Ctrl+Z is called as

„EOF‟ (End of file character). The loop of getting the character and writing to file

should be repeated till the user types Ctrl+Z (EOF). That is, as long as x is not EOF.

The line while(x!=EOF) will do this.

Which-ever character the user types, should be written to the file. The function

putc(x,f1); may be used to do this.

At the end, when user enters „EOF‟, file should be closed by using fclose(f1);

Apart from this, there should be some appropriate message for the user like “Please

Enter few characters / lines and finally press Ctrl+z” .

As we are using FILE structure, “stdio.h” file must be included, by typing

#include<stdio.h> even before the main( ).

/* Program to get charaters from user and write those to a file */

#include <stdio.h>

#include <conio.h>

main()

{

FILE *f1;

f1=fopen("sample1.txt","w");

char x=‟ ‟;

clrscr();

printf(“Enter few words and press Ctrl+z”);

while(x!= EOF)

{

x=getche();

fputc(x,f1);

}

fclose(f1);

}

Output

Please Enter few characters / lines and finally press Ctrl+z

God, Give me pations! but please hurry up ! ^z

Page 108: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [108]

The file sample1.txt may be opened using notepad to check this.

Important : Note the line char x = „ ‟ ; in the program. As the “while loop” checks the

condition (x != EOF), and the line x=getche(); is inside the loop, there should be some

initial value to variable x.

Alternatively we could use while(1). This will be contionuous loop, and when the user

enters EOF, an if statement may be used to come out of loop:

while(1)

{

x=getche( );

fputc(x,f1);

if(x== EOF)

break;

}

fclose(f1);

This could also be done by using x=getche( ) in the condition part of while, getting the

character and checking it whether it is not EOF :

while((x=getche( )) != EOF)

{

fputc(x,f1);

}

fclose(f1);

In this (last) method there is no need to use braces { }, because there is a single line in

block.

Error in Opening a file : We have seen that the function fopen is used to open a file.

Suppose we are opening a file using “r” (read) mode.[ f1=fopen("sample1.txt","r");] But

what will happen, if "sample1.txt" file is not at all there on the disk?

In that case, the function returns NULL value. Meaning, NULL will be stored in f1.

In write mode too, such problem may arise. This will happen if the file could not be

opened / created. This can happen if there is no space on disk (or if disk is

„write protected‟ or any other reason).

That is, immediately after a line like “f1=fopen(“sample1”,”r”);” our program should first

check whether the file was successfully opened or not. If there is NULL in the f1, there

was some error. In that case, the program should not execute the next lines. One “if ” may

be used to check this. If there is error, [meaning if (f1= = NULL)] a function exit( ); may

be used to end the program.

f1=fopen(“sample1”,”r”);

if(f1= =NULL)

{

printf(“ Error in opening the file ”);

exit( );

}

Page 109: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [109]

Program 61. Write a program to read data from keyboard, write it to a file and then

again read data back from file, and display it on screen.

Logic:

The first part of program (to read data from keyboard, write it to a file), as discussed

in the previous program.

In the second part, the data is to be fetched back again from file and displayed on

screen.

The sample1.txt should be re-opened in “r” (read) mode, [ fopen(“sample1”, “r”);]

Using fgetc function, the characters should be read. [x=fgetc(f1)]

This step4 should be repeated till EOF. [while (x!=EOF)]

Using printf in the same block, the characters should be displayed.

fclose(f1); should be used to close the file.

/* Program to get charaters from user and write those to a file */

/* then again display the contents of file*/

#include <stdio.h>

main()

{

FILE *f1;

fopen(“sample2.txt”,”w”)

char x;

clrscr();

printf(“Enter few words and press Ctrl+z”);

while((x=getche()) != EOF)

{

fputc(x,f1);

}

fclose(f1);

printf(“\n Now printing the contents of the file:\n”);

f1=fopen(“sample2.txt”, “r”);

x= „ ‟;

while(x != EOF)

{

x=fgetc(f1);

printf(“%c”,x);

}

fclose(f1);

Page 110: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [110]

}

Program 62. Write a program to open a file and count number of characters, spaces,

newlines in a file “employee.txt”.

Logic : Lets think of the steps:

Open the file [ f1 = fopen(”employee.txt”,”r”) ]

Show error and end the program if (f1= =NULL) using exit( ); function.

Read the characters one by one [x=fgetc(f1);]

Use counters to count number of charecters (nc), number of spaces (ns), number of

new lines (nnl).

Declare x, n, ns, nnl, f1 variables.

When EOF is found, exit the loop and display n, ns, nnl.

/* Program : Find number of characters, spaces */

# include <stdio.h>

#include<conio.h>

main()

{

FILE *f1;

char x;

int nc=0, ns=0, nnl=0;

fp = fopen(“employee.txt”,”r”);

/* Check for errors in opening the file */

if(f1==NULL)

{

printf(“ Error in opening the file ”);

exit();

}

while(1)

{

x=fgetc(f1);

if(x==EOF)

break;

nc= nc+1;

if(x==‟ „)

ns= ns+1;

if(x==‟\n‟)

nnl = nnl+1;

Page 111: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [111]

}

fclose(f1);

printf(“\n The file employee contains : ”);

printf(“\n %d characters”,nc);

printf(“\n %d spaces”,ns);

printf(“\n %d New line chars",nnl);

}

Exercise :

Page 112: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [112]

PPrreepprroocceessssoorr,, SSttrruuccttuurreess iinn CC

C preprocessor : We know that the computer can understatnd language of 1 and 0. A program written in

HLL like C should first be compiled (converted to machine language). This conversion is

done by a program called compiler.

But even before that, yet another program called “preprocessor” first „processes‟ the

program written in C language (source code).

This preprocessor first searches the preprocessor commands or preprocessor directives.

These commands are first of all executed. These preprocessor commands begin with “#”.

There are three types of preprocessor commands in C:

1. Macro substitution directives. (#define)

2. File inclusion directives. (#include)

3. Compiler control directives. (#ifdef)

Macro substitution directives We can „define‟ some „templates‟ using this directive. For example :

#define PI 3.1415

#define PLIMIT 35 /*passing limit */

#define SQUR(n) (n*n) /* square of a number */

The words followed by #define (PI, PLIMIT, SQUR(n)) are called as macro templates.

The values/formulae (3.1415, 35,(n*n)) after the templates are called macro expansion.

When such directives are present, the macro templates in the source code are searched

and replaced by macro expansions. For example, in the source code program, where-ever

the word PI is there, it is replaced by 3.1415.

Because of this :

Program becomes easy to read. (Instead of 3.1415, PI is seen in the source code

program)

Making changes in the values of constants becomes easy. For example to change passing

marks from 35 to 40, it is enough to make change in #define.

Instead of variables, constants are put in the program. Due to this the program runs faster.

Complex formulae appear easy. For example, a line like s=3.1415 * r * r; in a program

would look like a=PI * SQUR(r);

File Inclusion directives Using the (#include) directives, we can insert a file in our program. Why do this?

If a program is too big, to make it easy it can be divided in more than one file. In that

case, to compile it together, #include can be used.

To use functions in more than one programs, simply write them in a file and “include”

that file in other programs. For example, if we have written some functions and we want

Page 113: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [113]

to use these functions in some other programs, then it is better to write such functions in a

file once and simply “include” it where ever required.

Such files are generally called header files. The extension of these files is “.h”. To

include such header files, following preprocessor directive is written:

#include <filename>

For example to include stdio.h file just write #include <stdio.h> at the beginning of the

program/ source code.

Similarly suppose if you have developed some functions in a program, copy them to a

new file. Save this file with “.h” extension (for example “myfns.h”). Now these functions

can be used later in any other file. Just “include” this myfns.h file in that program.

Difference between #include <xyz.h> and #include “xyz.h”

#include <xyz.h> : Here (when only angle brackets < > are there), header file is searched

on specified list of directories only.

#include “xyz.h” : Here (when double quotes are used) header file is searched in current

directory and specified list of directories also.

Structures : We have seen that an Array can be used to create more than one variables of same name

and type. (For example to store marks of 50 student, m[0],m[1],…m[49] variables).

Now what can be done to store the name, marks, branch etc of a single student? We can

use separate variables for each, but in that case there names would NOT be same. We can

use array for varaibles with same name, but in that case there data type would be same!

That is, here we want to store some variables together (with same name) but array can not

be used because the data type of name, marks, branch etc is not same.

Actually here it is a “record” of one student. In C language a “structure” is used in such

situation.

Structure is a constructed data type which can hold together different data types.

The general format of declaration of Structure:

struct tag_name

{

data_type memeber1;

data_type memeber2;

……..

……..

};

For example:

struct stud_rec

{

char name[20];

float marks;

char branch[10];

Page 114: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [114]

};

Here, the stud_rec itself becomes a data type. Just like int, float, char etc this “stud_rec”

becomes a new data type. To declare variables x,y of int type we write int x,y;. Just like

that, we can create variables of this new stud_rec data type:

stud_rec s1,s2;

Here stud_rec is name of the structure. s1, s2 are varaibles of this new type “stud-rec”.

The name, marks, branch are members of the structure “stud_rec”.

To assign value to the member variables (name, marks, branch) the general format is:

variable.member = value;

For example:

s1.marks = 79.57;

strcpy(s1.name,”Venkatesh”);

strcpy(s1.branch,”Comp”);

Note : s1.name is a string (char array). Therefore, s1.name = “Venkatesh”; can not be

written. The function strcpy must be used.

Similarly the structure members can be used in functions like scanf, printf, gets, puts etc.

The following program makes these things clear.

Write down a program to declare a structure, get the values for its elements from user and

then display those values.

/* Program: Demonstrates use of structures */

#include <stdio.h>

#include <conio.h>

int main(void)

{

clrscr( );

struct stud_rec

{

char name[20];

float marks;

char branch[10];

};

struct stud_rec s1,s2;

scanf("%s%f%s\n",s1.name,&s1.marks,s1.branch);

gets(s2.name);

printf("\n%s %f %s\n",s1.name,s1.marks,s1.branch);

puts(s2.name);

getch();

Page 115: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [115]

}

In the above program, two variables s1, s2 are used to store the name, marks, branch of

two students. This is sufficient for two students. What if there are 50 students like this?

Should we use 50 varaibles like s1, s2,…s50? No way!

Again here for s1,s2…s50 we can use an array. But this array will be array of structures!

The method for declaring this array is same:

struct stud_rec s[50];

This line will create 50 variables like s[0], s[1],s[2], ……s[49] ! After that they can be

used like a structure varaible. For example :

s[1].marks = 79.57;

strcpy(s[1].name,”Venkatesh”);

strcpy(s[1].branch,”Comp”);

Page 116: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [116]

TTiippss,, TTrriicckkss aanndd TTrraappss Following is the list of some “practical” tips. These can make the program more easy to

read as well as edit. This is more important when working in team (like working on

projects).

As far as possible, use simple logic.

Use proper “indents” (Use TAB key) while typing the source code. All the lines

within a block (between opening and closing curly brackets) should be indented. This

makes the program easy to read. For example :

main( )

{

/* The lines in this block are indented */

…….

…….

if (x>10)

{

/* These lines are further indented */

…………

…………

}

}

Because of this, closing curly brace looks exactly below the corresponding opening

curly brace. Another advantage is that there is little chance of forgetting the closing

curly brace.

As far as possible, the variable names should be self- explaining. For example instead

of using varaibles like b, h it is better to use varaibles (names) like base, height etc.

Give proper file name to the program (source code) file. For example a program used

to find area of rectangle may be named as “rectarea.c”. Generally the beginners tend

to use filenames names like xyz, prog1, rajesh etc. Similarly it is good idea to save

our files in separate folder, if the same computer (PC ?) is used by many.

The last line of C program should be “getch( );”.

The condition in “if statement” should be as much simple as possible. For example

sometimes instead of using && operator, nested if staments may be used. Refer

program number ......

Use brackets ( ) whenever there is doubt about the Hierarchy of operations.

For example : in statement like x=a+b*c; we want addition of a and product of b and

c, there is no need to use brackets. But even if we use brackets, there is nothing

wrong. Here the meaning of x= a+b*c; and x=a+(b*c); is same.

When x = (a+b) / (2*c); the brackets must be used. Otherwise if we omit the brackets

and write x=a+b/2*c; it will mean x=a+( (b/2) * c);

Page 117: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [117]

If some lines (group of lines) are being repeatedly used, it is better to write a function

for the same, and call that function.

Operators like ++, -- should be used very carefully. There is small difference between

y=x++; and y= ++x;. One is post-increment and another is pre-increment. If initially

the value of x is 3, then y=++x; will make values both x and y same equal to 4. On

the other hand statement like y =x++; will increment value of x and make it 4, but

value of y will be 3 only! Because in first case it is “increment and assign” and in

second case it is “First assign and then increment”.

Advantage of using x++; over x=x+1; is that x++ works faster. But habit of using ++

or -- may become headache in other programming languages.

In the learning phase (in the beginning), it is better to use simple statements instead of

using ++, --, += etc. These operators are spefic to C language.

+=, -=, *=, /= are called as compound assignment operators. x+=2; is short form of

x=x+2;. Here, use of += operator practically does not give great advantage, unless

you are preparing for C language exam.

Tricks

x+=2; is same as x=x+2;. To remember the meaning of such compound operators,

there is trick. Think of first varaible like LHS (x=). Then drop “=” in “x+=2;”, it gives

RHS (x+2).

To find the output of given program (“Hand run” or “Dry running of algorithm”):

First write all the variables (including loop counters) used in the program, on a paper,

like:

a 2 25

b 5

c

x

Now carefully read each line and write the values of these variables on the paper on the

corresponding line (on paper). For example if a line in program is a=2; then write 2 in

front of „a‟ on the paper.

If the value changes after that, write new value there. For example in the same program

next line is a=a+23 or a=25 then put a strikethrough on 2 and write 25 on the

corresponding line on paper.

Apart from this, write output on screen on the paper.

For example suppose we want to find the output of following program.

int main()

{

clrscr();

int x=4,y,z;

y= --x;

z=x--;

Page 118: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [118]

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

}

Write the values of x,y,z and display output on paper as follows:

x 4 3 (--x) 2 (x--)

y 3

z 3

Display 2 3 3

When you read the line int x=4, write 4 infront of x on paper. When you read y = --x;

scartch 4 and write 3 for x and 3 for y. Next when you read z =x--; write 2 for x and 3 for

z (as it is „assign and then decrement‟).

Traps: Even after learniing C language, there can be lot of problems in successfully running the

program. In the beginning ther can be 10 errors/warning in a program of 5 lines! Just

don‟t worry, everyone goes through this phase. If you are getting errors, may be you have

made one of the following mistakes. :

Typing Printf instead of printf. (Capital P)

Forgetting & in scanf

Using & in printf.

Using & in scanf for string.

Using a variable without declaring.

Spelling mistakes in variable name.

Upper case – lower case <capital/small> mistake in variable name.

For example : int Rad; and rad=50; here These two variables are seperate variables.

The variable rad is not at all declared. (Rad is declared).

Forgetting semicolon “;” at the end of a statement. In this case the compiler shows

error on next line. Because up to semicolon it is same line for the compiler. For

example, if following two lines are there in a program, the compiler will show error

on second (scanf) line :

printf("\nPlease enter a number :")

scanf("%d",&x);

Use of “unwanted” semicolon:

main( ) ;

if( );

else ;

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

Use of single = (assignment) instead of double = = (is equal to).

Page 119: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [119]

Improper use of format string. For example, use of %d instead of %f.

Using integer division when finding “float” result. For example: on the following

line even if avg is float, the ressult may be wrong:

avg=tot/3;

Instead it should be :

avg=t/3.0; Or

avg = ( (float) t ) /3 ; (type casting);

Page 120: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [120]

RRee--vviieeww……..!! Now it is time for review. Apart from review, this chapter contains lot of information

about C language in ready reference form.

Program : The program is a list of instructions for the computer to carry out given task.

There can be different paths for going from one place to another. Some paths may be

shorter some may be longer. Some paths may be easier and some may be difficult.

Naturally some of them may take longer time and others may require less time!

Just like that there can be different ways (methods) of doing the same task. Some of these

methods may take less time and others may require more time. In programming too there

are different algorithms for the same program. Some algorithms are faster and some are

slower.

Algorithm : The list of procedures or steps is called algorithm. The algorithm will be in

human language. Therefore algorithm is same for program written in different languages

like C, Pascal, Fortran, Basic etc. Offcourse there can be different algorithms for same

task.

Flow charts : It is graphical representation of sequence of instructions.

The flow chart shows different instructions and their sequence in graphical form.

Instructions are written in boxes of different shapes. For example for Input/ output

parallelogram is used, for process rectangle, and for decision rhombus is used.

Dry running of algorithms: Once an algorithm is decided the output of the algorithm is

checked by dry running or by performing „hand run‟. In this 'dry running' we check what

the computer/ compiler would do at each step. Here we do it without actually running the

program on computer.

C Fundamentals Character Set : A „character‟ in a programming language means a single letter (alphabet),

digit, special symbol. For example „a‟, „y‟, „5‟, „#‟ etc.

In C language only following characters are allowed:

A,B,……,Z

a,b,……..,z

0,1,2,..…,9

~ „ ! @ # % ^ & * ( ) _ - + = | \ { } [ ] : ; “ < > , . ? /

Constants : A constant is a quantity that doesn‟t change. For example a number, a

character etc. There are different types of constant namely Character constant, Integer

constant, Real constant.

For example „a‟, „b‟ are character constants, a number without decimal point is an

integer constant. A number with decimal point (e.g. 345.67 or 5.0) are examples of Real

constant.

Page 121: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [121]

Note that the character constant must be enclosed in a single quote. If quotes are omitted

then it can not be called as a character. Even double quote is not allowed for single

characters because then it becomes a string. That is „a‟ is a character but “a” is a string!

Data Type : The kind of data variables may hold in a programming language is called its

data type.

Data can be of different forms like character, number, text, picture, sound etc. C

language supports four different classes of data types.

Primary or fundamental data type

User defined data types

Derived data types

Empty data set

Following data types called as fundamental data type are most commonly used in C

programs:

int : This is basic integer data type. A variable on int data type can hold a number without

decimal fraction. Even if an attempt is made to store a number with decimal value, the

fraction part is ignored. The number is truncated and not rounded off. For example if a

variable x is of int type and we write x = 7.97; in a program then x will hold its integer

part 7 (and not 8).

float : This is another basic data type. A variable of float data type can hold a number

with decimal value.

char : This data type can hold both a character as well as a number. If it is used to store a

number then it can store a number from -128 to 127. But generally it is used to store

character data.This data type can hold a single character like „A‟, „b‟, „?‟ etc. An array of

char may be used to store long character strings like name, town etc.

Following table shows four fundamental data types (char, int, float, double) and its sub

types:

Type Bits Bytes Range Format

char or

signed

char

8 1

-128 to 127 %c

unsigned

char 8 1

0 to 255 %c

int or

signed

int or

short int

16 2

-32,768 to 32,768 %d

unsigned

int or

short

unsigned

16 2

0 to 65,535 %u

Page 122: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [122]

int

long or

long int

or long

signed

int

32 4

-

2147483648

to 2147483647 %ld

long

unsigned

int

32 4

0 to 4294967295 %lu

float 32 4 -3.4 e 38 to +3.4 e 38 %f

double 64 8 -1.7 e 308 to +1.7 e 308 %lf

long

double 80 10

-1.7 e 4932 to +1.7 e 4932 %Lf

Key words : Keywords are reserved words of the language, the meaning of which word is

predefined in the language, which can not be changed.

Therefore these words should not be used as variable name or function name. For

example you can use a variable roi to store the rate of interest but you can not use a

variable named “int”, because this (int) is a keyword in C language. There are 32

keywords in C language. The following table shows keywords of C language:

auto const double float if register static union

break continue else far int return struct unsigned

case default enum for long short switch void

char do extern goto near signed typedef while

Identifiers : Identifiers refer to the names of variables, functions and arrays.

Variables : In case of programming, Variable is name given to the location where the

data is stored.

Variable is a quantity which can vary (change). Variable is like a container that contains

some thing (number, character). The variable has a name. That is when we say,

x=5; x is variable name and the content of variable is 5.

In C language a variable must be declared before it is used.

Generally we tend to use a single character long variable name like x, y, z etc. (like we

used to do in algebra) . Though this is allowed in C language, it is advisable to go for a

descriptive variable name. For example instead of using variable names like r,a for

radius, area of circle, it is better to use the variable name like rad, area etc.

Variable Name Rules :Variable name should be decided considering the following rules.

Length of variable name should be between 1 to 8. Some compilers allow 40

character long variable names.

Page 123: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [123]

It can contain alphabets and digits both. But its first character must be alphabet. For

example rad2 is OK but 2rad variable name is not allowed.

Comma or blank space is not allowed. But underscore can be used in variable names.

For example “perc mks” is invalid but perc_mks is valid variable name.

Except underscore, special symbol like *, &, etc are not allowed.

Declaration : In C language the variable must be declared before it is used. The

importance of declaration is that, once a variable is declared, the computer reserves

required number of bytes in memory. For example when an integer variable is declared it

will reserve two bytes of memory.

Operators : An operator is a symbol that tells the computer to perform certain

mathematical or logical manipulations. Operators are used in programs to manipulate

data and variables. They are used in mathematical or logical expressions. +, -, *, /,%, &,

=, <, = = are all examples of operators. In all there are more than 32 operators in C

language.

Unary and Binary : Unary operators operate on a single quantity (variable or constant or

expression), whereas binary operators operate on two quantities.

Arithmetic : Arithmetic operators with their meaning are shown below:

Operators Meaning

+ Addition or unary plus

- Subtraction or unary minus

* Multiplication

/ Division

% Modulo division

Relational : The relational operator are used to compare two quantities. Relational

operators are shown in the following table with their meaning.

Operators Meaning

< is less than

> is greater than

<= is less than or equal to

>= is greater than or equal to

= = is equal to

!= is not equal to

Note that for “not equal to” the sign # is not used. Similarly for is equal to single = is not

used.

Logical : Logical operators combine two or more relational expressions.

Operators Meaning

&& logical and

|| logical or

! logical not

Page 124: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [124]

Assignment : Assignment operators are used to assign the result of expression to a

variable. = is an assignment operator. For example x=7; it is “assign 7 to variable x.”

In addition to this, there is a short hand assignment operator available in c language. It is

of the form:

variable operator = expression;

For example x + = 2; is same as x = x +2;

Hierarchy of operators : When two or more operators are there in an expression, then

there is some priority of operations. This is called as hierarchy. For example if

multiplication and addition both are there, multiplication is done first. If the two

operators are there with same priority then it is evaluated from Left to Right. The

following table shows the hierarchy of operators:

Operators Type

! Logical NOT

* / % Arithmetic

+ - Arithmetic

< > <= >= Relational

== != Relational

&& Logical AND

|| Logical OR

= Assignment

For example if an expression is x=5+4*7-6/2 it is evaluated as follows:

x= 5+4*7-6/2

x= 5 + 28 – 3

x= 33 -3

x= 30

Expressions : An expression is combination of variables, constants, and operators

arranged as per syntax of language. An expression consists of one or more operands and

zero or more operators linked together to compute a value. Following are some examples

of expression

y=x+3;

t = 2 * 3.14 * sqrt(l/g);

x++;

++x;

x+=3;

Function : A function is a block of code that perform a specific task .

Each program is made up of few functions. main( ) is one of the functions. Execution of

the program starts from main function.

Page 125: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [125]

Within a function another function is “called”. A function can call to another function.

Even a function can call itself (recursion). Recursion is a process where a function calls

itself.

Need / advantages of using function :

A function can be called many times therefore repetition of same code is avoided.

As the task is broken up in parts, the program becomes compact and readable.

Debugging becomes simple.

Once a function is written, the same can be used in many programs by many

programmers. So improves productivity.

As the functions are just like programs, functions also may take some input and may give

some output. The input to the function is called “parameter” or argument. The argument

is supplied by the calling statement.

Input -> Program -> Output

Similarly

Arguments -> Function -> Returned value

Passing arguments : In previous sections we have seen some programs which take some

input and then give some output. For example a program takes radius of a circle as input

and gives the area of circle as an output.

Call by value & call by reference : When a function is called by passing the values (of

variables) as arguments then it is called as call by value. For example on the following

line the function addnums is called and the values of a and b are passed to the function:

addnums(a,b);

Alternatively it is possible to pass the address of these variables as argument to a function

in such case it is called as call by reference. When a function is called by passing the

address of variable(s) as arguments then it is called as call by reference. For example on

the following line the function addnums is called and the addresses of a and b are passed

to the function:

addnums(&a,&b);

Call by value is simple method but in this method if the (formal) arguments are changed

within the function then there is no effect on the actual arguments.

On the other hand in case of call by reference the address of variables is passed to the

function so the function can directly change these values. (Therefore it can be used in

situations like interchanging contents of variables). When a function is called by passing

the addresses of variables as arguments then it is called as call by reference.

Using call by reference we can get the effect of „return‟ of more than one variable.

To use a function in many programs, the function is saved in a separate file. This file

which may contain many functions is called as header file. Generally there extension is

“.h” . Such file can be included in any (other) program using following line at the

beginning of the program:

#include <filename>

Page 126: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [126]

So when you write a function, and you want to use the same function in several

programs, there are two ways.

1. You can rewrite or copy the same function in all files.

2. You can write the function in a header file. Then attach this header file to all programs,

using #include.

Library functions : C compilers contain header files which carry huge number of ready

made functions. These are called as library functions. The frequently used printf, scanf,

getch, clrscr, sqrt, pow are all library functions. Following table shows most frequently

used library functions.

Function Header File Use

printf stdio.h display message, variable etc on screen

scanf conio.h get user input

clrscr conio.h clear the screen

getch conio.h wait and get a character from user

gets conio.h wait and get a string from user

puts conio.h Display a string on screen

pow math.h calculate xy

sqrt math.h calculate square root

fopen stdio.h Create / Open a file

fclose stdio.h Close a file

fgetc stdio.h Read a single character from a file.

fputc stdio.h Write a single character to a file.

fgets stdio.h Read a string from a file

fputs stdio.h Write a string to a file

fscanf stdio.h Read (formatted) data from a file

fprintf stdio.h Write (formatted) data to a file

strcpy stdio.h Copy string.

If you want to use such functions, its header file must be attached (using #include). For

example if you are using printf, scanf functions in your program, you must write

following lines in your program at the beginning:

#include <stdio.h>

#include <conio.h>

User defined functions: Like the readymade library functions available, a programmer

can write his own function. These functions are called as user defined functions.

The following sample program shows function prototype, function definition, actual

arguments (sub1, sub2, sub3), formal arguments (a,b,c).

main( )

{

Page 127: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [127]

/* Program for finding out average of marks of 3 subjects */

int sub1,sub2,sub3,total;

float p;

/* Following line is function declaration or Function Prototype */

float fnavg(int,int,int); /* Function Prototype */

printf(“Please Enter the marks of three subjects “);

scanf(“%d%d%d”,&sub1, &sub2, &sub3);

/* Following line is function call */

p= fnavg(sub1,sub2,sub3);

printf(“%f”,p);

getch();

}

/* Function Definition */

float fnavg(int a, int b, int c)

{

float d;

d = (a+b+c)/3.0;

return(d);

}

Arrays : An array is a group of related data items that share a common name. For

example data like set of characters, set of numbers (like marks of few students, or names

of employees).

Declaration of array : General form of array declaration is :

type array-name[size];

For example int marks[5]; char empname[15];

Initializing array elements: General form of initializing array elements is:

type array-name[size]={list of vaues} ;

For example : int marks[5]={45,77,56,98,86};

In the above example declaration as well as initialization is done at once. In this case the

[size] parameter may be omitted. That is,

int marks[ ]={45,77,56,98,86}; is allowed.

Two dimensional array declared as follows:

type array-name[row_size][column_size];

Initializing a two dimensional array:

int pricetbl [2] [3] = {11,33,55,44,66,88};

or

int pricetbl [2] [3] = { {11,33,55} , {44,66,88} };

or

int pricetbl [2] [3] = {

Page 128: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [128]

{11,33,55} ,

{44,66,88}

};

Strings: In C language, a string is an array of characters. For example “Nagpur” is a

string constant.

Declaring a string variable.

char string_name[size];

For example, char city[15];

Declaring a string variable and initializing at once: There are two methods of declaring

and initializing an array at once:

char city[10] = “Mumbai”;

char city [7] = {„M‟,„u‟,‟m‟,‟b‟,‟a‟,‟i‟,‟\0‟ };

To assign a string to an already declared array, a function strcpy should be used.

For example : strcpy(city,”Mumbai”);

To read the string from keyboard (that is to get it from user) scanf or gets functions may

be used.

char city[15];

scanf(“%s”,city);

or,

gets(city);

Remember that here %s is used instead of %c. (Also note „&‟ is not used)

The scanf can NOT be used to get a multiword string (string having a space). For

example the user types “Pimpri Chinchwad” for city then only “Pimpri” will be assigned

to string variable city!

The function gets( ) can be used to get a multi word string.

Displaying a string on screen: For this purpose the printf, puts functions may be used.

printf(“%s”,city”);

or,

puts(city)

The function puts( ) can display only one string at a time. The puts( ) functions adds a

newline, that means the cursor will be place on next line after puts( ) .

pritnf puts

can display more than one

variables

can display only one variable at a

time

Does not add automatically \n Adds automatically after puts \n

one printf is enough to display two

strings

Two puts are required to display

two strings

combinations of strings and

numbers can be displayed

can display only string

Page 129: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [129]

C preprocessor : It is a program which processes the source code before it passes through

the compiler. That is, before compilation, the preprocessor looks for “preprocessor

command” (or preprocessor directives) in the source code file. If these commands are

there in the source code, appropriate action is taken. Theses commands begin with the

symbol #. There are three types of preprocessor commands:

1. Macro substitution directives. (#define)

2. File inclusion directives. (#include)

3. Compiler control directives. (#ifdef)

Advantages of preprocessor:

Program becomes readable and easy to understand.

Compiler generates faster code if constants are used instead of variables.

Making change at the beginning is enough to make changes in entire program.

Storage classes in C: Storage classes in C are the keywords which determine where the

value of a variable will be stored.

Storage class decides:

Where the value of a variable will be stored.

What will be the default value of the variable.

Scope of the variable

The life of variable.

There are four storage classes in C namely, Automatic, Register, Static, External.

Storage class Location Default

Value

Scope Life

Automatic Memory Garbage Local to block

where it is

defined

Until Control is in

that block

Register CPU

Registers

Garbage Local to block

where it is

defined

Until Control is in

that block

Static Memory Zero Local to block

where it is

defined

value is retained

between different

function calls

External Memory Zero Global Throughout the

program

Structures : It is a constructed data type which can hold together entities of dissimilar

data types.

General format of declaration of a structure:

struct tag_name

{

data_type memeber1;

Page 130: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [130]

data_type memeber2;

……..

……..

};

For example:

struct book_details

{

char title[20];

char author[20];

float price;

};

Later variables of this data type can be declared like:

struct book_details book1, book2, book3;

Assigning values to members:

variable.item = value;

For example :

book1.price = 70.00;

strcpy(book1.title, "Basic Physics");

Formatted printing: The printf function contains % symbol followed by a letter

when used for printing contents of variables. Following table shows the variable type and

the format character used

Data type Format character

integer %d

Long %ld

short unsigned %u

Long unsigned %lu

Float %f

double %lf

character %c

string %s

To get more control over the display, optional width and justification parameters w.n may

be added between % and format character. w specifies width and n specifies number of

digits after decimal.

For example %10.2f will print a floating point number in 10 columns (10 spaces) with 2

decimal places. To display it left aligned, - sign may be added. For example %-10.2f will

display same number left aligned in given space.

The following program makes the point clear:

Page 131: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [131]

/* Program: Demonstrates use of %d, %f */

#include <stdio.h>

#include <conio.h>

int main(void)

{

clrscr();

int x=5;

float y=2.76;

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

printf("\n%5d",x);

printf("\n%-5d",x);

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

printf("\n%5.1f",y);

printf("\n%5.2f",y);

printf("\n%-5.1f",y);

getch();

}

Output:

5

5

5

2 . 7 6 0 0 0 0

2 . 8

2 . 7 6

2 . 7 6

Page 132: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [132]

Program 1.Write down a C program which will find average (Percentage) of marks in three

subjects. ............................................................................................ 16 Program 2.Write down a „C‟ program which will ask two numbers to the user, store them in two

variables a and b then interchange their values. ........................................... 17 Program 3.Write down a program which will find simple interest on given principle at given

rate of interest for a given period. ............................................................ 18 Program 4.Write down a program which will find compound interest on given principle at given

rate of interest for a given period. ............................................................ 19 Program 5.Write down a program which will display the ascii code and corresponding character

of a given number. ............................................................................... 20 Program 6.Write down a program to interchange contents of two variables without using third

variable. ............................................................................................ 20 Program 7.Write down a C language program which will accept a number and print whether

that is odd or even. .............................................................................. 26 Program 8.Write down a program which will accept an year- number and print whether that

year is Leap or not. .............................................................................. 26 Program 9.Write down a program to find the biggest of three numbers.

....................................................................................................... 28 Program 10.Write down a program which will find square roots of a quadratic equation.

....................................................................................................... 29 Program 11.Write down a program to add, subtract, multiply, divide given numbers when keys

+, -, *, / are pressed respectively. ............................................................ 33 Program 12.Write a function to accept month (1 to 12) and print name of month using switch

statement. ......................................................................................... 34 Program 13.Write down a program which will display larger of two numbers using conditional

operator. ........................................................................................... 36 Program 14.Write down a program which finds sum of three numbers a,b,c when their values

(entered by the user) are within range, and displays „Invalid Data‟ otherwise. ...... 38 Program 15.Write down a program which finds sum of three numbers a,b,c when their values

(entered by the user) are within range. ...................................................... 38 Program 16. Write a C program that asks PIN number and repeates it till user types correct PIN number. 41 Program 17. Write down a C language program to find the sum of first 50 natural numbers. 44 Program 18. Write down a C language program to find factorial of a number. ................ 45 Program 19. Write down program to find sum of digits of a number. ............................ 46 Program 20. Write down program to check wheteher a number is Armstrong number or not. 47 Program 21. Write down program to find whether a number is prime or not. ................. 48 Program 22. Write down a program which will print following pattern:......................... 49 Program 23. Write down a program which will print following pattern:......................... 50 Program 24. Write down a program which will print following pattern:......................... 50 Program 25. Write down a program which will print following pattern:......................... 51 Program 26. Write down a program which will print the following pattern: .................... 52 Program 27. Write down a program which will repeatedly accept a number and display its square root till user enters 0. .............................................................................. 53 Program 28. Write down a program which uses do..while loop to repeatedly find square root of numbers untill user enters 0. ............................................................................ 54 Program 29. Write down a program which will find average of set of n numbers. ............ 55 Program 30. Write down a program which will print the multiplication tables of numbers from 1 to 10. 56 Program 31. Write down a program which will find the sum of first 10 numbers of the following series: ............................................................................................... 57 Program 32. Write down a program which will find a b without using pow function. ......... 57

Page 133: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [133]

Program 33. Write down a program which will get ages of 10 persons and count the number of persons with age between 15 to 20. .................................................................... 58 Program 34. Write down a program which will display all the ascii codes and their corresponding character. (ASCII Table) ................................................................... 59 Program 35. Write down a program which will generate and print first n fibonocci numbers. 59 Program 36. Write down a program to display a circle which increases in size. ............... 60 Program 37. Write down a program to check whether a number is palindrome or not. ...... 61 Program 38. Write down a program which displays all four digit numbers which are even and divisible by 7. 62 Program 39. Write down a program display a number in binary format. ........................ 62 1) As the task is broken up in parts; the program becomes simple, compact. .............. 65 2) Use of function avoids repeatation. In the above example, if function were not used, the lines for calling meeting would be repeated two times. ......................................... 65 3) Program becomes easy to edit. It is enough to make changes in function at one place only. 65 4) Once a function is written, the same can be used in many programs by many programmers. So it improves productivity. .............................................................. 65 Program 40. Write down a program which will find factorial of a number using recursive function. 71 Program 41. Write down a program to display a number in binary format using a recursive function. 73 Program 42. Write down a program which will accept marks in three different subjects and show the result as pass or fail. Use functions to find average and minimum. ..................... 74 Program 43. Write down a program which will ask 10 numbers, store them in an array and find the biggest of these numbers. ......................................................................... 78 Here we want to store 10 numbers in an array and then find and display the biggest of them. How we (a human) would have done this? Just a look at the list of ten numbers, and we immediately come to know which is biggest. But what if these numbers are told to us one by one ? Lets suppose the numbrs are (4, 7, 3, 8, 22, 55, 11, 73, 1, 6). ................................ 78 We would first keep first number 4 in mind. ................................................... 78 Then when the next (7) is told, we keep this in mind and leave the first (4). ........... 78 Then when the next (3) number is told we would simply ignore it and go ahead. ...... 78 In short when the next number is bigger then store it else ignore it. ..................... 78 Lets take a variable m (m for maximum) and store first number in it. (m = n[0] ;). ... 78 Next if second is bigger, put it in „m‟. That is : if(n[1]>m) then m = n[1]; ............... 79 Same process for the third, fourth… last number. ............................................ 79 That is if(n[x]>m) tr m = n[x] ; Here x varies from 1 to 9. ................................... 79 Program 44. Write down a program which will copy contents of one array to another array. 79 Program 45. Write down a program which will sort 10 numbers in ascending sequence., ... 80 Program 46. Write down a program to store 1 to 10 numbers in an array and then find sum of first 5 numbers using break statement. ................................................................... 82 Program 47. Write down a program to declare and display a two dimensional array in matrix form. 82 Program 48. Write down a program to add two, two-dimensional array in matrix ........... 84 Program 49. Write a function to initialize a square matrix of size 4 as unity matrix (leading diagonal elements as 1 and other elements as 0). ...................................................... 85 Program 50. Write down a program which will use functions to read, print, transpose, and find sum of all elements of a two dimensional matrix. ................................................ 86 Program 51. Write down a program which will multiply two given matrices. .................. 88 Program 52. Write down a program to interchange contents of two variables using function. 94 Program 53. Write down a program which will copy contents of one array to another array using a function. ............................................................................................... 95

Page 134: A. M. Joshi...methods, question-answers etc. The students get good knowledge of language syntax, they “pass” the subject, may even get very good marks; but developing a new program

Programming A New Approach * Notes * A.M.Joshi [134]

Program 54. Write down a program which will ask name to the user and then display a welcome message using scanf, printf. ..................................................................... 98 Program 55. Write down a program which will ask name to the user and then display a welcome message using string functions. ................................................................. 98 Program 56. Write down a C language program which will convert given string to upper case. 99 Program 57. Write down a program to find the length of a given string. ...................... 100 Program 58. Write down a program to find length of a given string using function. ........ 101 Program 59. Write down a program that displays a scrolling message. ......................... 102 Program 60. Write a program to read data from keyboard, write it to a file. ................. 106 Program 61. Write a program to read data from keyboard, write it to a file and then again read data back from file, and display it on screen. .................................................... 109 Program 62. Write a program to open a file and count number of characters, spaces, newlines in a file “employee.txt”. ........................................................................ 110