Fundamentals - 2
Fundamentals - 2
Fundamentals - 2
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.
2
http://pradeeppearlz.blogspot.com/
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:
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:
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.
3
http://pradeeppearlz.blogspot.com/
# 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.
4
http://pradeeppearlz.blogspot.com/
The definition section defines all the symbolic constants. This can be achieved by the preprocessor
directive #define as follows:
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 (;).
5
http://pradeeppearlz.blogspot.com/
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
6
http://pradeeppearlz.blogspot.com/
Program #2
Program #3
7
http://pradeeppearlz.blogspot.com/
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
8
http://pradeeppearlz.blogspot.com/
for a great many things while our program executes. It holds the return addresses of function calls,
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.
10
http://pradeeppearlz.blogspot.com/
Interview question #1
Interview question #2
Interview question #3
11
http://pradeeppearlz.blogspot.com/
4.5. Common programming errors
An error is the mistake that causes the
proper execution of program to be
stopped. The errors may be classified into
the following categories:
× Compile-time errors.
× Linker errors.
× Run-time errors.
Compile-time errors: Compile-time
errors are the most common, easy to
locate and in a way harmless. Most
common causes of compilation errors are:
1. Not terminating the statement with
a semicolon or putting a semicolon
at the wrong place.
2. Using values not defined.
3. Declaring variables after
assignment statement.
4. Failure to close the format string or
the definition of function.
5. Inability to include header files for
using library functions (In case it is
essential in the compiler you are
using).
Ex:
main()
{
float x;y; /*Error: semicolon at
wrong place*/
x=5.00 /*Error: No semicolon at
the end of statement*/
y=4.00;
k=3;
int k; /*Error: Declaration after
use*/
printf(“k=%d,k); /*Error: Failure to
close format string*/
12
http://pradeeppearlz.blogspot.com/
}
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*/
}
13
http://pradeeppearlz.blogspot.com/
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) #include<stdio.h>
#define PI 3.1412; main()
Main() int base,height;
{ printf(“\nEnter base and height values:”)
Float area; scanf(“%f%f”,base, height)l;
Printf(“\n Enter radius value:); area=1/2bh;
Scanf(“%d,&r); printf(“\n Area of triangle=%f”,area);
Area=4*PI*rrr/3;
Volume=4PIrr;
printf(“%d”,Area);
printf(“f”,volume);
}
2.
3.
4.
5.
6.
14
http://pradeeppearlz.blogspot.com/
15
http://pradeeppearlz.blogspot.com/
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
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.
16
http://pradeeppearlz.blogspot.com/