You are on page 1of 14

Language Fundamentals-III

4
(Writing a Program in C)

Chapter Outline
Chapter Outline
“First, master the fundamentals.”
–Larry Bird Introduction.
Introduction.
Structure of C program.
Structure of C program.
Executing a C program in UNIX
Executing a C program in UNIX
system.
system.
Language processors for
Language processors for
executing a C program.
executing a C program.
Common programming errors.
Common programming errors.
“I long to accomplish great and noble task, but
Multi-file compilation.
it is my chief duty to accomplish small tasks as Multi-file compilation.
if they were great and noble.” Conclusion.
Conclusion.
–Helen Keller

“Success is neither magical nor mysterious. Success


is the natural consequence of consistently applying
the basic fundamentals.”
–Jim Rohn
4.1. Introduction
A program is a well-organized collection of instructions that is used to achieve desired objective. In order
to get our work is done using a computer, a program should be written. For writing a program, it is
necessary to learn a programming language. Usually, a programming language follows programming
paradigm(s), model(s) or style(s) in which a program should be written.
Since C is a programming language, it also follows a programming paradigm that is known as
procedure-oriented programming. In this procedure-oriented programming, a program will be divided into
small pieces called procedures (also known as functions, routines). These procedures are combined
into one single location with the help of return statements. From the main or controlling procedure,
a procedure call is used to invoke the required procedure. After the sequence is processed, the flow of
control continues from where the call was made.

Main
procedure

Procedure#1 Procedure#2 Procedure#N

4.2. Structure of a C program


A C program can be viewed as a group of building blocks called functions. A function is also called as a
subroutine that may include one or more statements designed to perform a specific task. To write a C
program, we first create our own functions or consider built-in functions and then put them together.
A C Program may contain one or more sections as shown below:
Documentation Section
Link Section
Definition Section
Global Declaration section
main( )
{
Declaration Part
Executable Part
}
Sub Program Section
Function-1
Function-2
Function-3
:
:
Function-n
2
The Documentation section consists of a set of comment lines giving the name of the program, the
author and other details, which the programmer would like to use later. Usually, this section can be
included at any place in the program and will be ignored by the C compiler. Comment lines will help the
user to understand the program clearly and easily. Hence, the comment lines increase the readability of
the program. The comment lines can be defined as follows:

/* User’s Message*/

A comment line should begin with /* and end with */, though it is single line comment or multi-line
comment. However, comments with in the comments are not allowed.
Ex: /* Program to find area of triangle*/ [valid comment]
/* This program helps the user to calculate area of triangle by using three sides that will be input by the
user*/ [valid comment]
/*This is comment /* with in another*/ comment*/ [invalid]

The link section provides instructions to the compiler to link functions from standard library. Library
functions are grouped category-wise and stored in different files known as header files. If we want to
access the functions stored in the library, it is necessary to tell the compiler about the files to be accessed.
This is achieved by using the preprocessor directive #include as follows:

# include <filename>

Where “filename” is the name of the header file that contains the required function definition. Usually,
preprocessor directives are placed at the beginning of the program.
Ex: #include<stdio.h>
This statement informs the compiler to search for the file stdio.h in the subdirectory where other header
files are located.
The file to be included in our source code does not necessarily have to be a system header file.
We can include any file available in our system. Suppose that there is a file namely “myfun.c” in our
working directory. We can include this file by writing the following line:
# include ”myfun.c”
It is important to note that the file name is written inside double quotes. This informs the compiler that
the file to be included is available in the current directory.

# include <first.c> This command looks for the file “first.c” in the specified
directories only.
# include “first.c” This command looks for the file “first.c” in the current
working directory as well as the specified list of
directories only.

3
The definition section defines all the symbolic constants. This can be achieved by the preprocessor
directive #define as follows:

# define const_name value

Where const_name is a legal identifier and value is the one that is going to be substituted. The spaces
should be needed among #define, const_name and value and never be terminated with a semicolon.
Ex: # define PI 3.1412
# define NEWLINE printf(“\n”)
# define int float
# define AND &&
The above lines are also called as macros. When these are used, the value will be substituted in
place of const_name wherever it is appears in our source code.

