You are on page 1of 79

CSET 06101

Basic Computer Programming

Introduction

‗C‘ is the most widely used computer language, which is being taught as a core
subject. C is general-purpose structural language that is powerful, efficient and
compact, which combines features of high-level language and low-level
language. It is closer to Man and Machine both. Due to this inherent flexibility
and tolerance it is suitable for different development environments .Due to these
powerful features C has not lost its importance and popularity in recently
developed and advanced software industry C can also be used for system level
programming, C is still considered as first priority programming language.

Even though people says that ―C‖ has been already superseded by languages
like C++, C# and Java but C is still important. According to Yashavant P.
Kanetkar the author of Let Us C disagree this opinion with the following reasons:-
a) C++, C# or Java make use of a principle called Object Oriented
Programming (OOP) to organize the program. This organizing principle
has lots of advantages to offer. But even while using this organizing
principle you would still need a good hold over the language elements of
C and the basic programming skills.
b) Though many C++ and Java based programming tools and frameworks
have evolved over the years the importance of C is still unchallenged
because knowingly or unknowingly while using these frameworks and

Basic Programming – NTA 6 Page 1


tools you would be still required to use the core C language elements—
another good reason why one should learn C before C++, C# or Java.
c) Major parts of popular operating systems like Windows, UNIX, Linux is
still written in C. This is because even today when it comes to
performance (speed of execution) nothing beats C. Moreover, if one is to
extend the operating system to work with new devices one needs to write
device driver programs. These programs are exclusively written in C.
d) Mobile devices like cellular phones and palmtops are becoming
increasingly popular. Also, common consumer devices like microwave
oven, washing machines and digital cameras are getting smarter by the
day. This smartness comes from a microprocessor, an operating system
and a program embedded in this devices. These programs not only have
to run fast but also have to work in limited amount of memory. No
wonder that such programs are written in C. With these constraints on
time and space, C is the language of choice while building such operating
systems and programs
e) At times one is required to very closely interact with the hardware
devices. Since C provides several language elements that make this
interaction feasible without compromising the performance it is the
preferred choice of the programmer.

It is hoped that newcomers will find C a useful and friendly language. Care must
be taken in using C. Many of the extra facilities which it offers can lead to extra
types of programming error. You will have to learn to deal with these to
successfully make the transition to being a C programmer.

Basic Programming – NTA 6 Page 2


Tools of C

As programmer we need different tools to develop a program. These tools are


needed for the life cycle of programs

Editors
First of all we need a tool for writing the code of a program. For this purpose we
used Editors in which we write our code. We can use word processor too for this,
but word processors have many other features like bold the text, italic, coloring
the text etc, so when we save a file written in a word processor, lot of other
information including the text is saved on the disk. For programming purposes
we don‘t need these things we only need simple text. Text editors are such
editors which save only the text which we type. So for programming we will be
using a text editor

Compiler and Interpreter


As we write the code in English and we know that computers can understand
only 0s and 1s. So we need a translator which translates the code of our program
into machine language. There are two kinds of translators which are known as
Interpreter and Compilers. These translators translate our program which is
written in C-Language into Machine language. Interpreters translates the
program line by line meaning it reads one line of program and translates it, then
it reads second line, translate it and so on. The benefit of it is that we get the
errors as we go along and it is very easy to correct the errors. The drawback of
the interpreter is that the program executes slowly as the interpreter translates
the program line by line. Another drawback is that as interpreters are reading the

Basic Programming – NTA 6 Page 3


program line by line so they cannot get the overall picture of the program hence
cannot optimize the program making it efficient.

Compilers also translate the English like language (Code written in C) into a
language (Machine language) which computers can understand. The Compiler
read the whole program and translates it into machine language completely. The
difference between interpreter and compiler is that compiler will stop translating
if it finds an error and there will be no executable code generated whereas
Interpreter will execute all the lines before error and will stop at the line which
contains the error. So Compiler needs syntactically correct program to produce
an executable code. We will be using compiler in our course

Debugger
Another important tool is Debugger. Every programmer should be familiar with
it. Debugger is used to debug the program i.e. to correct the logical errors. Using
debugger we can control our program while it is running. We can stop the
execution of our program at some point and can check the values in different
variables, can change these values etc. In this way we can trace the logical errors
in our program and can see whether our program is producing the correct
results. This tool is very powerful, so it is complex too

Linker
Most of the time our program is using different routines and functions that are
located in different files, hence it needs the executable code of those
routines/functions. Linker is a tool which performs this job, it checks our
program and includes all those routines or functions which we are using in our
program to make a standalone executable code and this process is called Linking

Basic Programming – NTA 6 Page 4


Loader
After a executable program is linked and saved on the disk and it is ready for
execution. We need another process which loads the program into memory and
then instruct the processor to start the execution of the program from the first
instruction (the starting point of every C program is from the main function).
This processor is known as loader.

Linker and loaders are the part of development environment. These are part of
system software. The following figure represents a graphical explanation of all
the steps involved in writing and executing a program.

Basic Programming – NTA 6 Page 5


Editor Disk
Preprocessor program
Preprocessor Disk processes the code.

Compiler creates object


Compiler code and stores
Disk
it on disk.
Linker Disk Linker links the object
code with the libraries
Primary Memory

L oader
Loader puts program
in memory.
Disk ..
..
..

Primary Memory CPU takes each


instruction and
CPU
executes it, possibly
storing new data
values as the
..
..
..
program executes.

Basic Programming – NTA 6 Page 6


Programming Languages

WHAT IS LANGUAGE?
You are aware with the term language. It is a system of communication between
you and me. Some of the basic natural languages that we are familiar with are
English, Swahili, French etc. These are the languages used to communicate
among various categories of persons. But how you will communicate with your
computer. Your computer will not understand any of these natural languages for
transfer of data and instruction. So there are programming languages specially
developed so that you could pass your data and instructions to the computer to
do specific job. You must have heard names like FORTRAN, BASIC, COBOL etc.
These are programming languages. So instructions or programs are written in a
particular language based on the type of job. As an example, for scientific
application FORTRAN and C languages are used. On the other hand COBOL is
used for business applications.
Programming Languages
There are two major types of programming languages. These are Low Level
Languages and High Level Languages. Low Level languages are further divided
in to Machine language and Assembly language.

Low Level Languages


The term low level means closeness to the way in which the machine has been
built. Low level languages are machine oriented and require extensive
knowledge of computer hardware and its configuration.

(a) Machine Language


Machine Language is the only language that is directly understood by the
computer. It does not needs any translator program. We also call it
machine code and it is written as strings of 1's (one) and 0‘s (zero). When

Basic Programming – NTA 6 Page 7


this sequence of codes is fed to the computer, it recognizes the codes and
converts it in to electrical signals needed to run it. For example, a program
instruction may look like this:

1011000111101

It is not an easy language for you to learn because of its difficult to understand. It
is efficient for the computer but very inefficient for programmers. It is considered
to the first generation language. It is also difficult to debug the program written
in this language.

Advantage
The only advantage is that program of machine language run very fast because
no translation program is required for the CPU.

Disadvantages
1. It is very difficult to program in machine language. The programmer has
to know details of hardware to write program.
2. The programmer has to remember a lot of codes to write a program which
results in program errors.
3. It is difficult to debug the program.

(b) Assembly Language


It is the first step to improve the programming structure. You should
know that computer can handle numbers and letter. Therefore some
combination of letters can be used to substitute for number of machine
codes.

Basic Programming – NTA 6 Page 8


