Lesson4 - Language Fundamentals3
Lesson4 - Language Fundamentals3
Lesson4 - Language Fundamentals3
(Writing a Program in C)
Chapter Outline Chapter Outline 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. Multi-file compilation. Multi-file compilation. Conclusion. Conclusion.
I long to accomplish great and noble task, but it is my chief duty to accomplish small tasks as if they were great and noble. 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
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: /* Users 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*/ user*/ [valid comment] [invalid] [valid comment] /* This program helps the user to calculate area of triangle by using three sides that will be input by the /*This is comment /* with in another*/ comment*/
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> # include first.c This command looks for the file first.c in the specified directories only. This command looks for the file first.c in the current working directory as well as the specified list of directories only.
http://pradeeppearlz.blogspot.com/
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 o o o o o main() int main() void main() main(void) void main(void) 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 (;).
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 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.
http://pradeeppearlz.blogspot.com/
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
http://pradeeppearlz.blogspot.com/
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 programs 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
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 Cs 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.
http://pradeeppearlz.blogspot.com/
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 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 entered with help of a text editor by programmer.
Source Code
Preprocessor
Compiler
Object Code
Linker
Executable code
http://pradeeppearlz.blogspot.com/
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)
http://pradeeppearlz.blogspot.com/
10
http://pradeeppearlz.blogspot.com/
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*/
http://pradeeppearlz.blogspot.com/
12
Find the errors in the following programs: /*program to find area, /* volume*/ of sphere*/ #include (stdio.h) #define PI 3.1412; Main() { Float area; Printf(\n Enter radius value:); Scanf(%d,&r); Area=4*PI*rrr/3; Volume=4PIrr; printf(%d,Area); printf(f,volume); }
\*program to calculate area of triangle with base and height*\ #include<stdio.h> main() int base,height; printf(\nEnter base and height values:) scanf(%f%f,base, height)l; area=1/2bh; printf(\n Area of triangle=%f,area);
Q U E S T I O N S
Fill in the blanks of the following programs: /*program to find area volume of sphere #..............<stdio.h> #.............. PI 3.1412 .() { . printf(.Enter radius value:.).. scanf(...,radius); area=.; volume=.; printf(\n Area=%f\tVolume=%f); }
.....program to calculate area of triangle with base and height. #include<stdio.h> main() .. int base,height; .. printf(\n Enter base and height values:); scanf(%d%d,&base,&height); area=. pintf(\n Area of triangle=,area); .
1 a (log e( )) k a x 5 5. c = ( F 32) 9 ax 2 + bx + c 6. ax 2 bx c
http://pradeeppearlz.blogspot.com/
13
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.
http://pradeeppearlz.blogspot.com/
14