There are some variables that are used in more than one function. Such variables are called global
variables and are declared in the global declaration section that is outside of all functions. The global
variables can be declared as in the way the local variables inside function are declared and can be
initialized.

Every C program must have one main() function. C permits different forms of main() as follows:
o main()
o int main()
o void main()
o main(void)
o void main(void)
o int main(void)

The empty pair of parentheses indicates that the function has no arguments. This must be
explicitly indicated by using the keyword void inside the parentheses. We may also specify the keyword
int or void before the word main. The keyword void means that the function does not return any
information to the operating system and int means that the function returns an integer value to the
operating system. When int is specified, the last statement in the program must be “return 0”.
The main() function contains two parts: declaration part and executable part. The declaration
part declares all the variables used in the executable part. There is atleast one statement in the
executable part. These two parts must appear between the opening and closing braces. The program
execution begins at the opening brace and ends at the closing brace. The closing brace of the main()
function is the logical end of the program. All statements in the declaration and executable parts end with
a semicolon (;).

4
The subprogram section contains all the user-defined functions that are called in the main() function.
User-defined functions are generally placed immediately after the main() function, although they may
appear in any order.

All sections except main() may be absent when they are not required.
Program #1
Write a program to calculate area and circumfrance of a circle
1. /* A program to calculate area and circumfrance of a circle*/
2. #include<stdio.h>
3. #define PI 3.1412
4. main()
5. {
6. float radius,area,circum;
7. printf(“\nEnter radius:”);
8. scanf(“%f”,&radius);
9. area=PI*r*r;
10. circum=2*PI*r;
11. printf(“\n Area of circle=%f”,area);
12. printf(“\n Circumfrance of circle=%f”,circum);
13. }
Run:
Enter radius:23
Area of circle=1661.694824
Circumfrance of circle=144.495193

Annotation:
1. The first line is a comment that identifies the purpose of the program.
2. The lines 2 and 3 are called as preprocessor directives. The second line is a file-inclusion
directive that is used to include header files and user-defined programs as and when needed.
3. The line 3 is also called as a macro. Usually, it is used to define symbolic constants. Before
execution of program, the macro name (PI) will be substituted with its definition (3.1412),
wherever it appears.
4. The line 4 is the heading for main function. The empty parentheses following the name of the
function indicate that this function does not include any arguments. It is important to note that
the program execution always begins with main().
5. The line 5 indicates the start and line 13 indicates the end of body of main(). From lines 5 to 13,
collectively known as body of main() function or main() function definition.
6. The line 6 is declarative instruction that is used to declare all the variables that are used in a
program. In this program, radius, area and circum are variables that are used to hold the values
of radius, area and circumfrance of circle respectively. Since, all these can hold real values,
these are declared as of float type.
7. The line 8 is used to read a float value from keyboard. The scanf() function reads a value and
stores it in variable radius. Since, radius is of type float, %f is used. %f is a conversion
character that converts the input value into float. For the purpose of user interaction, line 7 is
written.
8. The lines 9 and 10 are called as assignment statements. In line 9, the area is calculated and is
stored in the variable area. In line 10, the circumfrance is calcualated and is stored in variable
circum
9. The lines 11 and 12 print the results that are stored in their respective variables onto the
monitor.

5
Program #2
Write a program to calculate simple interest and amount to be paid
/* A program to calculate simple interest and amount to be paid*/
#include<stdio.h>
int main(void)
{
float p,t,r,si,amount;
printf(“\n Enter principal amount, time and rate of interest:”);
scanf(“%f%f%f”,&p,&t,&r);
si=(p*t*r)/100.0;
amount=p+si;
printf(“\n Simple interest=%.2f”,si);
printf(“\n Amount to be paid=%.2f”,amount);
return 0;
}
Run:
Enter principal amount, time and rate of interest: 1000
2.5
5
Simple interest=125.00
Amount to be paid=1125.00