The set of symbols and letters forms the Assembly Language and a
translator program is required to translate the Assembly Language to
machine language. This translator program is called `Assembler'. It is
considered to be a second-generation language.

Advantages:
1. The symbolic programming of Assembly Language is easier to understand
and saves a lot of time and effort of the programmer.
2. It is easier to correct errors and modify program instructions.
3. Assembly Language has the same efficiency of execution as the machine level
language. Because this is one-to-one translator between assembly language
program and its corresponding machine language program.

Disadvantages:
One of the major disadvantages is that assembly language is machine dependent.
A program written for one computer might not run in other computers with
different hardware configuration.

HIGH LEVEL LANGUAGES


You know that assembly language and machine level language require deep
knowledge of computer hardware where as in higher language you have to
know only the instructions in English words and logic of the problem
irrespective of the type of computer you are using.

Higher level languages are simple languages that use English and mathematical
symbols like +, -, %, / etc. for its program construction.

You should know that any higher level language has to be converted to machine
language for the computer to understand.

Basic Programming – NTA 6 Page 9


Higher level languages are problem-oriented languages because the instructions
are suitable for solving a particular problem. For example COBOL (Common
Business Oriented Language) is mostly suitable for business oriented language
where there is very little processing and huge output. There are mathematical
oriented languages like FORTRAN (Formula Translation) and BASIC (Beginners
All-purpose Symbolic Instruction Code) where very large processing is required.

Thus a problem oriented language designed in such a way that its instruction
may be written more like the language of the problem. For example,
businessmen use business term and scientists use scientific terms in their
respective languages.

Advantages of High Level Languages


Higher level languages have a major advantage over machine and assembly
languages that higher level languages are easy to learn and use. It is because that
they are similar to the languages used by us in our day to day life.

Compiler
It is a program translator that translates the instruction of a higher level language
to machine language. It is called compiler because it compiles machine language
instructions for every program instructions of higher level language. Thus
compiler is a program translator like assembler but more sophisticated. It scans
the entire program first and then translates it into machine code.

The programs written by the programmer in higher level language is called


source program. After this program is converted to machine languages by the
compiler it is called object program.

Basic Programming – NTA 6 Page 10


Higher Level Language  (Compile)  Program Machine Language
Program

A compiler can translate only those source programs, which have been written,
in that language for which the compiler is meant for. For example FORTRAN
compiler will not compile source code written in COBOL language.

Object program generated by compiler is machine dependent. It means programs


compiled for one type of machine will not run in another type. Therefore every
type of machine must have its personal compiler for a particular language.
Machine independence is achieved by using one higher level language in
different machines.

Interpreter
An interpreter is another type of program translator used for translating higher
level language into machine language. It takes one statement of higher level
languages, translate it into machine language and immediately execute it.
Translation and execution are carried out for each statement. It differs from
compiler, which translate the entire source program into machine code and does
involve in its execution.
.
The advantage of interpreter compared to compiler is its fast response to changes
in source program. It eliminates the need for a separate compilation after
changes to each program. Interpreters are easy to write and do not require large
memory in computer. The disadvantage of interpreter is that it is time

Basic Programming – NTA 6 Page 11


consuming method because each time a statement in a program is executed then
it is first translated. Thus compiled machine language program runs much faster
than an interpreted program.

Programming Language
 a standardized communication technique for expressing instructions to a
computer
 Like human languages, each language has its own syntax and grammar
 There are different types of programming languages that can be used to
create programs, but regardless of what language you use, these
instructions are translated into machine language that can be understood
by computers.

Categories of Programming Languages

High-level Programming Languages

– a programming language that is more user-friendly, to some extent


platform-independent, and abstract from low-level computer

– processor operations such as memory accesses – A programming


statement may be translated into one or several machine
instructions by a compiler.

– Examples: Java, C, C++, Basic, Fortran


● Low-level Assembly Language

– Assembly languages are similar to machine languages, but they are


much easier to program because they allow a programmer to
substitute names for numbers

Basic Programming – NTA 6 Page 12


– Assembly languages are available for each CPU family, and each
assembly instruction is translated into one machine instruction by
an assembler program

Basic Programming – NTA 6 Page 13


Unit 1
Program Development
Life Cycle

1.0 From Problem to Program 2

1.1 Program Development Life Cycle 2

1.1.1 Problem Definition 2

1.1.2 Problem Analysis 2

1-2: Concept of flowcharts and Algorithms 4

1-2-1: The flow Chart 4

1-3: Algorithms: 8

Basic Programming – NTA 6 Page 1


1.0 From Problem to Program

Programming is not about mathematics, it is about organization.

The art of taking a problem and breaking it down into a set of instructions
you can give a computer is the interesting part of programming.
Unfortunately it is also the most difficult part of programming as well. If
you think that learning to program is simply a matter of learning a
programming language you are very wrong. In fact if you think that
programming is simply a matter of coming up with a program which
solves a problem you are equally wrong!

There are many things you must consider when writing a program; not all
of them are directly related to the problem in hand. I am going to start on
the basis that you are writing your programs for a customer. He or she has
problem and would like you to write a program to solve it. We shall
assume that the customer knows even less about computers than we do!

Initially we are not even going to talk about the programming language,
type of computer or anything like that, we are simply going to make sure
that we know what the customer wants. Coming up with a perfect
solution to a problem the customer has not got is something which
happens surprisingly often in the real world.

1.1 Program Development Life Cycle

Basic steps in trying to solve a problem on the computer:


1. Problem Definition
2. Problem Analysis
3. Algorithm design and representation (Pseudocode or flowchart)
4. Coding and debugging

1.1.1 Problem Definition

1. A clearly defined problem is already half the solution.


2. Computer programming requires us to define the problem first before
we even try to create a solution.
3. Let us now define our example problem:
4. ―Create a program that will determine the number of times a name
occurs in a list.‖
1.1.2 Problem Analysis

Basic Programming – NTA 6 Page 2


 After the problem has been adequately defined, the simplest and
yet the most efficient and effective approach to solve the problem
must be formulated.
 Usually, this step involves breaking up the problem into smaller
and simpler sub problems.
 Example Problem:
o Determine the number of times a name occurs in a list
 Input to the program:
o – list of names (let's call this nameList)
o – name to look for (let's call this keyName)
 Output of the program:
o – the number of times the name occurs in a list

Basic Programming – NTA 6 Page 3


1-2: Concept of flowcharts and Algorithms

A computer cannot understand the problem nor it solves it – it can only


perform a set of predefined operations. It is the programmer‘s job to
convert the given problem into a set of instructions so that those actions,
when performed would solve the problem.

A computer can be likened to the servant, who is highly competent and


faithful as long as following the instructions are concerned, but cannot
reason out by himself. So, you as a programmer will have to break the
problem into sequence steps for the computer to work with. You should
be able to break the problem into the simple steps so that you can describe
these steps in the language.

Further, such an analysis will also help you remember what you have
done and modify, if necessary, at a much later date. Also, if some other
person wants to know your sequence of reasoning, obviously it should be
possible for you to describe your logic in simple, unambiguous steps.
Because of all these reasons, it is highly essential to develop some form of
intermediary mechanism to describe the problem on hand as a sequence
of steps, which can be later converted to a program. There are two such
commonly used and universally accepted methods of describing the
solution process.-
a) The Flow Charts, and
b) The Algorithms

1-2-1: The flow Chart


As the name suggest, it is a chart to describe the flow of the solution
process. You break up the solution into simple steps and connect them to
describe the of information.

1. Terminal: This symbol is used in the


beginning and at the end of the flow
chart. Here the beginning and the end
refer to the logical beginning and the
logical end of the sequence of
operations. Start, Stop, End, or Exit is
Writer inside the symbol to indicate
the type of terminal. For example the
beginning of the flow chart is
represented as given here.

Basic Programming – NTA 6 Page 4


2. Input/Output : The symbol
parallelogram is used for reading or
witting of data. This symbol is used
for all types of input and output, such
as floppy reading, printing, magnetic
tape reading or writing, or disk
reading or writing, etc. The brief
description of the operation is written
inside the symbol. For example,
reading a record can be represented as
given here.
3. Processing : The symbol rectangle is
used for processing operations, i.e. for
arithmetic computations (addition,
subtraction, multiplication, division)
or moving the data from one location
or core storage to another location. For
example, the computations of PME
(percentage of marks in English) can
be represented as given here. 3.
Processing : The symbol rectangle is

Basic Programming – NTA 6 Page 5


4. Decision : The diamond shaped
symbol is used for representing a
decision. . It indicates that a condition
is to be tested and one of the
alternative paths is to be followed.
For example, PME can be compared 40 (for
deciding more or less or equal to 40) and can
be represented as follows:

Sometimes, the number of alternative paths


after the decision point are 3 or even more
then the symbol used is as given

Basic Programming – NTA 6 Page 6


5. Flowline: The straight lines with
arrowheads show the path of flow.
Arrows on the line indicate the
direction of flow. The flowline
connects the various symbols.
6. Connector : A small circle is called
the connector, and is used to show the
entry to or exit from the logical path of
a flow char. In fact, this symbol
replaces the long flowlines connecting
the different parts of a flowchart on
the same page. One symbol shows
where the branching of flow is one
whereas the other symbol shows the
entry of the flow. Inside the symbol
the name of the entry or exist point is
written.
7. Preparation: This symbol is used for
the housekeeping operations. All
those operations, which are done
before starting the actual processing of
data, come in this category. For
example, setting the number of
students to zero before processing of
data starts.
8. Predefined: This symbol indicates that
a routine or process, which is shown
in the flowchart separately, is executed at
this position. Normally when a specific
process is used at different logical paths
then the use of this symbol provides the
simplicity in the flowchart.
9. Off page Connector : This symbol is used
in placed of connector when the exit and
the corresponding entry point are shown
on different pages in the flowchart.

10. Annotation, Comments: This symbol


provides the facility of writing more
description of an operation. When the
space inside a symbol is not sufficient to
write the details, then this symbol is used.
The dotted line between the symbol and
flow chart shows the point to which it

Basic Programming – NTA 6 Page 7


relates.

1-3: Algorithms:
The other concept is the algorithm. It is a step by step description of the
problem in a language similar to English, but not in full sentences, but as a
set of commands. Some of the examples below will classify the concepts.

Examples 1-1:
Simple interest is calculated using the formula SI=(P * T * R)/100

Flowchart Algorithm

Step 1: START

Step 2: Read P T and R

Step 3 : Calculate I = P * R * T/100

Step 4 : Write 1

Step 5 : End

Basic Programming – NTA 6 Page 8


Example 1-2
Victor Construction Company plans to give a 5% year-end Bonus to each
of its employees earning Tshs. 5,000 or more per year, and a fixed Tshs.
250 bonus to the other employees. The flowchart and algorithm for
calculation the Bonus for an employee is as shown in figure.

Flowchart Algorithm

Step 1 : START

Step 2 : Read SALARY of an employee

Step 3 : If Salary is Greater than or Equal to


5,000 then

Step 4 : Calculate Bonus = 0.5 * Salary Else


Step 5 : Calculate Bonus = 250

Step 6 : Write Bonus of Employee

Step 7 : End

Example 1-3
The flowchart and algorithm for adding the integers from 1 to 10.

Algorithm
Flowchart

Basic Programming – NTA 6 Page 9


Step 1 : Start

Step 2 : Initials SUM=0 and


N=1

Step 3 : If N is greater than


10
then

Step 4 : Print SUM Step 5 :


Stop

Step 6 : Calculate
SUM=SUM+N
N=N+1 End if

Step 7 : Go to Step 3

Example 1-4
A Flowchart to calculate the largest and the smallest numbers in a list of
input values is as shown in figure. The last input value is 99999.

Basic Programming – NTA 6 Page 10


Read the first number
Take that number as the largest number
Take that number as the smallest number also
Input the next number
If this num = 99999, you want to end the session,
So print the largest and smallest number and STOP.
Else
if the number is > the preset large number, make the new number the
largest.
Else
If the number < the present small number, make the new number as the
smallest
Go to step 4.

Basic Programming – NTA 6 Page 11


Example 1-5:
A flow chart to read the marks of a student and classify him into different
grades. If marks greater than or equal to 90 Grade A, greater than or equal
to 80 but less than 90 Grade B, Greater than or equal to 65 but less than 80
Grade C otherwise Grade D.

Algorithm:
Read marks
If marks >= 90
Declare Grade = A
Else If marks >=80 declare grade = B
Else if marks >=65 declare Grade = C
Else declare Grade = D
Write Grade
End

Example 1-6: A flowchart to find the roots of a quadratic equation

Algorithm
Read the parameters of A,B,C
Evaluate D = b2 – 4 * a * c
If D>0,
Evaluate the first root as –b + sqrt (D) / (2 * a)
Second Root as –b – sqrt (D) / (2 * a)
Else
If D = 0
Evaluate First root as –b / 2 * a
Basic Programming – NTA 6 Page 12
Else
If D<0, Simply write complex roots.
End

Unit 2
Debugging and Program
Testing
2-1: Debugging and Program Testing 1
2-2: Types of Errors 1
2-3: Formal Program Testing: 2

Basic Programming – NTA 6 Page 13


2-1: Debugging and Program Testing
 After constructing the algorithm, it is now possible to create the
source code. Using the algorithm as basis, the source code can now
be written using the chosen programming language.
 Debugging
o The process of fixing some errors (bugs) in your program

Debugging is a fundamental skill of any programmer. Debugging can


be quite stressful if you are under pressure (time constrains) but it can
also be quite fun, kind of like a logic mystery. Experience in debugging
will not only reduce future errors but generate better hypothesis for
what might be going wrong. Other alternatives are running automated
tools to test or verify the code or analise the code as it runs, this is the
task were a debugger can come to your aid.
2-2: Types of Errors
The compiler can only translate a program if the program is
syntactically correct; otherwise, the compilation fails and you will not
be able to run your program. Syntax refers to the structure of your
program and the rules about that structure.

Compilers are not so forgiving. If there is a single syntax error


anywhere in your program, the compiler will print an error message
and quit, and you will not be able to run your program

a. Compile-time error or syntax errors


 This is when your program doesn't use the proper syntax and does
not compile. The compiler will detect the error and the program
won't even compile. At this point, the programmer is unable to
form an executable program that a user can run until the error is
fixed.

The following code fragment is NOT syntactically correct. What is


wrong?

printf ("Enter the distance traveled in miles > );

What will happen during compilation if your program has syntax


errors?
The program will not compile successfully until all syntax errors
have been Corrected.

The following code fragment has been corrected and is now


syntactically correct.

2-1
printf ("Enter the distance traveled in miles > ");

b. Runtime Errors
 Your program compiles, but when it runs, in certain cases it
terminates abruptly. An example of this would be a program that
attempted to divide by zero while running. Compilers aren't
perfect and so can't catch all errors at compile time. This is
especially true for logic errors such as infinite loops. This type of
error is called runtime error.
Example:
If the user enters a value of 0 for the miles_per_gallon, the
resulting calculation

gasoline_used = miles / miles_per_gallon;

will divide the number of miles traveled by 0.

Dividing a number by zero is mathematically meaningless


(undefined) and is an illegal operation on the computer. It will
cause your program to terminate (we sometimes say "crash", or
abort) with a run-time ―divide by 0 error.‖

c. Semantic/Logical Error:
 Your program compiles and executes without abnormal
termination, but does not always produce the desired results.
The following code fragment is NOT semantically correct, the
formula for calculating kilometers is wrong. Why?

kilometers = miles / 1.609;


You should be multiplying miles by 1.609, not dividing.

The following code fragment has been corrected and is now


semantically correct

kilometers = miles * 1.609;


The only way you can locate errors such as these is to use carefully
constructed tests to verify that the program is semantically correct.
BUT … you have to know what answers are expected for each test
case, or you have no way of evaluating each test.

2-3: Formal Program Testing:


The software industry is primarily concern with logical errors and hidden
run-time errors. Companies expend enormous effort to find the errors
before the release. To fix a bug after the release cost a 100 times more;

2-2
patches must be designed and ship out. Besides the customer are not very
happy. Software companies generally have a special team for code test,
besides allocating time for program testing. Beta releases are distributed
for evaluation by the end user.

The industry is concerned with Verification and Validation:

 Validation or appropriate:

Is the program a banana when it should be an apple?


Techniques for insuring validation:

 Inspection code at a high level


 Have the user/costumer test software
 Requires good software specification

 Verification or correctness

Is the program producing the correct answers?


Techniques for insuring verification:

 Code walk through or inspection


 Testing

Testing and inspection are the primary technique for V and V:

 Testing uses input data and observes output.


o There maybe additional output then in the final product.
o The code is running not static.
o The evaluation may include more then just the correctness of
the output.
o Testing can be at the component level or integrated level.
 Inspection analyzes the code statically
o The code is not running.
o Typically a walk though.
o Software does exist for code inspection; for example LINT for C

Testing:
You can do component testing in your programs. There are basically two
types of testing technique black box and white box.

 Black box or functional testing

Black box testing implies that you will test for all possible input
types. To test for all possible data inputs would take too long so

2-3
we identify input types, this process is called partitioning the
inputs.

As example suppose that the program is a calculator then you


may partition data as:

 Operations: multiply, divide, add and subtract


 Numbers
 integer
 real
 positive and negative

Be sides testing example cases inside the partition, be sure to


test at the boundary of the partitions: for example zeros or
mixed integers and real.

 White box or structural testing

White box testing implies we have access to code and test all
possible paths that a program may take. Therefore we must
analyze the program, this is a good time to double check
conditionals.

Paths are the different routes the computer can take through the
program.

If example:

if (w >x){
a = a + 1;
}
else {
a = a + 3;
}
if ( y < z) {
a = a + 3;
}
else{
a = a + 4;
}
How many paths are there in this example? What are they?

2-4
Unit 3
C-FUNDAMENTALS
3-1: C-FUNDAMENTALS 2
3-2 Character of C 2
3-3: Types of C Constants 2
3-4: Rules for Constructing Integer Constants 3
3-5: Rules for Constructing Real Constants 3
3-6: Rules for Constructing Character Constants 4
3-7: Types of C Variables 4
3-8: Rules for Constructing Variable Names 5
3-9: C Keywords 5
3-10: C Instructions 6
3-11: Type Declaration Instruction 6
3-12: Arithmetic Instruction 7
3-13: Integer and Float Conversions 10
3-14 Type Conversion in Assignments 10
3-14: Associativity of Operators 13
3-15 Control Instructions in C 16

Basic Programming – NTA 6 Page 1


3-1: C-FUNDAMENTALS

We now start with the fundamentals of the language. Any language, as


you know made of sentences, which are made up of words, which in turn
are made up of characters i.e. we start learning the characters, then learn
how to combine them into words, combine the words into sentences and
so on

3-2 Character of C
C makes use of the normal characters of English – a to z, 0 – 9 and several
special characters like + - * / , . % # $ & ― = ; ( ) { } \ and so on. Most of the
compilers are also case sensitive. i.e. they do differentiate between capital
and small letters so you should not go about mixing them. It is a good
practice and also pleasing to type all program with small letters.

Alphabets A, B, ….., Y, Z
a, b, ……, y, z
Digits 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Special symbols ~‗!@#%^&*()_-+
=|\{}
[]:;"'<>,.?/

3-3: Types of C Constants

C constants can be divided into two major categories:

a) Primary Constants

b) Secondary Constants

Basic Programming – NTA 6 Page 2


At this stage we would restrict our discussion to only Primary Constants,
namely, Integer, Real and Character constants. Let us see the details of each
of these constants. For constructing these different types of constants certain
rules have been laid down. These rules are as under:

3-4: Rules for Constructing Integer Constants


a) An integer constant must have at least one digit.
b) It must not have a decimal point.
c) It can be either positive or negative.
d) If no sign precedes an integer constant it is assumed to be positive.
e) No commas or blanks are allowed within an integer constant.
f) The allowable range for integer constants is -32768 to 32767.

3-5: Rules for Constructing Real Constants


Real constants are often called Floating Point constants. The real constants
could be written in two forms—Fractional form and Exponential form.

Following rules must be observed while constructing real constants


expressed in fractional form:

a) A real constant must have at least one digit.


b) It must have a decimal point.
c) It could be either positive or negative.
d) Default sign is positive.
e) No commas or blanks are allowed within a real constant.

Following rules must be observed while constructing real constants


expressed in exponential form:

a) The mantissa part and the exponential part should be separated by a


letter e.
b) The mantissa part may have a positive or negative sign.
c) Default sign of mantissa part is positive.

Basic Programming – NTA 6 Page 3


d) The exponent must have at least one digit, which must be a positive or
negative integer. Default sign is positive.
e) Range of real constants expressed in exponential form is -3.4e38 to
3.4e38.

3-6: Rules for Constructing Character Constants


a) A character constant is a single alphabet, a single digit or a single special
symbol enclosed within single inverted commas. Both the inverted
commas should point to the left. For example, ‘A‘ is a valid character
constant whereas ‗A‘ is not.
b) The maximum length of a character constant can be 1 character.

3-7: Types of C Variables


In C, a variable must be declared before it can be used. Variables can be
declared at the start of any block of code, but most are found at the start of
each function. Most local variables are created when the function is called,
and are destroyed on return from that function.

A declaration begins with the type, followed by the name of one or more
variables. For example,
int high, low, results[20];

Declarations can be spread out, allowing space for an explanatory


comment. Variables can also be initialised when they are declared, this is
done by adding an equals sign and the required value after the
declaration.
int high = 250; /* Maximum Temperature */
int low = -40; /* Minimum Temperature */
int results[20]; /* Series of temperature readings */

Just as a language is made up of names, verbs, adjective, adverbs etc., C


programs are made up of variables, constants, arithmetic operators etc. A
variable in a program is a name to which you can associate a value or an
entity that may vary during program execution. Variable names are
names given to locations in memory. These locations can contain integer,
real or character constants. In any language, the types of variables that it
can support depend on the types of constants that it can handle. This is
because a particular type of variable can hold only the same type of
constant. For example, an integer variable can hold only an integer
constant, a real variable can hold only a real constant and a character
variable can hold only a character constant.

Basic Programming – NTA 6 Page 4


The rules for constructing different types of constants are different.
However, for constructing variable names of all types the same set of rules
apply. These rules are given below.
3-8: Rules for Constructing Variable Names
a) A variable name is any combination of 1 to 31 alphabets, digits or
underscores. Some compilers allow variable names whose length could
be up to 247 characters. Still, it would be safer to stick to the rule of 31
characters. Do not create unnecessarily long variable names as it adds
to your typing effort.
b) The first character in the variable name must be an alphabet or
underscore.
c) No commas or blanks are allowed within a variable name.
d) No special symbol other than an underscore (as in gross_sal) can be
used in a variable name.
Ex.: si_int
m_hra
pop_e_89

C compiler is able to distinguish between the variable names by making it


compulsory for you to declare the type of any variable name that you
wish to use in a program. This type declaration is done at the beginning of
the program.

Variable themselves come in different types. They can be integers (whole


numbers). Floats(fractional numbers) doubles and characters. Characters
as the name suggests are used to store characters. A number of characters
in a spring are sometimes called the string (Str) variables. The data type
doubles need some introduction. Normally a C compiler can store
numbers of certain size only. The actual size depends on the computer
you are using and the compiler in use. If you suspect that you are likely to
use numbers bigger than this, you should use double declaration, which
will give you twice the number places. i.e. if your original limit was 5
places, you may now get to use to 10 places which will suffice in most
cases.
3-9: C Keywords
Keywords are the words whose meaning has already been explained to
the C compiler (or in a broad sense to the computer). The keywords
cannot be used as variable names because if we do so we are trying to
assign a new meaning to the keyword, which is not allowed by the
computer. Some C compilers allow you to construct variable names that
exactly resemble the keywords. However, it would be safer not to mix up
the variable names and the keywords. The keywords are also called
‗Reserved words‘.

Basic Programming – NTA 6 Page 5


3-10: C Instructions

There are basically three types of instructions in C:

a) Type Declaration Instruction

b) Arithmetic Instruction

c) Control Instruction

The purpose of each of these instructions is given below:


Type declaration To declare the type of variables used in
instruction − a C program.
Arithmetic instruction − To perform arithmetic operations
between constants and variables.

Control instruction − To control the sequence of execution of


various statements in a C program.

3-11: Type Declaration Instruction

This instruction is used to declare the type of variables being used in the
program. Any variable used in the program must be declared before using it
in any statement. The type declaration statement is written at the beginning
of main( ) function
Example:
int bas ;
float rs, grosssal ;
char name, code ;

Basic Programming – NTA 6 Page 6


There are several slight variations of the type declaration instruction. These
are discussed below:

a) While declaring the type of variable we can also initialize it as shown


below.
int i = 10, j = 25 ;
float a = 1.5, b = 1.99 + 2.4 * 1.44 ;

b) The order in which we define the variables is sometimes important


sometimes not.
For example,
int i = 10, j = 25 ;
is same as
int j = 25, j = 10 ;
However,
float a = 1.5, b = a + 3.1 ;
is alright, but
float b = a + 3.1, a = 1.5 ;

is not. This is because here we are trying to use a even before defining
it.

c) The following statements would work int a, b, c, d ;


a = b = c = 10 ;
However, the following statement would not work
int a = b = c = d = 10 ;

Once again we are trying to use b (to assign to a) before defining it.

3-12: Arithmetic Instruction

A C arithmetic instruction consists of a variable name on the left hand side of


= and variable names & constants on the right hand side of =. The variables
and constants appearing on the right hand side of = are connected by
arithmetic operators like +, -, *, and /.

Ex.: int ad ;
float kot, deta, alpha, beta, gamma ;
ad = 3200 ;
kot = 0.0056 ;
deta = alpha * beta / gamma + 3.2 * 2 / 5 ;

Here,
*, /, -, + are the arithmetic operators.
= is the assignment operator.
2, 5 and 3200 are integer constants.
Basic Programming – NTA 6 Page 7
3.2 and 0.0056 are real constants.
ad is an integer variable.
kot, deta, alpha, beta, gamma are real variables.

The variables and constants together are called ‘operands’ that are operated
upon by the ‘arithmetic operators’ and the result is assigned, using the
assignment operator, to the variable on left-hand side.

A C arithmetic statement could be of three types. These are as follows:

a) Integer mode arithmetic statement - This is an arithmetic statement


in which all operands are either integer variables or integer constants.
Ex.: int i, king, issac, noteit ;
i=i+1;
king = issac * 234 + noteit - 7689 ;

b) Real mode arithmetic statement - This is an arithmetic statement in


which all operands are either real constants or real variables.

Ex.: float qbee, antink, si, prin, anoy, roi ;


qbee = antink + 23.123 / 4.5 * 0.3442 ;
si = prin * anoy * roi / 100.0 ;

c) Mixed mode arithmetic statement - This is an arithmetic statement in


which some of the operands are integers and some of the operands are
real.

Ex.: float si, prin, anoy, roi, avg ;


int a, b, c, num ;
si = prin * anoy * roi / 100.0 ;
avg = ( a + b + c + num ) / 4 ;

It is very important to understand how the execution of an arithmetic statement


takes place. Firstly, the right hand side is evaluated using constants and the
numerical values stored in the variable names. This value is then assigned to the
variable on the left-hand side.

Though Arithmetic instructions look simple to use one often commits mistakes in
writing them. Let us take a closer look at these statements. Note the following
points carefully.

a) C allows only one variable on left-hand side of =. That is, z = k * l is legal,


whereas k * l = z is illegal.

b) In addition to the division operator C also provides a modular division


operator. This operator returns the remainder on dividing one integer
Basic Programming – NTA 6 Page 8
with another. Thus the expression 10 / 2 yields 5, whereas, 10 % 2 yields
0. Note that the modulus operator (%) cannot be applied on a float. Also
note that on using % the sign of the remainder is always same as the sign
of the numerator. Thus –5 % 2 yields –1, whereas, 5 % -2 yields 1.

c) An arithmetic instruction is often used for storing character constants in


character variables.
char a, b, d ;
a = 'F' ;
b = 'G' ;
d = '+' ;
When we do this the ASCII values of the characters are stored in the
variables. ASCII values are used to represent any character in memory.
The ASCII values of ‗F‘ and ‗G‘ are 70

d) Arithmetic operations can be performed on ints, floats and chars.


Thus the statements,
char x, y ;
int z ;
x = 'a' ;
y = 'b' ;
z=x+y;

e) No operator is assumed to be present. It must be written explicitly. In the


following example, the multiplication operator after b must be explicitly
written. a = c.d.b(xy) usual arithmetic statement
b = c * d * b * ( x * y ) C statement

f) Unlike other high level languages, there is no operator for performing


exponentiation operation. Thus following statements are invalid.
a = 3 ** 2 ;
b=3^2;
If we want to do the exponentiation we can get it done this way:
#include <math.h>
main( )
{
int a ;
a = pow ( 3, 2 ) ;
printf ( “%d”, a ) ;
}
Here pow( ) function is a standard library function. It is being used to
raise 3 to the power of 2. #include <math.h> is a preprocessor directive. It
is being used here to ensure that the pow( ) function works correctly.

Basic Programming – NTA 6 Page 9


3-13: Integer and Float Conversions
In order to effectively develop C programs, it will be necessary to understand the
rules that are used for the implicit conversion of floating point and integer values
in C. These are mentioned below. Note them carefully.

a) An arithmetic operation between an integer and integer always yields an


integer result.

b) An operation between a real and real always yields a real result.


c) An operation between an integer and real always yields a real result. In
this operation the integer is first promoted to a real and then the operation
is performed. Hence the result is real.
Example
Operation Result Operation Result
5/2 2 2/5 0
5.0 / 2 2.5 2.0 / 5 0.4
5 / 2.0 2.5 2 / 5.0 0.4
5.0 / 2.0 2.5 2.0 / 5.0 0.4

3-14 Type Conversion in Assignments


It may so happen that the type of the expression and the type of the variable
on the left-hand side of the assignment operator may not be same. In such a
case the value of the expression is promoted or demoted depending on the
type of the variable on left-hand side of =.
For example, consider the following assignment statements.
int i ;
float b ;
i = 3.5 ;
b = 30 ;

Here in the first assignment statement though the expression‘s value is a float
(3.5) it cannot be stored in i since it is an int. In such a case the float is
demoted to an int and then its value is stored. Hence what gets stored in i is
3. Exactly opposite happens in the next statement. Here, 30 is promoted to
30.000000 and then stored in b, since b being a float variable cannot hold
anything except a float value.

Basic Programming – NTA 6 Page 10


Arithmetic Result Arithmetic Result
Instruction Instruction
k=2/9 0 a=2/9 0.0
k = 2.0 / 9 0 a = 2.0 / 9 0.2222
k = 2 / 9.0 0 a = 2 / 9.0 0.2222
k = 2.0 / 9.0 0 a = 2.0 / 9.0 0.2222
k=9/2 4 a=9/2 4.0
k = 9.0 / 2 4 a = 9.0 / 2 4.5
k = 9 / 2.0 4 a = 9 / 2.0 4.5
k = 9.0 / 2.0 4 a = 9.0 / 2.0 4.5

In the first statement, since both 2 and 9 are integers, the result is an
integer, i.e. 0. This 0 is then assigned to k. In the second statement 9 is
promoted to 9.0 and then the division is performed. Division yields
0.222222. However, this cannot be stored in k, k being an int. Hence it gets
demoted to 0 and then stored in k.

Hierarchy of Operations
Operators are the special symbol use to perform special operation (for
example, arithmetic & logical) on operands. Operands are the variables,
constants or expressions on which operators perform operation.

While executing an arithmetic statement, which has two or more


operators, we may have some problems as to how exactly does it get
executed. For example, does the expression 2 * x - 3 * y correspond to (2x)-
(3y) or to 2(x-3y)? Similarly, does A / B * C correspond to A / (B * C) or to
(A / B) * C? To answer these questions satisfactorily one has to
understand the ‗hierarchy‘ of operations. The priority or precedence in
which the operations in an arithmetic statement are performed is called the
hierarchy of operations.
Priority Operators Description
1
st */% multiplication, division,
modular division
2
nd + - addition, subtraction
3
rd = assignment

As per the number of operands required by the operator, it is classified in


three categories:
1. Unary operators
2. Binary operators
3. Ternary operators

Basic Programming – NTA 6 Page 11


Operator Type Meaning Example
+ Addition 9 + 45
– Subtraction 89 – 12
* Binary Multiplication 10 * 3
/ Division 18 / 6
% Modulo Division 14 % 3
+ Unary Plus +51
Unary
– Unary Minus –92
= Binary Assignment a = 45 + 10/2
Increment Post increment: a++ Pre
++
increment: ++a
Unary
Decrement Post decrement: a–– Pre
––
decrement: ––a
a += 10 implies that a = a + 10
+= Add and assign
a –= 10 implies that a = a – 10
–= Subtract and assign
a *= 10 implies that a = a * 10
*= Binary Multiply and assign
a /= 10 implies that a = a / 10
/= Divide and assign
a %= 10 implies that a = a %
%= Mod and assign
10

A few examples would clarify the issue further.

Example 1: Determine the hierarchy of operations and evaluate the following


expression:
i=2*3/4+4/4+8-2+5/8
Stepwise evaluation of this expression is shown below:
i=2*3/4+4/4+8-2+5/8
i=6/4+4/4+8-2+5/8 operation: *
i=1+4/4+8-2+5/8 operation: /
i = 1 + 1+ 8 - 2 + 5 / 8 operation: /
i=1+1+8-2+0 operation: /
i=2+8-2+0 operation: +
i = 10 - 2 + 0 operation: +
i=8+0 operation : -
i=8 operation: +

So far we have seen how the computer evaluates an arithmetic statement


written in C. But our knowledge would be incomplete unless we know how
to convert a general arithmetic statement to a C statement.

Basic Programming – NTA 6 Page 12


C can handle any complex expression with ease. Some of the examples of C
expressions are shown below:-

Algebric Expression C Expression


axb–cxd a*b–c*d
(m + n) (a + b) (m + n) * (a + b)
3x2 + 2x + 5 3*x*x+2*x+5
(a+b+c)/(d+e)

2 * b * y / ( d + 1 ) – x /3 * (
z+y)

3-14: Associativity of Operators


When an expression contains two operators of equal priority the tie between
them is settled using the associativity of the operators. Associativity can be of
two types—Left to Right or Right to Left. Left to Right associativity means
that the left operand must be unambiguous. Unambiguous in what sense? It
must not be involved in evaluation of any other sub-expression. Similarly, in
case of Right to Left associativity the right operand must be unambiguous.
Let us understand this with an example.
Consider the expression
a=3/2*5;
Here there is a tie between operators of same priority, that is between / and *.
This tie is settled using the associativity of / and *. But both enjoy Left to
Right associativity.

Operator Left Right Remark


/ 3 2 or 2 * 5 Left operand is unambiguous,
Right is not
* 3 / 2 or 2 5 Right operand is unambiguous,
Left is not
Since both / and * have L to R associativity and only / has unambiguous left
operand (necessary condition for L to R associativity) it is performed earlier.
Consider one more expression
a=b=3;

Here both assignment operators have the same priority and same
associativity (Right to Left)

Operator Left Right Remark

Basic Programming – NTA 6 Page 13


= a b or b = 3 Left operand is unambiguous,
Right is not

= b or a = b 3 Right operand is unambiguous,


Left is not
Since both = have R to L associativity and only the second = has
unambiguous right operand (necessary condition for R to L associativity) the
second = is performed earlier.
Consider yet another expression
z=a*b+c/d;

Here * and / enjoys same priority and same associativity (Left to Right)

Operator Left Right Remark


* a b Both operands are unambiguous
/ c d Both operands are unambiguous

Here since left operands for both operators are unambiguous Compiler is free
to perform * or / operation as per its convenience since no matter which is
performed earlier the result would be same.

Precedence Table

Description Operator Associativity


Function expression () Left to Right
Array Expression [] Left to Right
Structure operator -> Left to Right
Structure operator . Left to Right
Unary minus - Right to left
Increment/Decrement ++ -- Right to Left
One‘s compliment ~ Right to left
Negation ! Right to Left
Address of & Right to left
Value of address * Right to left
Type cast ( type ) Right to left
Size in bytes sizeof Right to left
Multiplication * Left to right
Division / Left to right
Modulus % Left to right
Addition + Left to right
Subtraction - Left to right
Left shift << Left to right
Right shift >> Left to right
Less than < Left to right
Basic Programming – NTA 6 Page 14
Less than or equal to <= Left to right
Greater than > Left to right
Greater than or equal to >= Left to right
Equal to == Left to right
Not equal to != Left to right
Bitwise AND & Left to right
Bitwise exclusive OR ^ Left to right
Bitwise inclusive OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = Right to left
*= /= %= Right to left
+= -= &= Right to left
^= |= Right to left
<<= >>= Right to left
Comma , Right to left

More Assignment Operators: +=, -=, *=, /=, %=

C has several assignment operators. The most basic one, of course, is =, which
simply assigns the value of the expression at its right to the variable at its left.
The other assignment operators update variables. Each is used with a variable
name to its left and an expression to its right. The variable is assigned a new
value equal to its old value adjusted by the value of the expression at the right.
The exact adjustment depends on the operator. For example,

scores += 20 is the same as scores = scores + 20.

dimes -= 2 is the same as dimes = dimes - 2.

bunnies *= 2 is the same as bunnies = bunnies * 2.

time /= 2.73 is the same as time = time / 2.73.

reduce %= 3 is the same as reduce = reduce % 3.

The preceding list uses simple numbers on the right, but these operators also
work with more elaborate expressions, such as the following:

Basic Programming – NTA 6 Page 15


x *= 3 * y + 12 is the same as x = x * (3 * y + 12).

The assignment operators we've just discussed have the same low priority that =
does—that is, less than that of + or *. This low priority is reflected in the last
example in which 12 is added to 3 * y before the result is multiplied by x.

You are not required to use these forms. They are, however, more compact, and
they may produce more efficient machine code than the longer form. The
combination assignment operators are particularly useful when you are trying to
squeeze something complex into a for loop specification.

3-15 Control Instructions in C


As the name suggests the ‗Control Instructions‘ enable us to specify the order in
which the various instructions in a program are to be executed by the computer.
In other words the control instructions determine the ‗flow of control‘ in a
program. There are four types of control instructions in C. They are:

(a) Sequence Control Instruction


(b) Selection or Decision Control Instruction
(c) Repetition or Loop Control Instruction
(d) Case Control Instruction

The Sequence control instruction ensures that the instructions are executed in
the same order in which they appear in the program. Decision and Case control
instructions allow the computer to take a decision as to which instruction is to
be executed next. The Loop control instruction helps computer to execute a
group of statements repeatedly.

Some Terminology

a) As long as you are learning the names of things, the proper term for
what we have called an "item" (as in "the item to the left of the =") is
operand. Operands are what operators operate on.
b) The addition operator causes the two values on either side of it to be
added together
c) The subtraction operator causes the number after the – sign to be
subtracted from the number before the sign.

The + and – operators are termed binary, or dyadic, operators,


meaning that they require two operands.

d) Sign Operators: – and +

Basic Programming – NTA 6 Page 16


The minus sign can also be used to indicate or to change the algebraic
sign of a value.

When the minus sign is used in this way, it is called a unary operator,
meaning that it takes just one operand

Unary and binary operators.

e) C uses the / symbol to represent division. The value to the left of the /
is divided by the value to the right.
f) The modulus operator is used in integer arithmetic. It gives the
remainder that results when the integer to its left is divided by the
integer to its right.

g) The increment operator performs a simple task; it increments


(increases) the value of its operand by 1. This operator comes in two
varieties. The first variety has the ++ come before the affected variable;
this is the prefix mode. The second variety has the ++ after the affected
variable; this is the postfix mode. The two modes differ with regard to
the precise time that the incrementing takes place.

Basic Programming – NTA 6 Page 17


h) C offers a shorthand way to express one form of the if else statement. It
is called a conditional expression and uses the ?: conditional operator.
This is a two-part operator that has three operands. Recall that
operators with one operand are called unary operators and that
operators with two operands are called binary operators. In that
tradition, operators with three operands are called ternary operators,
and the conditional operator is C's only example in that category.

Basic Programming – NTA 6 Page 18


Unit 4
The First C Program
4-1: The First C Program 2
4-2: Structure of a C Program:- 2
4-3: Type casting or Type conversion 10
4-4 Some C Program Examples 10

Basic Programming – NTA 6 Page 1


4-1: The First C Program

Before we begin with our first C program do remember the following rules that are
applicable to all C programs:

a) Each instruction in a C program is written as a separate statement. Therefore a


complete C program would comprise of a series of statements.
b) The statements in a program must appear in the same order in which we wish
them to be executed; unless of course the logic of the problem demands a
deliberate ‗jump‘ or transfer of control to a statement, which is out of sequence.
c) Blank spaces may be inserted between two words to improve the readability of
the statement. However, no blank spaces are allowed within a variable, constant
or keyword.
d) All statements are entered in small case letters.
e) C has no specific rules for the position at which a statement is to be written.
That‘s why it is often called a free-form language.
f) Every C statement must end with a ;. Thus ; acts as a statement terminator.

4-2: Structure of a C Program:-


The structure of a C program can by explained by taking an example of a C
program to calculate area and perimeter of a rectangle. The program is written as
follows.
/* Example program */
/* This program finds the area and perimeter of a rectangle */
# include <stdio.h>
main( )
{
int p,q, area, perimeter;
p=4
q=6
area = p*q;
perimeter = 2 * (p+q);
printf(“area = %d\n”, area);
printf(“perimeter = % d\n”, perimeter);
}
/* End of main */

a) Comments
In the above program the first line in the program starts with /* and ends
with */. Any thing written between /* and */ is called a comment. In the C
Language comments are an aid to the programmer to read and understand a
program. It is not a statement of the language. The compiler ignores

Basic Programming – NTA 6 Page 2


comments It is a good practice to include comments in a program which will
help in understanding a program.

 Comment about the program should be enclosed within /* */. For example,
the first two statements in our program are comments.

 Though comments are not necessary, it is a good practice to begin a program


with a comment indicating the purpose of the program, its author and the
date on which the program was written.

 Any number of comments can be written at any place in the program. For
example, a comment can be written before the statement, after the statement
or within the statement as shown below:
/* formula */ si = p * n * r / 100 ;
si = p * n * r / 100 ; /* formula */
si = p * n * r / /* formula */ 100 ;

 Sometimes it is not so obvious as to what a particular statement in a program


accomplishes. At such times it is worthwhile mentioning the purpose of the
statement (or a set of statements) using a comment. For example:

/* formula for simple interest */


si = p * n * r / 100 ;

 Often programmers seem to ignore writing of comments. But when a team is


building big software well commented code is almost essential for other team
members to understand it.

 Although a lot of comments are probably not necessary in this program, it is


usually the case that programmers tend to use too few comments rather than too
many. An adequate number of comments can save hours of misery and suffering
when you later try to figure out what the program does.

 The normal language rules do not apply to text written within /* .. */. Thus we
can type this text in small case, capital or a combination. This is because the
comments are solely given for the understanding of the programmer or the
fellow programmers and are completely ignored by the compiler

 Comments cannot be nested. For example, /* Cal of SI /* Author sam date


01/01/2002 */ */
is invalid.

 A comment can be split over more than one line, as in,


/* This is
a jazzy

Basic Programming – NTA 6 Page 3


comment */

b) PREPROCESSOR DIRECTIVE
Now let us observe the line
# include <stdio.h>

This is called a preprocessor directive. It is written at the beginning of the


program. It commands that the contents of the file stdio.h should be
included in the compiled machine code at the place where # include appears.

The file stdio.h contains the standard input/output routines.

All preprocessor directives begin with pound sign # which must be entered
in the first column. The # include line must not end with a semicolon. Only
one preprocessor directive can appear in one line.

Include statements call include files (sometimes also referred to as "header


files") which are text files containing information about function declarations,
constants and structures. When your program is compiled, the information in
the specified include file is 'pasted' directly into your program.
/* Examples: */
#include <math.h> /* incl. file
with math. function info */
#include <stdio.h> /* include file
with I/O info */
#include <time.h> /* include file
with time funct. info */
#include <graph.h> /* include file with graphics info */
#include <myconst.h> /* see example directly below */

Here is a very simple example which illustrates the purpose of include files.
Assume that we were to write programs which depend on predefined
physical constants, such as h, c, G, k etc. Instead of looking the values up and
entering them directly into each of our programs, we could write a short text
(i.e. ASCII) file using the QuickC editor. Something like this:
/* SI Constants */
/* File Name:
*/
myconst.h
/* this statement defines the
#define c 3.0e8 */
constant 'c'
/* see section I. c) for more information on
'define' statements. */
#define G 6.67e- /* this defines the constant 'G' */

Basic Programming – NTA 6 Page 4


11
#define k
/* this defines the constant 'k' */
1.38e23

Next, we save this file in the include subdirectory as "myconst.h" (Note, the
extension ".h" is used to distinguish include files from C programs which
have extension .c). If we enter in any of our future programs:
#include <myconst.h>
then all the above defined constants can be used directly in such a program
and they do not have to be declared or entered again. In other words, when
your program compiles, the entire content of 'myconst.h' is directly pasted or
'included' in the program. The most commonly used include files contain
function declarations for predefined C functions. Each C function must be
declared somewhere, i.e. the function's name, its type and the arguments
must be declared before it can be used. In our programs, we will be using
numerous predefined C functions such as sin(), printf(), scanf() etc. Since
these functions must be declared we should type their often lengthy and
cumbersome declarations in our programs. Lucky for us, someone has
already entered all predefined function declarations in various include files.
Hence, using an include statement in our program which refers to a particular
include file is identical to typing all the statements in the include file directly
into our program.

The declarations from related functions are usually grouped together. For
example, the declarations for all predefined math functions, such as sin(),
exp(), rand(), log() etc., are stored in the file 'math.h'. To find out which
include file is needed for a particular function, read the summary help screen
(i.e. move the cursor to the function statement in your program and press f1).
Note, if you forget to enter the corresponding include file for a function, the
program may still compile without error messages but it may not work;
hence, always check that each predefined C function has its corresponding
include file declared!

c) Main( ) Function
The next line is main( ). It defines what is known as a function in C. A C
program is made up of many functions. The function main( ) is required in all
C programs. It indicates the start of a C program. We will use main( ) at the
beginning of all programs. Observe that main( ) is not followed by a comma
or semicolon.

 Technically speaking main( ) is a function. Every function has a pair of


parentheses ( ) associated with it.

Basic Programming – NTA 6 Page 5


 Any variable used in the program must be declared before using it.
For example, int p, n ;
float r, si ;

 Any C statement always ends with a ; For example,


float r, si ;

d) Braces {And}
Braces {and} enclose the computations carried out by main ( ). Each line in the
program is a statement. Every statement is terminated by a semicolon; The
statement itself can be written anywhere in a line. More than one statement
can be on a line as a semicolon separates them.
However it is a good practice to write one statement per line.

e) Declaration

In the above program the first statement int p, q, area, perimeter;


This statement is called a declaration. It informs the compiler that p,q, area
and perimeter are variable names and that individual boxes must be reserved
for them in the memory of the computer. Further it tells that the data to be
stored in the memory boxes named p,q, area and perimeters are integers
namely, whole numbers without a fractional part(e.g, 0,1,2,...). The statement
ends with a semicolon .

f) Assignment Statements
The statement p=4; is an assignment statement. It commands that the integer
4 be stored in the memory box named p. when the statement is executed the
integer 4 will be stored in the memory box named p

g) Arithmetic Statement
The statement area=p*q; is an arithmetic statement. It commands that the
numbers stored in memory boxes p and q should be copied in to the CPU.
The original contents of p and q remain in their respective boxes. These
numbers are multiplied by the CPU and product is stored in box named area.
After executing this statement the box named area will contain 24 as shown
below:-

Basic Programming – NTA 6 Page 6


The next statement perimeter = 2 *(p+q) is also an arithmetic statement.

h) printf

This formatted output function statement defined in stdio.h file used to print
the string or the values of variables on the output screen.

Syntax:
printf(“<format string>”, <variables-list>);

Here, the format string will contain the string and the format specifiers or
format codes to display the values of variables in the sequence of format
specifiers.

The format string is enclosed in quotes. It specifics any message to be printed


and the manner in which the contents of variables are to be displayed for
each of the variables in the list of variables.

Here the %d is called as integer format specifier and used to print the integer
value of variable on the screen. Such 16 different format specifiers / format
codes are used in printf as well as scanf. These are listed below:

printf(“area = % d\n”, area);

The format string is % d\n The symbol % d says interpret the variable area
occurring after the comma in the printf statement as an integer and display
its value‖. The symbol \n causes the display to advance to the next line. Thus
when this statement is carried out we will see on the screen

Basic Programming – NTA 6 Page 7


Format Specifiers / format codes

%c Character format specifier.


%d Decimal integer format specifier.
%e Scientific notation for floating point format specifier.
%E Scientific notation for floating point format specifier.
%f Floating-point format specifier.
%g Uses %f or %e, whichever result is shorter.
%G Uses %f or %E, whichever result is shorter.
%i Integer format specifier (same as %d).
%n Records the number of characters written so far.
%o Unsigned octal format specifier.
%p Displays the corresponding argument that is a
pointer.
%s String format specifier.
%u Unsigned integer format specifier.
%x Unsigned hexadecimal format specifier.
%X Unsigned hexadecimal format specifier.
%% Outputs a percent sign (%).

In addition to format specifiers like %f, %d and %c the format string may also
contain any other characters. These characters are printed as they are when the
printf( ) is executed.
Following are some examples of usage of printf( ) function:
printf ( "%f", si ) ;
printf ( "%d %d %f %f", p, n, r, si ) ;
printf ( "Simple interest = Tshs. %f", si ) ;
printf ( "Prin = %d \nRate = %f", p, r ) ;
What is ‗\n‘ doing in this statement? It is called newline and it takes the cursor
to the next line. Therefore, you get the output split over two lines. ‗\n‘ is one of
the several Escape Sequences available in C.

Character Meaning

\n New line
\t Tab
\b Backspace
\v Vertical tab
\a Audible Alert (Bell)

Basic Programming – NTA 6 Page 8


\r Carriage return
\f Farm Feed
\\ Backslash
\‗ Single Quote
\― Double Quote

i) Scanf

This formatted input function statement defined in stdio.h file and used
to accept the values of variables from the keyboard.
Syntax:
scanf(“<format string>”, <variables-list>);

For example:
int var1;
float var2;
scanf(“%d%f”, &var1, &var2);

Here, the format string will contain the format specifiers or format codes
to accept the values of variables in the sequence of format specifiers.
Note that the ampersand (&) before the variables in the scanf( ) function is a
must. & is an ‗Address of‘ operator. It gives the location number used by the
variable in memory. When we say &a, we are telling scanf( ) at which
memory location should it store the value supplied by the user from the
keyboard.
j) Define Statements
Define statements declare constants. Constants are 'variables' that will not
change during the program execution. Define statements can be stored in a
separate include file which is useful if there is a large number of them. You
don't need to use capital letters for the constant names, but it is a good (and
very common) practice and helps to distinguish them from variables.
Three very common mistakes with define statements are:
1) to include an equal sign between the name and its declaration,
2) to use a semicolon at the end of the statement,
3) to use type definitions, such as short, float etc. with define
statements.
#define PI = 3.1416 /* W R O N G ! ! ! */
#define PI 3.1416; /* W R O N G
! ! ! */
#define PI 3.1416 /* R I G H T

Basic Programming – NTA 6 Page 9


*/
#define float PI 3.1416 /* W R O N G */

4-3: Type casting or Type conversion


The C programming language has ability to convert one type of the data into
another type temporarily. This is called as type casting or type conversion.
When a C expression contains different types of the data, the result of that
expression is always be in highest data types in the expression. For example:

int num1, num2;


float x;
long y;
here, when we write the expression,
num1 * num2 + x/y;
will always result in the long type of the data. And the expression,
num2 + x * num1;
will result in float type of the data. This is because, it is the property of the
expression. It is referred as automatic type casting. The type cast operator
- ( ) can be used to convert one data type into another temporarily. This is
referred as manual type casting. Such as:
int x = 10, y = 4;
float result;
result = x / y;
printf(―Division: %f‖, result);
Here, the printf statement will output:
Division: 2.000000
But, it is not the accurate answer. So type casting is required. Such as,
result = (float) x / y;
This statement will convert value of x temporarily into float type. So result
of expression will automatically be float. Now the printf statement will
output:
Division: 2.500000
This concept is referred as type casting, which is found to be one of the
useful concepts in ‗C‘.

4-4 Some C Program Examples

Example 4-1
Write a program to convert a temperature given in Celsius to Fahrenheit -
The formula for conversion is f = 1.8C + 32

Basic Programming – NTA 6 Page 10


/* Example program */
/* This program converts a Celsius temperature to Fahrenheit */

# include <stdio.h>
main ( )
{
float fahrenheit, celsius;
scanf(“%f”, & celsius);
fahrenhit = 1.8*celsius + 32.0;
printf (“fahrenheit = % f\n”, fahrenheit);
} /* End of main */
Example 4-2
Write a program to multiply two number..

/ * program to multiply two numbers */


# include <stdio.h>
main( )
{
Float num 1,num2,product;
num1=300.0;
num2=0.6;
product = num1 * numb2;
printf(“ \n %f times %f is %f \n”, num1,num2,product);
}

Output:
300.000000 times 0.600000 is 180.000000

Example 4-3
Write a program to compute average of three numbers

* program to computer average of three numbers * /


#include<stdio.h>
{
int a = 8;
int b = 10;
int c = 4;
int sum, remainder;
float average;
/* Calculate the average and display the result */
sum = a + b + c;
average = sum / 3;

Basic Programming – NTA 6 Page 11


remainder = sum % 3;
printf(The average of %d, %d, %d is %d and %d/3
\n”,a,b,c,average,remainder);
}

Output:
The average of 8,10,4 is is 7.000000 and 1/3

Example 4-4
Write a program to find the area and perimeter of a circle given its radius.

Algorithm :
1. Start
2. Assign Pi ← 3.1415
3. Input radium
4. Calcualte area ← 2*pi*r
peri ← 2*pi*r
5. Output Area, Perimeter
6. Stop

/* CALCULATION OF AREA AND PERIMETER OF A CRICEL */


#include<stdio.h>
main ()
{
float r,pi=3.1415, area,peri;
printf(“\n Enter radius of circle:”);
scanf(“%f”, &r);
area = pi*r*r;
peri = 2 * pi * r;
printf(“\n Area = %5.2f”,area);
print(“\n Perimeter = %5.2f”,peri);
}
/* END OF PROGRAM */

Example 4-5
Write a program to find the area and perimeter of a rectangle having
length, l and breadth b.

Algorithm:
1. Start
2. Input length & breadth
3. Calculate area←length * breadth
peri←* (length + breadth)
4. Output area,peri
5. Stop.

Basic Programming – NTA 6 Page 12


/*CALCULATION OF PERIMETER AND AREA OF A RECTANGLE */
#include<stio.h>
main ()
{
float l,b,area,peri;
print(“\nEnter length of rectangle:”);
scanf(“%f”,&1);
printf(“\nEnter breadth of rectangle:”);
scanf(“%f”&b);
area=1*b;
peri= 2*(1+b);
printf(“\n Area=%10.2f”,area);
printf(“\n Perimeter=%10.2f”,peri);
}
/*END OF PROGRAM*/

Example 4-5

Writer a program to accept temperature in Fahrenheit and convert it to


degree Celsius and vice versa. [Hint: C=5/9*(F-32]

Algorithm :
1. Start
2. Input temperature in Fahrenheit(F)
3. Calculate Celsius <-5.0/9.0*(F-32.0)
4. Output temperature in Celsius(C)
5. Input temperature in Celsius(C)
6. Calculate Fahrenheit <- (C*9.0/5.0) +32.0
7. Output temperature in Fahrenheit
8. Stop

/* CONVERSION OF TEMPERATURE IN DEGREE TO FAHRENHEIT


AND VICEVERSA*/
#include<stdio.h>
main()
{
float f,c,faren, cel;
printf(“\n Enter temperature in Fahrenheit:”);
scanf(%f”,&f);
cel=5.0/9.0*(f-32.0);
print(“\n temperature in celsius =%10.2f”,cel);
printf(“\n Enter temperature in Celsius:”);
printf(“\n Enter temperature in Celsius:”);

Basic Programming – NTA 6 Page 13


scanf(“%f”,&c);
faren=(c*9.0/5.)+32.0;
printf(“\n Temperature in Fahrenheit=%10.2f”,faren);
}
/* NED OF PROGRAM */

Example 4-6

Basic salary of employee is input through the keyboard. DA is 40% of


basic salary & house rent allowance (HRA) is 20% of the basic salary.
Calculate his gross salary?

#include<stdio.h>
void main( )
{
float Basic, DA, HRA, GS;
printf(“Enter the basic salary”);
scanf(“%f”, &basic);
DA = (40/100) * basic;
HRA = (20/100)* basic;
GS = DA + HRA + Basic;
printf (“Gross salary = %f ”,GS);
}

Example 4-7

Write a program to compute the addition, subtraction, product, quotient


and remainder of two given numbers.

#include <stdio.h>
void main()
{
int n1,n2,add,sub,prod,quot,remain;
printf("\nENTER NUMBER-1: " );
scanf("%d",&n1);
printf("\nENTER NUMBER-2: " );
scanf("%d",&n2);
add=n1+n2;
sub=n1-n2;
prod=n1*n2;
quot=n1/n2;
remain=n1%n2;
printf("\nADDITION OF THE NUMBERS: %d",add);
printf("\nSUBSTRACTION OF THE NUMBERS: %d",sub);

Basic Programming – NTA 6 Page 14


printf("\nPRODUCTION OF THE NUMBERS: %d",prod);
printf("\nQUOTIENT OF THE NUMBERS: %d",quot);
printf("\nREMAINDER OF THE NUMBERS: %d",remain);
}

Example 4-9

Write a program to compute the seconds from a given age.


#include <stdio.h>
int main()
{
long unsigned age,sec;
printf("\nENTER YOUR AGE: ");
scanf("%lu",&age);
sec=age*365*24*60*60;
printf("\nAGE IN SECONDS: %lu",sec);
}

EXERCISE
1. Determine which of the following are valid identifiers. If invalid, explain why ?
(a) record 1 (b) return (c) name_and_address (d) name-and-address
2. What is the range of long double?
3. What does a declaration do?
4. What are the rules for naming variables?
5. What is the purpose of the preprocessing directive:
#include <stdio.h>
6. Discuss the various types of constants?
7. What is an operator ? Describe several different type of operator included in C.
8. What are the basic modules of a C program called?
9. What is a syntax error? Give an example of one in English and one in C.
10. What is a semantic error? Give an example of one in English and one in C.
11. Which of the following are C keywords? main, int, function, char, =
12. Which data type would you use for each of the following kinds of data?
a. The population of East Simpleton
b. The cost of a movie on DVD
c. The most common letter in this manual
d. The number of times that the letter occurs in this manual.
13. Why would you use a type long variable instead of type int?
14. Identify the type and meaning, if any, of each of the following constants:
a. '\b'
b. 1066
c. 99.44

Basic Programming – NTA 6 Page 15


d. 0XAA
e. 2.0e30
15. Identify what each of the following escape sequences represents:
a. \n
b. \\
c. \"
d. \t
16. Assume all variables are of type int. Find the value of each of the following
variables:
a. x = (2 + 3) * 6;
b. x = (12 + 6)/2*3;
c. y = x = (2 + 3)/4;
d. y = 3 + 2*(x = 7/2);
17. Assume all variables are of type int. Find the value of each of the following
variables:
a. x = (int) 3.8 + 3.3;
b. x = (2 + 3) * 10.5;
c. x = 3 / 5 * 22.0;
d. x = 22.0 * 3 / 5;

18. Construct statements that do the following (or, in other terms, have the
following side effects):
a. Increase the variable x by 10.
b. Increase the variable x by 1.
c. Assign twice the sum of a and b to c.
d. Assign a plus twice b to c.

19. Construct statements that do the following:


a. Decrease the variable x by 1.
b. Assigns to m the remainder of n divided by k.
c. Divide q by b minus a and assign the result to p.
d. Assign to x the result of dividing the sum of a and b by the product of c
and d.
20. State different data types supported by ‗C‘ language
21. Write a ‗C‘ statement for each of the following:
ii. Relational operator.
iii. Assignment operator.
22. State the use of increment and decrement operator and give its precedence and
Associativity.
23. Define the following:
i. Expressions
ii. Data types
iii. Logical operators

Basic Programming – NTA 6 Page 16


24. State the use of increment and decrement operators. Also give difference
between i++ and ++i with example.
25. What is variable? How to declare it? How variable differs from constant?
26. What is variable declaration and variable initialization?
27. What are the uses of printf( ) and scanf( )?
28. List different relational and logical operators. What will be the output of
following program
#include<stdio.h>
void main( )
{
float a = 5, b = 2;
int c;
c = a % b;
printf(“%d”,c);
}
29. State use of %c %d and %f. Write output of following:
#include<stdio.h>
main( )
{
float y = 123.456;
printf(“%f %.3f %.1f \n\n”, y, y, y);
}

30. Define the following:


a) Keyword
b) Variable.
c) Data types
d) Constants.

31. State four relational operators with its meaning.


32. State four printf format codes.
33. State the arithmetic and logical operators with its meaning.
34. State four rules of choosing variable‘s name.
35. Differentiate between unary, binary and ternary operators.
36. What is precedence and associativity of operators?
37. Explain the use of manual and automatic type casting with suitable Example.
38. What is comment? Explain its use
39. Is this a valid C program? Explain:
main0 {22;}
40. Where the name of the language ―C‖ does comes from?
41. What‘s wrong with these declarations?
int first = 22, last = 99, new = 44, old = 66;

Basic Programming – NTA 6 Page 17


42. What‘s wrong with these declarations?
int x = y = 22;
43. Write four different C statements that each subtract 1 from the integer variable
n.
n = n - 1;
n - --1;
- -n;
n--;

44. Point out the errors, if any, in the following C statements:

a) int = 314.562 * 150 ;


b) name = ‗Ajay‘ ;
c) varchar = ‗3‘ ;
d) 3.14 * r * r * h = vol_of_cyl ;
e) k = ( a * b ) ( c + ( 2.5a + b ) ( d + e ) ;
f) m_inst = rate of interest * amount in rs ;
g) si = principal * rateofinterest * numberofyears / 100 ;
h) area = 3.14 * r ** 2 ;
i) volume = 3.14 * r ^ 2 * h ;
j) k = ( (a * b ) + c ) ( 2.5 * a + b ) ;
k) a=b=3=4;
l) count = count + 1 ;
m) date = '2 Mar 04' ;

45. What is meant by ―top-down‘‘ programming? What are its advantages? How is
it carried out?
46. What is pseudocode? What advantage is there in using pseudocode to plan a
new program?
47. What is meant by ―bottom-up‖ programming? How does it differ from top-
down programming?
48. How much flexibility does the programmer have in the logical sequencing of
the statements within a C program? Explain.
49. Why are some statements indented within a C program? Is this indentation
absolutely necessary?
50. What are the reasons for placing comments within a C program? How
extensive should these comments be?
51. Name two factors that contribute to the generation of clear, legible output data.
52. What useful information is provided by prompts?
53. How is a program entered into the computer in most contemporary C
programming environments?
54. What is a program name extension?
55. What is a syntactic error? Name some common syntactic errors.
Basic Programming – NTA 6 Page 18
56. What is an execution error? Name some common execution errors.
57. How do syntactic errors and execution errors differ from one another?
58. What is a logical error? How do logical errors differ from syntactic and
execution errors?
59. What are diagnostic messages?
60. What is the difference between compilation messages and execution messages?
Name some situations in which each type of diagnostic message would be
generated.
61. What is error isolation? For what is it used? How is error isolation carried out?

Multiple choice questions

62. Pick up the correct alternative for each of the following questions:

(a) C language has been developed by


(1) Ken Thompson
(2) Dennis Ritchie
(3) Peter Norton
(4) Martin Richards

(b) C can be used on


(1) Only MS-DOS operating system
(2) Only Linux operating system
(3) Only Windows operating system
(4) All the above

(c) C programs are converted into machine language with the help of
(1) An Editor
(2) A compiler
(3) An operating system
(4) None of the above
(d) The real constant in C can be expressed in which of the following forms
(1) Fractional form only
(2) Exponential form only
(3) ASCII form only
(4) Both fractional and exponential forms

(e) A character variable can at a time store


(1) 1 character
(2) 8 characters
(3) 254 characters

Basic Programming – NTA 6 Page 19


(4) None of the above

(f) The statement char ch = ‘Z’ would store in ch


(1) The character Z
(2) ASCII value of Z
(3) Z along with the single inverted commas
(4) Both (1) and (2)

(g) Which of the following is NOT a character constant


(1) ‗Thank You‘
(2) ‗Enter values of P, N, R‘
(3) ‗23.56E-03‘
(4) All the above

(h) The maximum value that an integer constant can have is


(1) -32767
(2) 32767
(3) 1.7014e+38
(4) –1.7014e+38

(i) A C variable cannot start with


(1) An alphabet
(2) A number
(3) A special symbol other than underscore
(4) Both (2) & (3) above

(j) Which of the following statement is wrong


(1) mes = 123.56 ;
(2) con = 'T' * 'A' ;
(3) this = 'T' * 20 ;
(4) 3 + a = b ;

(k) Which of the following shows the correct hierarchy of arithmetic operators in C
(1) **, * or /, + or -
(2) **, *, /, +, -
(3) **, /, *, +, -
(4) / or *, - or +

(l) In b = 6.6 / a + 2 * n ; which operation will be performed first?


(1) 6.6 / a
(2) a + 2
(3) 2 * n
(4) Depends upon compiler

(m) Which of the following is allowed in a C Arithmetic instruction

Basic Programming – NTA 6 Page 20


(1) [ ]
(2) { }
(3) ( )
(4) None of the above

(n) Which of the following statements is false


(1) Each new C instruction has to be written on a separate line
(2) Usually all C statements are entered in small case letters
(3) Blank spaces may be inserted between two words in a C statement
(4) Blank spaces cannot be inserted within a variable name

(o) If a is an integer variable, a = 5 / 2 ; will return a value


(1) 2.5
(2) 3
(3) 2
(4) 0
(p) The expression, a = 7 / 22 * ( 3.14 + 2 ) * 3 / 5 ; evaluates to
(1) 8.28
(2) 6.28
(3) 3.14
(4) 0
(q) The expression, a = 30 * 1000 + 2768 ; evaluates to
(1) 32768
(2) -32768
(3) 113040
(4) 0
(r) The expression x = 4 + 2 % - 8 evaluates to
(1) -6
(2) 6
(3) 4
(4) None of the above

(s) Hierarchy decides which operator


(1) is most important
(2) is used first
(3) is fastest
(4) operates on largest numbers

(t) An integer constant in C must have:


(1) At least one digit
(2) At least one decimal point
(3) A comma along with digits
(4) Digits separated by commas

Basic Programming – NTA 6 Page 21


(u) A character variable can never store more than
(1) 32 characters
(2) 8 characters
(3) 254 characters
(4) 1 character
(v) In C a variable cannot contain
(1) Blank spaces
(3) Decimal point
(4) All the above
(w) Which of the following is FALSE in C
(1) Keywords can be used as variable names
(2) Variable names can contain a digit
(3) Variable names do not contain a blank space
(4) Capital letters can be used in variable names
(x) In C, Arithmetic instruction cannot contain
(1) variables
(2) constants
(3) variable names on right side of =
(4) constants on left side of =

(y) Which of the following shows the correct hierarchy of arithmetic operations in C
(1) / + * -
(2) * - / +
(3) + - / *
(4) * / + -
(z) What will be the value of d if d is a float after the operation d = 2 / 7.0?
(1) 0
(2) 0.2857
(3) Cannot be determined
(4) None of the above

Solved Programming Exercises

1. The distance between two cities (in km.) is input through the keyboard. Write a
program to convert and print this distance in meters, feet, inches and centimeters
.

/*
Distance Conversion:
1Km = 39370 inches
1Km = 3281 Feet
1Km = 100000 Cm
1Km = 1000 metres

Basic Programming – NTA 6 Page 22


*/

#include<stdio.h>

main()
{
float km,m,cm,inch,foot;

printf("Enter the distance between the two cities in Km: ");


scanf("%f", &km);

inch = 39370*km;
foot = 3281*km;

cm= 100000*km;
m = 1000*km;

printf ("\nDistance converted to inches: %f", inch);


printf ("\nDistance converted to feet: %f", foot);

printf ("\nDistance converted to centimeters: %f", cm);


printf ("\nDistance converted to meters: %f", m);

Alternative method:

#include<stdio.h>

int main()
{
float km,metres,feet,inches,cm;

printf("Enter the distance in (km): ");


scanf("%f",&km);

/*conversions*/
metres = km *1000;
feet = km * 3280.83;
inches = km * 39370.0787;
cm = metres *100;

/*printing the values after conversions*/


printf("km = %f\nmetres = %f\nfeet = %f\ninches = %f\ncm =
%f\n",km,metres,feet,inches,cm);

Basic Programming – NTA 6 Page 23


return 0;
}

2. If the marks obtained by a student in five different subjects are input


through the keyboard, find out the aggregate marks and percentage marks
obtained by the student. Assume that the maximum marks that can be obtained
by a student in each subject is 100.

#include<stdio.h>
main()
{

int m1, m2, m3, m4, m5, total;


float percentage;

printf ("Enter the marks obtained by the student in all the five subjects: ");
scanf ("%d %d %d %d %d", &m1, &m2, &m3, &m4, &m5);

total= m1+m2+m3+m4+m5;
percentage = total/5;

printf ("\nThe aggregate marks obtained by the student are: %d", total);
printf ("\nThe percentage obtained by the student are %f", percentage);

Alternative method:

#include<stdio.h>

int main()
{
float s1,s2,s3,s4,s5;
float total,avg;

printf("Enter the marks of each subject: ");


scanf("%f %f %f %f %f",&s1,&s2,&s3,&s4,&s5);

total = (s1+s2+s3+s4+s5);
avg = (total/500)*100;

printf("The total is %f and the average is %f\n",total,avg);

Basic Programming – NTA 6 Page 24


return 0;
}

3. Temperature of a city in Fahrenheit degrees is input through the keyboard.


Write a program to convert this temperature into Centigrade degrees.

/*To convert Fahrenheit to Celsius, subtract 32 degrees and divide by 1.8.


To convert Celsius to Fahrenheit, multiply by 1.8 and add 32 degrees.*/

#include<stdio.h>

int main()
{
float fh,cs;

printf("Enter the temperature in fahrenheit: ");


scanf("%f",&fh);

cs = (fh-32.0)*(5.0/9.0);

printf("Fh = %f\nCS = %f\n",fh,cs);

return 0;
}

4. The length and breadth of a rectangle and radius of a circle are input through the
keyboard. Write a program to calculate the area and perimeter of the rectangle,
and the area and the circumference of the circle.

/*
aor: area of rectangle
por: perimeter of rectangle
aoc: area of circle
coc: circumference of circle
*/

#include <stdio.h>

Basic Programming – NTA 6 Page 25


main()
{
float length, breadth, radius, aor, por, aoc, coc;

printf ("\nEnter the Length and Breadth of the Rectangle: ");


scanf("%f %f", &length, &amp;breadth);

printf("\nEnter the Radius of the Circle: ");


scanf("%f", &radius);

aor = length*breadth;
por= 2*(length+breadth);

aoc = 3.14*radius*radius;

coc = 2*radius*3.14;

printf("\nThe area of the rectangle is: %f", aor);

printf("\nThe perimeter of the rectangle is: %f ", por);

printf("\n\nThe area of the Circle with radius %f is: %f ", radius, aoc);

printf("\nThe circumference of the same circle is: %f", coc);

}
Or

#include<stdio.h>

int main()
{

float len,bre,rad;
float peri,circum,area_rec,area_circle;

printf("Enter the length and breadth of rectangel: ");


scanf("%f %f",&len,&bre);
area_rec = len*bre;
peri = 2*(len+bre);
printf("Rectangle:\nArea = %f\nPerimeter = %f\n",area_rec,peri);

Basic Programming – NTA 6 Page 26


printf("Enter the radius of circle: ");
scanf("%f",&rad);
area_circle = 3.14*rad*rad;
circum = 2*3.14*rad;
printf("Circle:\nArea = %f\nCircumference = %f\n",area_circle,circum);

return 0;
}

5. Two numbers are input through the keyboard into two locations C and D.
Write a program to interchange the contents of C and D.

#include<stdio.h>
main ()

{
int A,C,D;
printf ("Enter the value of C and D: ");

scanf ("%d %d", &C, &D);

A=C;

C=D;
D=A;

printf ("\nThe exchanged values of C and D are: %d and %d ", C, D);

6. If a five-digit number is input through the keyboard, write a program to calculate


the sum of its digits.

(Hint: Use the Modulus Operator '%')

/*If a five-digit number is input through the keyboard, write a program to


calculate the sum of its digits.
(Hint: Use the Modulus Operator '%') */

/*Is 12345 / 100 % 10 not 3?


The divide by 100 strips the 45 and the remainder of 123 / 10 would be 3.

Basic Programming – NTA 6 Page 27


unit digit 5 would be 12345 % 10
tens digit would be (12345 / 10) % 10
hundreds digit would be (12345 / 100) % 10 ...
*/

/* Using / ..the normal division opeator returns the quotient.


Using % ..the modulus Operator returns the Remainder. */

#include<stdio.h>
main ()
{
int number, last_digit, next_digit, total;

printf ("Enter the number whose sum of digits is to be calculated: ");


scanf ("%d", &number);

last_digit = number%10;
total = last_digit;

next_digit = (number/10) % 10;

total = total + next_digit;

next_digit = (number/100) % 10;

total = total + next_digit;

next_digit = (number/1000) %10;

total = total + next_digit;

next_digit = (number/10000) %10;

total = total + next_digit;

printf ("The sum of the digits of the entered number is: %d", total);

7. If a five-digit number is input through the keyboard, write a program to reverse


the number.

Basic Programming – NTA 6 Page 28


/*Use an integer variable to store the reverse (say rev_num).
take out the first (rightmost) digit of the number.
Give it to rev_num.
Take out the 2nd digit from right.
Now multiply rev_num by 10 and add this new digit to it.
Do this till the last digit.

*/

/*To understand the program, assume that the five digit number -- 12345 is entered
Calculate the values manually and check against the given number.

The final result (reversed number) is going to be 54321*/

#include<stdio.h>
main()
{
int number, rev_num, next_digit,last_digit;

printf ("Enter the number that is to be reversed: ");


scanf("%d", &number);

last_digit = number - ((number / 10) * 10); /*units place*/

rev_num = last_digit; /* 5 */

next_digit = (number / 10) - ((number / 100) * 10); /*tenth's place*/

rev_num = (rev_num * 10) + next_digit; /*54*/

next_digit = (number / 100) - ((number / 1000) * 10); /*hundred's place*/

rev_num = (rev_num * 10) + next_digit; /*543*/

next_digit = (number / 1000) - ((number / 10000) * 10); /*thousand's place*/

rev_num = (rev_num * 10) + next_digit; /*5432*/

next_digit = (number / 10000) - ((number / 100000) * 10); /*ten thousand's place*/

Basic Programming – NTA 6 Page 29


rev_num = (rev_num * 10) + next_digit; /*54321*/

printf ("The Reversed Number is: %d",rev_num);


}

8. If a four-digit number is input through the keyboard, write a program to obtain


the sum of the first and last digit of this number.

/*HINT: If a number is divided using % , then the number to the right side of the decimal
point is the result. (This applies only to integers.) */

#include<stdio.h>

main ()

int number, last_digit, first_digit, total;

printf (" Enter the number which is to be operated on: ");

scanf ("%d", &number);

last_digit = number % 10;

total = last_digit;

first_digit = (number / 1000) % 10;

total = total + first_digit;

printf ("The total of the first and the last digit of the entered number is: %d", total);

}
9. A cashier has currency notes of denominations 10, 50 and 100. If the amount to
be withdrawn is input through the keyboard in hundreds, find the total number
of currency notes of each denominations the cashier will have to give to the
withdrawer.

Basic Programming – NTA 6 Page 30


main()
{
int cur,hun,ten,fifty,hunR,tenR,fiftyR;

clrscr();
printf("Enter currency in hundreds: ");
scanf("%d",&cur);

hun = cur/100;
ten = cur/10;
fifty = cur/50;

hunR = cur%100;
tenR = cur%10;
fiftyR = cur%50;

printf("\n%d Ten Notes",ten);


printf("\n%d Hundred Notes",hun);
printf("\n%d Fifty Notes\n\n\n",fifty);
printf("\n%d Left: if Ten Notes",tenR);
printf("\n%d Left: if Hundred Notes",hunR);
printf("\n%d Left: if Fifty Ten Notes",fiftyR);
getch();
}

Basic Programming – NTA 6 Page 31

You might also like