Program #3
Write a program to encode and decode a 5-letter word. Encode each letter by adding 3 to it.
Decode the encoded word.
/* A program to encode and decode a 5-letter word*/
#include<stdio.h>
int main(void)
{
char word[6];
printf(“\n Enter 5-letter word only:”);
scanf(“%5s”,word);
word[0]=word[0]+3;
word[1]=word[1]+3;
word[2]=word[2]+3;
word[3]=word[3]+3;
word[4]=word[4]+3;
printf(“\n Coded word=%s”,word);
word[0]=word[0]-3;
word[1]=word[1]-3;
word[2]=word[2]-3;
word[3]=word[3]-3;
word[4]=word[4]-3;
printf(“\n Original word=%s”,word);
return 0;
}
Run:
Enter 5-letter word only:
water
Coded word=zdwhu
Original word=water

6
4.3. Executing a C program in UNIX system
Step 1: Creating the C program
Once we load the UNIX operating system into the memory, the computer is ready to receive the program.
The program must be entered into a file that should have a name. The file name consists of letters, digits
and special characters (usually space is omitted), followed by a dot and a letter c.
Ex: simple.c
Hello123.c

A file can be created with the help of a text editor vi. The command for calling the editor and
creating the file is: vi file_name
If the file exists before, it is loaded. If it does not yet exist, the file has to be created so that it is ready to
receive the code to be typed. Any corrections in the program are done under the editor.

When the editing is over, the file should be saved on the disk. It then can be referenced later by
its name. The program that is entered into the file is known as source code or source program.
Step 2: Compiling the C program
Let us assume that we have created the source file: first.c. Now the program is ready for compilation. The
Compilation command to achieve this task under UNIX is: cc first.c

The source program instructions are now translated into a form that is suitable for execution by the
computer. The translation is done after examining each instruction for its correctness. If every thing is
alright, then compilation proceeds silently and the translated program is stored on another file with the
name first.o. This program is also known as object code.

Linking is the process of putting together other program files and functions that are required by the
program. Under UNIX, the linking is done automatically when the cc command is used.

If any mistakes are discovered, then they are listed out and the compilation process ends right
here. The errors should be corrected in the source program with the help of editor and the compilation is
done again.

The compiled and linked program is called the executable object code and is stored in another
file named a.out.

A compiled C program creates and uses four logically distinct regions of memory. The first region is
the memory that actually holds the program’s executable code. The next region is the memory where
global variables are stored. The remaining two regions are the stack and the heap. The stack is used to
for a great many things while our program executes. It holds the return addresses of function calls,

7
arguments to functions and local variables. It also saves the current state of the CPU. The heap is a region
of free memory that our program can use via C’s dynamic memory allocation functions.

Step 3: Running the C program


Running the C program is simple task. The command ./a.out would load the executable object code into
the computer memory and execute the instructions. During execution, the program may request for some
data to be entered through the keyboard. Sometimes, the program does not produce the desired result.
Perhaps, there is some thing wrong with the data or logic. Then it would be necessary to correct the
source program or the data. If the source code is modified, then the entire process of compilation and
running the program should be repeated.

4.4. Language processors for executing a C program


Language processors are the system softwares that play key role in translating a source file into an
executable file. These language processors include: preprocessor, compiler, linker and loader. The
translation process from source file into an executable file is depicted as follows:
1. A C program must be typed into the computer and saved to a file. A text editor is used for this
task. The statements written by the programmer are called source code and the file in which the
statements are saved is called as source file.
2. After the source code is saved to a file, the process of translating it to machine language can begin.
During the first phase of this process, a program called the preprocessor reads the source code.
The preprocessor searches for special lines that begin with the # symbol. These lines (usually,
called as preprocessor directives) contain commands that cause the preprocessor to modify the
source code in someway. The preprocessor modifies the existing source code and stores modified
source code into another file.
3. During the next phase, the compiler steps through the preprocessed source code, translating each
modified source code instruction into the appropriate machine language instruction. This process
will uncover any syntax error that may be in program. If the program is free of syntax errors, the
compiler stores the translated machine language instructions, which are called object code, in an
object file.
4. Although an object file contains machine language instructions, it is not a complete program.
Usually, C is conveniently equipped with a library of prewritten code for performing common
8
operations or some-times difficult tasks. For example, the library contains hardware specific code
for displaying messages on the screen and reading input from the keyboard. Programs almost
always use some part of it. However, when the compiler generates an object file, it does not
include machine code for any run-time library routine the programmer might have used in
program. During the last phase of the translation process, another program called the linker
combines the object file with library routines. Once the linker is finished with this step, an
executable file is created. The executable file contains machine language instructions, or
executable code, and is ready to run on the computer.
5. Once, the executable file is stored on disk, the loader that is a part of operating system brings it to
main memory and starts it running.
This translation process is shown in the following figure:

Source code is
Source Code entered with help
of a text editor by
programmer.

Preprocessor

Modified Source
Code

Compiler

Object Code

Linker

Executable code

9
Interview question #1
What are the differences between compiler and interpreter?
Compiler Interpreter
1) Scans the entire program first and then 1) Translates the program line-by-line.
translates it into machine code.
2) Converts the entire program into machine 2) Each time the program is executed, every line
code; when all the syntax and linker errors are is checked for error and then be converted to
removed from execution. equivalent machine code.
3) Slow for debugging. 3) Good for fast debugging.
4) Execution time is less. 4) Execution time is more.

Interview question #2
What are the functions of linker and loader?
Linkers and loaders perform various related but conceptually different tasks:
1. Program Loading. This refers to copying a program image from hard disk to the main memory
in order to put the program in a ready-to-run state. In some cases, program loading also might
involve allocating storage space or mapping virtual addresses to disk pages.
2. Relocation. Compilers and assemblers generate the object code for each input module with a
starting address of zero. Relocation is the process of assigning load addresses to different parts
of the program by merging all sections of the same type into one section. The code and data
section also are adjusted so they point to the correct runtime addresses.
3. Symbol Resolution. A program is made up of multiple subprograms; reference of one
subprogram to another is made through symbols. A linker's job is to resolve the reference by
noting the symbol's location and patching the caller's object code.
So a considerable overlap exists between the functions of linkers and loaders. One way to think of them
is: the loader does the program loading; the linker does the symbol resolution; and either of them can
do the relocation.

Interview question #3
How many files are created when a C program is written using Borland c compiler?
When a C program is written, four files will be created:
1. Source file (e.g., first.c)
2. Back up file (e.g, first.bak)
3. Object file (e.g., first.obj)
4. Executable file (e.g., first.exe)

10
4.5. Common programming errors
An error is the mistake that causes the
Start
proper execution of program to be
stopped. The errors may be classified into
the following categories: Edit Source code

× Compile-time errors.
× Linker errors. Compiler
× Run-time errors.
Compile-time errors: Compile-time
errors are the most common, easy to Yes
locate and in a way harmless. Most Compile
-time
common causes of compilation errors are: error?
1. Not terminating the statement with
a semicolon or putting a semicolon No
at the wrong place.
Linker
2. Using values not defined.
3. Declaring variables after
assignment statement.
Yes
4. Failure to close the format string or
Linker
the definition of function. error?
5. Inability to include header files for
using library functions (In case it is
No
essential in the compiler you are
using). Execute program
Ex:
main()
{
float x;y; /*Error: semicolon at Run-
time
wrong place*/ error?
Yes
x=5.00 /*Error: No semicolon at
No
the end of statement*/
y=4.00;
k=3; Done

int k; /*Error: Declaration after


use*/
printf(“k=%d,k); /*Error: Failure to
close format string*/
}

11
Linker errors: A program in C generally consists of a number of functions. They can be in different files.
An object file is created when a file containing the source program is successfully compiled. The complete
program may contain a number of object files. They have to be combined to create a single ‘.exe’ file. This
process is known as linking.
Linking is required even if our program contains a single function main() in a single file. This is
because, there are some object files in the library which form a part of the system. Our program has to be
linked with C library.
Linker errors result mainly because of wrong-spelt function names.
Ex:
main()
{
int k=10;
Printf(“k=%d”,k);
}

When the above code gets executed, the following error message gets displayed:
Undefined symbol _Printf in function main.
This is because C is case sensitive. It does not understand Printf(). The function should be written as
printf(), in lower case letters only. The program compiles because the compiler expects the function
Printf() to be available in some other ‘.obj’ module. When it is not available during linking, the process is
terminated with the error message.
Run-time errors: Runtime errors are the most difficult to locate and also most harmful. Even after
successful compiling and linking, the program may not produce the desired output. The compiler will not
help us to find the error because as far as the compiler is concerned there is no error in our program. The
undesirable output produced by a computer program is known as garbage.
Some of logical errors occur because of the following:
1. Variable exceeding the maximum or minimum limit.
2. Inability to supply the address of variable while reading it by scanf().
3. Inability to supply the arguments when the control string has format specifiers.
Ex:
main()
{
int a=25000,b=20000,c,k;
c=a+b;
printf(“%d”,c); /*error: variable exceeding maximum limit*/
printf(“\n Enter k value:”);
scanf(“%d”,k); /*error: segmentation fault*/
printf(“%d”); /*error: garbage value gets printed*/
}

12
Find the errors in the following programs:
/*program to find area, /* volume*/ of \*program to calculate area of triangle with
sphere*/ base and height*\
#include<stdio.h>
main()
#include (stdio.h) int base,height;
#define PI 3.1412; printf(“\nEnter base and height values:”)
Main() scanf(“%f%f”,base, height)l;
{ area=1/2bh;
Float area; printf(“\n Area of triangle=%f”,area);
Printf(“\n Enter radius value:);
Scanf(“%d,&r);
Area=4*PI*rrr/3;
Volume=4PIrr;
printf(“%d”,Area);
printf(“f”,volume);
}

Fill in the blanks of the following programs:


Q /*program to find area volume of sphere…… .....program to calculate area of triangle with
U #..............<stdio.h> base and height…….
#.............. PI 3.1412 #include<stdio.h>
E …………….() main()
{ …..
S ………………. int base,height;
T printf(….Enter radius value:…….)…….. ……………………..
scanf(“……...”,……radius); printf(“\n Enter base and height values:”);
I area=………………………………………….; scanf(“%d%d”,&base,&height);
O volume=…………………………………….; area=……………………………………….
printf(“\n Area=%f\tVolume=%f”……); pintf(“\n Area of triangle=……”,area);
N ………….
}
S

Write equivalent C arithmetic expressions for the following algebraic


expressions
1. ax3+bx2+c
2. s ( s  a )( s  b)( s  c )
3. ( x) 2   x 2
1 a
4. (log e( ))
k ax
5
5. c  ( F  32)
9
ax 2  bx  c
6.
ax 2  bx  c

13
4.6. Multifile Compilation
Multiple files can be compiled at a time using the command cc. Suppose that there are three files namely,
“first.c”,”second.c” and ”third.c”. These three files can be compiled at a time.This can be done as follows:
cc first.c second.c third.c
These files will be separately compiled into object files as “first.o”, “second.o” and “third.o” and then
linked to produce an executable program file a.out.
Note:
1) It is also possible to compile each file separately and link them later. E.g., the commands :
cc –c first.c
cc –c second.c
will compile the source files “first.c” and “second.c” into object files “first.o” and “second.o”. They
can be linked together by the command:
cc first.o second.o

2) We may also combine the source files and object files as follows:
cc sample.c second.o
only “sample.c” gets compiled and then linked with the object file “second.o”. This approach is very
useful when one of the multiple source files need to be changed and recompiled or an already
existing object files is to be used along with the program to be compiled.

3) The linker always assigns the same name to the executable object file as a.out. When we compile
another program, this file will be overwritten by the executable object code of the new program. If
we want to prevent from happening, we should rename the file immediately by using the
command: mv a.out name

We may also achieve this by specifying an option in the cc command as follows: cc –o


name source_file
This will store the executable object code in the file name and prevent the old file a.out
from being destroyed.

4.7. Conclusion
A C program is a collection of functions that is written to achieve desired objective. First, a C program
should be written using any text editor (e.g., vi in UNIX). Later, it should be compiled. If there are errors
(whether these are compile-time or linker errors), these should be corrected by editing source file. Once
the program is error-free, it should be run or executed. If there are run-time errors, these should be
corrected by editing source file. The program should be recompiled and re-executed. If we get desired
output whenever we supply correct inputs, then the program is accurate.

14

You might also like