1 Basics and introduction to C – Programming in C, 3/e, 3rd Edition

CHAPTER 1

Basics and Introduction to C

Chapter Outline
1.1  WHY TO USE COMPUTERS?

Computers play a vital role in the socioeconomic progress of a country. Every nation is paying much importance to computer literacy. Progress of individuals, surrounding region, nation and of the world is ensured only with the introduction and use of computers. In every walk of life, computers are being used increasingly. In every part of the world, computers are employed to increase the overall productivity. Moreover, the quality of the products due to application of computers is substantially improved. The impact of computers is very high on mass education, entertainment and productivity in all fields. With the use of computers the cost of production reduces drastically, a lot of time is saved and the best quality is ensured.

With the adoption of the policy of liberalization, privatization and globalization by the governments all over the world, it is necessary to become competitive in the market. Luxurious survival is not easy as was possible in ancient days. With land, labour, muscle power and capital, economy can certainly be boosted to a certain degree, but the intellectual power is highly superior to all these assets. With some know-how (for the common users) and a lot of technical innovations (by the developers), numerical problems, business transactions and scientific applications, can be computed in almost no time. A computer does various tasks on the basis of programs. Intellectual computer is certainly a powerful gadget but human intellectual capability is much higher than that of a computer. Thus, computer does not have its own brain. Brainpower of computer is limited. Thus, human intellectual power is further reinforced by the use of computers frequently in the day-to-day life. By learning programming languages, developing software packages and using hardware of computers, one can make his/ her life and nation prosperous.

1.2   BASICS OF A COMPUTER

Data to be processed by a computer appears in different forms, such as numeric, alphabetical characters either in uppercase or in lowercase, special characters and multimedia. Research applications in universities and colleges frequently use numeric data on large scales, whereas businessmen and people in the corporate sector use both numeric and character data. However, in animation multimedia is used which include text, video and audio.

A computer is a programmable electronic machine that accepts instructions and data through input devices, manipulating data according to instructions and finally providing result to the output device. The result can be stored in memory or sent to the output device. Figure 1.1 shows the conventional block diagram of a conventional computer.

Figure1.1  Block diagram of a conventional computer

Figure 1.2 shows a computer system containing a monitor, a keyboard and a rectangular box comprising CPU on the motherboard.

 

Figure 1.2  computer system

In brief, the various blocks of a computer are described as follows.

Input Device:Input device is used to accept the data and instructions in to the computer. Through the input device, i.e. keyboard, instructions and data are stored in a computer’s memory. Stored instructions are further read by the computer from its memory and thus a computer manipulates the data according to the instructions. The various input devices that can be used in a computer are keyboards, mouse, analog-to-digital converters, light pen, track ball, optical character reader and scanner. Figure 1.3 shows the input devices of a computer. Floppy, compact disc, etc. can be used as input or output device.

Figure 1.3  Input devices of a computer

Central Processor Unit:CPU is the abbreviation for central processor unit. It is the heart of the computer system. It is a hardware device in the computer and quite often it called as microprocessor chip. Since it is a tiny chip hence called as microprocessor chip. This chip is produced from silicon vapor over which millions of transistors are mounted with modern fabrication techniques.

The brain of the computer is CPU. This chip is responsible to interpret and execute the instructions. It comprises arithmetic and logical unit, registers and control unit. The arithmetic and logical unit performs various arithmetic and logical operations on the data based upon the instructions. The control unit generates the timing and control signals for carrying out operations within the processor. Registers are used for holding the instructions and storing the results temporarily. Instructions are stored in the memory and they are fetched one by one and executed by the processor.

Output Device: The output device is used to display the results on the screen or to send the data to an output device. The processed data is ultimately sent to the output device by the computer. The output device can be a monitor, a printer, an LED, seven-segment display, D to A converter, plotter, and so on. Figure 1.4 shows different output devices of a computer.

Figure 1.4  Output devices of a computer

Memory: Memory is used to store the program. There are two types of semi-conductor memories.They are as follows:

  • RAM (Random access memory)
  • ROM (Read only memory)

semi-conductor memory is used for storing the instructions and data in the form of ones and zeros. The memory can be called user’s memory or read–write memory. Processor first reads the instructions and data from the primary memory (semi-conductor memory). Then, it executes the instructions.

One more memory device used by a computer is called read only memory (ROM). This contains a fixed software program for providing certain operations. This is non-volatile memory. Its contents cannot be eliminated when power supply goes off. The basic input–output system (BIOS) is a software used to control various peripheral devices such as a keyboard, a monitor, a printer, a mouse, ports including serial and parallel ports. In fact, this is an operating system. It is possible to access the users’ written programs, i.e. by loading a file, saving it and doing modifications to it in the later stage. As soon as a personal computer is switched on, the software gets booted from ROM. Thus, various functions are assigned to all supporting peripherals of a central processing unit (CPU) and easy interactions are provided to the user by BIOS while booting the system.

For storing volumous data, secondery storage devices can be used. They are optical disk, magnetic disc, tapes, etc.

1.3   LATEST COMPUTERS

The discussion on the various types of computers existing in the market is beyond the scope in this book. Latest computers available in the market are in various shapes and sizes. These computers are just like notebooks or even require lesser space than the notebook. They are handy, light weighted and portable. Because of these reasons many computer users now carry laptops while travelling for their day-to-day work. In the next couple of years, it is predicted that every school-going child would be using a laptop or palmtop, and these devices would be sold just like hot cakes in the market with affordable prizes. A lot of research work is going on in the foreign and Indian Universities, institutes and industries on the reduction of the size of a computer, building more functions in it with low cost, minimum battery power for operating it for large duration in the absence of A.C. mains power supply. In a couple of years, laptops and palmtops would be flooded in the market. These notebook-shaped laptops are as powerful as desktop computers. In other words, the computing power of a laptop would be advancing to that of desktop computers and minicomputers. They are used for the purpose of text processing, web surfing, multimedia operation, image processing and so on. Performances of these computers are constantly improving, and the cost is drastically reducing. A wireless network can be formed easily with laptops with the Bluetooth technology. Wifi wireless network is quite popular nowadays, and there we use these computers quite often.

Typical specifications of a laptop computer are as follows,

  • Processor: Intel Core i7 ( 8M cache,2.80GHz) OR AMD
  • RAM: Minimum 2 GB to Maximum 16 GB
  • Hard disk: Minimum 320 GB up to 1 TB or higher
  • CD/DVD Drive: Dual Layer DVD+/-RW Drive, SuperDrive, Bluetooth and Camera
  • Screen Size: 15.6” up to 23” Flat screen with LCD/LED display
  • Ethernet: 10/100/1000 Mbps Ethernet
  • Port: USB 3.0
  • Graphics Card: From 520 MB or higher
  • Rechargeable Battery back up
  • Operating system such as windows XP/ windows 7/ Linux

For simpler application, one can go for Celeron-based laptop where heat generated by the processor is little. Pentium processors are used only for dedicated applications. Heat generated by this kind of laptop is more and battery is to be frequently charged (Figure 1.5).

Figure 1.5  The laptop

1.4   INTRODUCTION TO C

C is one of the most popular general-purpose programming languages. C language has been designed and developed by Dennis Ritchie at Bell Laboratories, USA, in 1972. Several important concepts of C are drawn from ‘Basic combined programming language’ and ‘B’ language. Figure 1.6 shows the development of C language from the two languages. Martin Richards developed BCPL in 1967. The impact of BCPL on C is observed indirectly through the language B, which was developed by Ken Thompson in 1970. C is also called an offspring of the BCPL. Table 1.1 illustrates the evolution of languages and their inventors of programming language.

Figure 1.6  Evolution of C

Table 1.1  Languages and their inventors

The C language is not tied to any particular operating system. It can be used to develop new operating systems. Refer to Figure 1.7 in which the C language is shown associated with the various operating systems. The C language is closely associated with the UNIX operating system. The source code for the UNIX operating system is in C. C runs under a number of operating systems including MS-DOS. The C programs are efficient, fast and highly portable, i.e. C programs written on one computer can be run on another with mere or almost no modification.

Figure 1.7  C and operating systems

The C programming language contains modules called functions. The C functions are the basic building blocks and the most programmers take its benefit. Programmers include these functions in their program from the C standard library.

C language is a middle-level computer language. It does not mean that C is not powerful and rugged for writing programs like in Fortran and Pascal. It also does not mean that it is troublesome like assembly level languages. It combines the features of a high-level language and functionality like assembly languages. In C, one can develop a program fast and execute fast. It reduces the gap between high-and low-level languages; that is why it is known as a middle level language. It is well suited for writing both application and system softwares.

C is a structural language. It has many similarities with the other structural languages such as Pascal and Fortran. Structured language facilitates the development of a variety of programs in small modules or blocks. Lengthy programs can be divided into shorter programs. The user requires thinking of a problem in terms of functional blocks. With appropriate collection of different modules, the programmer can make a complete program.

It is easy for writing, testing, debugging and maintenance with structured programming. In case some changes are to be done in a program, the programmer can refer to the earlier written module with editor and incorporate the appropriate changes. Hence, structured languages are easier and most of the developers prefer these languages, than the non-structured languages like BASIC and COBOL. Programming with non-structured languages is tough in comparison to structured languages.

C is also called a system-programming language because it is greatly helpful for writing operating systems, interpreters, editors, compilers, database programs and network drivers.

BCPL and B are data type-less languages. However, C language has a variety of data types. The standard data types in C are integers, floating point, characters. Also, derived data types can be created such as pointers, arrays, structures and unions. Expressions are built from operands and operators. Any expression or an assignment or a call to function can be a statement. The pointers provide machine-independent address arithmetic.

C also provides control-flow statements such as decision-making statements (if-else) and (switch-case) multi-choice statement. C supports for, while and do-while looping statements.

C does not have any operator to perform operation on composite object. There does not exist any function or operator that handles entire array or string. For example, to assign elements of one array to another array simply with single assignment statement is not enough, but an element-to-element assignment is to be done. However, structure objects can be copied as a unit.

C is not a strongly typed language. But typed statements are checked thoroughly by C compilers. The compiler will issue errors and warning messages when syntax rules are violated. There is no automatic conversion of incompatible data types. A programmer has to perform explicit type conversion.

UNIX:The UNIX is an interactive operating system. It is useful in microcomputers, minicomputers and main frame computers. This operating system is very portable and supports multi-user processing, multi-tasking and networking. Several users can use UNIX at once for performing the same task. This operating system was developed to connect various machines together. UNIX is primarily used for workstations and minicomputers.

1.5   ABOUT ANSI C STANDARD

For many years, there was no standard version of C language, and the definition provided in reference manual was followed. Due to this reason portability feature of C language was not provided from one computer to another. To overcome this discrepancy, a committee was set up in the summer of 1983 to create a standard C version which is popularly known as American National Standard Institute (ANSI) standard.

This committee had defined once and for all a standard C language. The standardization process took about six years for defining the C language. The ANSI C standard was adopted in 1989, and its first copy of C language was introduced in the market in 1990.

Thus, ANSI C is internationally recognized as a standard C language. The purpose of this standard is to enhance the portability and efficient execution of C language programs on different computers. Today, all compilers of C support the ANSI standard. In other words, almost all C compilers available in the market have been designed to follow ANSI C standard. ANSI C and other C compilers such as turbo-C version 2 support programs developed in this book.

1.6  MACHINE, ASSEMBLY AND HIGH-LEVEL LANGUAGE

It is a computer’s natural language, which can be directly understood by the system. This language is machine dependent, i.e. it is not portable. A program written in 1’s and 0’s is called a machine language. A binary code is used in a machine language for a specific operation. A set of instructions in binary pattern is associated with each computer. It is difficult to communicate with a computer in terms of 1s and 0s. Hence, writing a program with a machine language is very difficult. Moreover, speed of writing, testing and debugging is very slow in machine language. Chances of making careless errors are bound to be there in this language. The machine language is defined by the hardware design of that hardware platform. Machine languages are tedious and time consuming.

1.6.1  Assembly Language

Instead of using a string of binary bits in a machine language, programmers started using English-like words as commands that can be easily interpreted by programmers. In other words, the computer manufacturers started providing English-like words abbreviated as mnemonics that are similar to binary instructions in machine languages. The program is in alphanumeric symbols instead of 1s and 0s. The designer chooses easy symbols that are to be remembered by the programmer, so that the programmer can easily develop the program in assembly language. The alphanumeric symbols are called mnemonics in the assembly language. The ADD, SUB, MUL, DIV, RLC and RAL are some symbols called mnemonics.

The programs written in other than the machine language need to be converted to the machine language. Translators are needed for conversion from one language to another. Assemblers are used to convert assembly language program to machine language. Every processor has its own assembly language. For example, 8085 CPU has its own assembly language. CPUs such as 8086, 80186, 80286 have their own assembly languages.

Following disadvantages are observed with the assembly languages:

  1. It is time consuming for an assembler to write and then test the program.
  2. Assembly language programs are not portable.
  3. It is necessary to remember the registers of CPU and mnemonic instructions by the programmer.
  4. Several mnemonic instructions are needed to write in assembly language than a single line in high-level language. Thus, assembly language programs are longer than the high language programs.

1.6.2  High-Level Language

Procedure-oriented languages are high-level languages. These languages are employed for easy and speedy development of a program. The disadvantages observed with assembly languages are overcome by high-level languages. The programmer does not need to remember the architecture and registers of a CPU for developing a program. The compilers are used to translate high-level language program to machine language. Examples of HLL are COBOL, FORTRAN, BASIC, C and C++. The following advantages are observed with HLL languages:

  1. Fast program development.
  2. Testing and debugging a program is easier than in the assembly language.
  3. Portability of a program from one machine to other.
1.7   ASSEMBLER, COMPILER AND INTERPRETER

A program is a set of instructions for performing a particular task. These instructions are just like English words. The computer interprets the instructions as 1’s and 0’s. A program can be written in assembly language as well as in high-level language. This written program is called the source program. The source program is to be converted to the machine language, which is called an object program. A translator is required for such a translation.

Program translator translates source code of programming language into machine language-instruction code. Generally, computer programs are written in languages like COBOL, C, BASIC and ASSEMBLY LANGUAGE, which should be translated into machine language before execution. Programming language translators are classified as follows. A list of translators is given in Figure 1.8.

Figure 1.8  Translators

Translators are as follows:

  1. Assembler
  2. Compiler
  3. Interpreter

Assembler: An assembler translates the symbolic codes of programs of an assembly language into machine language instructions (Figure 1.9). The symbolic language is translated to the machine code in the ratio of one is to one symbolic instructions to one machine code instructions. Such types of languages are called low-level languages. The assembler programs translate the low-level language to the machine code. The translation job is performed either manually or with a program called assembler. In hand assembly, the programmer uses the set of instructions supplied by the manufacturer. In this case, the hexadecimal code for the mnemonic instruction is searched from the code sheet. This procedure is tedious and time-consuming. Alternate solution to this is the use of assemblers. The program called assembler provides the codes of the mnemonics. This process is fast and facilitates the user in developing the program speedily.

Figure 1.9  Assembler

Compiler: Compilers are the translators, which translate all the instructions of the program into machine codes, which can be used again and again (see Figure 1.10). The program, which is to be translated, is called the source program and after translation the object code is generated. The source program is input to the compiler. The object code is output for the secondary storage device. The entire program will be read by the compiler first and generates the object code. However, in interpreter each line is executed and object code is provided. M-BASIC is an example of an interpreter. High-level languages such as C, C++ and Java compilers are employed. The compiler displays the list of errors and warnings for the statements violating the syntax rules of the language. Compilers also have the ability of linking subroutines of the program.

Figure 1.10  Compiler/interpreter

Interpreter: Interpreters also come in the group of translators. It helps the user to execute the source program with a few differences as compared to compilers. The source program is just like English statements in both interpreters and compilers. The interpreter generates object codes for the source program. Interpreter reads the program line by line, whereas in compiler the entire program is read by the compiler, which then generates the object codes. Interpreter directly executes the program from its source code. Due to this, every time the source code should be inputted to the interpreter. In other words, each line is converted into the object codes. It takes very less time for execution because no intermediate object code is generated.

Linking: C language provides a very large library, which contains numerous functions. In some applications of C the library may be a very large file. Linker is a program that combines source code and codes from the library. Linking is the process of bringing together source program and library code.

The library functions are relocatable. The addresses of various machine codes are defined absolutely and only the offset information is kept. When the source program links with the standard library functions, offset of the memory addresses is used to create the actual address.

1.8  STRUCTURE OF A C PROGRAM

Every C program contains a number of building blocks known as functions. Each function of it performs a specific task independently. A C program comprises different sections shown in Figure 1.11.

Figure 1.11  Structure of a C program

  1. Include Header File Section: C program depends upon some header files for function definition that are used in the program. Each header file has extension ‘.h’. The header files are included at the beginning of the program in the C language. These files should be included using # include directive as given below.

    Example:

    # include <stdio.h> or

    # include “stdio.h”

    In this example, <stdio.h> file is included, i.e. all the definitions and prototypes of function defined in this file are available in the current program. This file is also compiled with the original program. The programmer can include the appropriate header files while executing solved or unsolved programming examples given in this book.

  2. Global Declaration:This section declares some variables that are used in more than one function. These variables are known as global variables. This section must be declared outside of all the functions.
  3. Function main():Every program written in C must contain main() and its execution starts at the beginning of this function. In ASCII C standard, first line of C program from where program execution begins is written as follows.

     

    int main(void)

    This is the function definition for main(). Parenthesis followed to main is to tell the user again that main() is a function. The int main(void) is a function that takes no arguments and returns a value of type int. Here in this line, int and void are keywords and they have special meanings assigned by the compiler. In case int is not mentioned in the above statement, by default the function returns an integer.

    Alternately, one can also write the first line of C program from where program execution begins is as follows.

     

    void main(void)

    Here, this function takes no arguments and returns nothing. Alternately, one can also write the same function as follows.

    void main(): This functions returns nothing and takes no arguments.

    In all chapters, in maximum programming examples the main function is written as void main(). This procedure is followed in this book only to avoid writing return statement at the end of each program. This step helps to minimize source code lines. At few places in this book, main function is initialized with int main(void). In such a case, return statement is used at the end of program (before closing brace). The programmer can either write the function main with int main(void) or void main(). Only in the formal case, return statement should be used before the end of function for terminating the execution of the main function.

    The program contains statements that are enclosed within the braces. The opening brace ({) and closing brace (}) are used in C. Between these two braces, the program should declare declaration and executable part. The opening curly brace specifies the start of the definition of the main function. The closing curly brace specifies the end of the code for the main function.

  4. Declaration Part:The declaration part declares the entire local variables that are used in executable part. Local variable scope is limited to that function where the local variables are declared. The initializations of variables can also be done in this section. The initialization means providing initial value to the variables.
  5. Executable Part:This part contains the statements following the declaration of the variables. This part contains a set of statements or a single statement.
  6. Function Call:From the main() a user defined function can be invoked by the user as per need/application.
  7. User-defined Function:The functions defined by the user are called user-defined functions. These functions are defined outside the main() function.
  8. Body of the Function: The statements enclosed within the body of the function (between opening and closing brace) are called body of the function.
  9. Comments:Comments are not necessary in a program. However, to understand the flow of programs a programmer can insert comments in the program. Comments are to be inserted by the programmer. It is useful for documentation. The clarity of the program can be followed if it is properly documented.

    Comments are statements that give us information about the program which are to be placed between the delimiters /* and */. The programmers in the programs for enhancing the lucidity frequently use comments. The compiler does not execute comments. Thus, we can say that comments are not a part of executable programs.

    A user can frequently use any number of comments that can be placed anywhere in a program. Please note that comment statements can be nested. The user should select the OPTION MENU of the editor and select the COMPILER-SOURCE - NESTED COMMENTS ON/OFF. The comments can be inserted with single statement or in nested statements.

    Example:

    /* This is single comment */

    /* This is an example of /* nested comments */*/

    /* This is an example of

    of comments in

    multiple lines */ /* It can be nested */

1.9   PROGRAMMING RULES

A programmer while writing a program should follow the following rules:

  1. Every program should have main() function.
  2. C statements should be terminated by a semi-colon. At some places, a comma operator is permitted. If only a semi-colon is placed it is treated as a statement. For example:

    while(condition)

    ;

    The above statement generates infinite loop. Without semi-colon the loop will not execute.

  3. An unessential semi-colon if placed by the programmer is treated as an empty statement.
  4. All statements should be written in lowercase letters. Generally, uppercase letters are used only for symbolic constants.
  5. Blank spaces may be inserted between the words. This leads to improvement in the readability of the statements. However, this is not applicable while declaring a variable, keyword, constant and function.
  6. It is not necessary to fix the position of statement in the program; i.e. a programmer can write the statement anywhere between the two braces following the declaration part. The user can also write one or more statements in one line separating them with a semi-colon (;). Hence, it is often called a free-form language. The following statements are valid:

    a=b+c;

    d=b*c;

    or

    a=b+c; d=b*c;

  7. The opening and closing braces should be balanced, i.e. if opening braces are four; closing braces should also be four.
1.10   EXECUTING THE C PROGRAM

A C program must go through various phases such as creating a program with editor, execution of preprocessor program, compilation, linking, loading and executing the program. The following steps are essential in C when a program is to be executed in MS-DOS mode:

  1. Creation of a Program:The program should be written in C editor. The file name does not necessarily include extension ‘.C’. The default extension is ‘.C’. The user can also specify his/her own extension. The C program includes preprocessor directives.
  2. Execution of a Preprocessor Program:After writing a program with C editor the programmer has to compile the program with the command (Alt-C). The preprocessor program executes first automatically before the compilation of the program. A programmer can include other files in the current file. Inclusion of other files is done initially in the preprocessor section.
  3. Compilation and Linking of a Program: The source program contains statements that are to be translated into object codes. These object codes are suitable for execution by the computer. If a program contains errors the programmer should correct them. If there is no error in the program, compilation proceeds and translated program is stored in another file with the same file name with extension ‘.obj’. This object file is stored on the secondary storage device such as a disc.

    Linking is also an essential process. It puts together all other program files and functions that are required by the program. For example, if the programmer is using pow() function, then the object code of this function should be brought from math.h library of the system and linked to the main() program. After linking, the program is stored on the disc.

  4. Executing the Program:After the compilation the executable object code will be loaded in the computer’s main memory and the program is executed. The loader performs this function. All the above steps/phases of C program can be performed using menu options of the editor.

As shown in Figure 1.12, pre-processor directories/program is executed before compilation of the main program. The compiler checks the program and if any syntax error is found, the same is displayed. The user is again forced to go to edit window. After removing an error, the compiler compiles the program. Here, at this stage object code is generated. During the program execution, if user makes mistakes in inputting data, the result would not be appropriate. Therefore, the user again has to enter the data. The output is generated when a program is error free.

Figure 1.12   Flow chart of a program in C

Editing, compiling and executing a program file with an editor (Figure 1.13):

Figure 1.13  Window to Turbo C editor

The programmer can use the Turbo C editor/compiler. The Turbo C editor is a software, in which the programmer can write the program in C source code. The window to Turbo C editor appears when we invoke shortcut to TC icon, which can be placed on desktop. This window is used for editing, compiling and running the program.

Its menu bar comprises eight menus: File, Edit, Run, Compile, Project, Options, Debug and Break/watch.

File: This menu is used for creating a new program file, loading an existing C file, writing the file with appropriate path, invoking DOS (OS Shell), changing directory and quitting the program.

Edit: The Edit menu provides editing options.

Run: The Run menu provides options such as Run, Program reset, Go to cursor, Trace into, Step over and User screen.

On pressing Alt+F keys, one can go to the File menu and select either New for creating a new file or in case file is already existing then use Load option and load the file by giving the appropriate path. Extension of the file with .c is automatically provided by the editor. The programmer can put extension .c or by default .c is provided by the editor. The programmer can now write a program with C syntax.

It is better to create and save programs in a separate folder/subdirectory in the home directory of the disk. The folder/subdirectory is the working directory. This is due to the association of the program file with several files created during compiling and running. Files created are your own files (source code file and data files) and besides, some other files created are after compilation and running the program.

For example if C:\Turboc2 is home directory, a subdirectory can be created with the Command prompt. Assume that the created subdirectory is Vishal, then working directory path would be C:\Turboc2\Vishal. So, create and save all programs in the working directory Vishal (Figure 1.14).

Figure 1.14  Opening a new file

After editing the program file, the same should be saved either with F2 key or Alt+F & Save from File menu and compiled from compile menu. Now programmer can use the keys Alt+C in the editor as shown below (Figure 1.15).

Figure 1.15  Compilation of program

On compilation, the same program is to be run with Alt+R keys. The screen appears as shown below. Of course, this step is adapted when there are no errors after compilation. After running the program, answer appears on the other screen. The programmer can try a simple program as cited below in the window.Executable file is created after running the program file. The .exe file created can be observed (Figure 1.16).

Figure 1.16  Running a program

It is expected to edit, compile and run a program given in the above snapshot by the user in the C editor.

1.11  STANDARD DIRECTORIES

The turbo-C has three standard directories; they are include, sys and lib. The Sys is the sub-directory of include. The include directory contains all the header files and lib contains all the library files. Before executing the program the path setting should be done. In turbo-c edit, select Option menu Directories option. Here, set the path of include, library and turbo-c-directories.

1.12   THE FIRST C PROGRAM

  1.1  Write a program to display message “Hello! C Programmers”.

void main()

{

printf(“Hello! C Programmers”);

}

OUTPUT:

Hello! C Programme

Explanation:

This program displays the message ‘Hello! C Programmers’ using the printf() statement. Follow the following steps to execute the program through Turbo-c editor.

After typing a program by pressing F2, a program can be saved. If you are saving for the first time, a name will be asked. Type the file and the extension (.c) will automatically be added.

By pressing ALT+C you can reach the compile option. Also by pressing F9, you can compile the program. To execute the program you can press CTRL + F9. To see the output of the program, press ALT+F5. User can make exe file by pressing F9 key twice.

  1.2  Write a program to know about the use of comments (how to use comments?).

void main()

{

clrscr(); /* clears the screen */

printf(“\This program explains comments”);

/* How to use comment? */

}

OUTPUT:

This program explains comments

Explanation:

In the above program, we can observe how comments are inserted in a program. The comments are not an executable part. It is only useful for the programmer to understand the flow of a program. This program prints the message as shown in the output. The function clrscr() clears the screen, defined in header file <conio.h>. Although the file is not included, some compilers allow execution and some will flag an error message.

  1.3   Write a program to return the value from main().

main()

{

return 0;

}

Explanation:

The above program produces no output. The main() should return a value of either 0 or 1.Some operating systems check the return value of main(). If main() returns 0, i.e. program executed successfully; else for other value OS assumes the opposite. If user fails to put the return statement, the compiler would not complain.

1.13  ADVANTAGES OF C
  1. It contains a powerful data definition. The data type supported are characters, alphanumeric, integers, long integer, floats and double. It also supports string manipulation in the form of character array.
  2. C supports a powerful set of operators.
  3. It also supports powerful graphics programming and directly operates with hardware. Execution of program is faster.
  4. An assembly code is also inserted into C programs.
  5. C programs are highly portable on any type of OS platforms.
  6. System programs such as compilers, operating systems can be developed in C. For example, the popular operating system UNIX is developed in C.
  7. The C language has 32 keywords and about 145 library functions and near about 30 header files.
  8. C works closely with machines and matches assembly language in many ways.
1.14   HEADER FILES

stdio.h: Standard input and output files. All formatted and unformatted functions include file operation functions defined in this file. The most useful formatted printf() and scanf() are defined in this file. This file must be included at the top of the program. Most useful functions from this header files are printf(), scanf(), getchar(), gets(), putc() and putchar().

conio.h: Console input and output. This file contains input and output functions along with a few graphic-supporting functions. The getch(), getche() and clrscr() functions are defined in this file.

math.h: This file contains all mathematical and other useful functions. The commonly useful functions from this files are floor(), abs(), ceil(), pow(), sin(), cos() and tan(). The list of commonly used header files are given in Table 1.2

Table 1.2  Commonly useful header files

There are different ways of representing the logical steps for finding a solution of a given problem. They are as follows:

  1. Algorithm
  2. Flowchart
  3. Pseudo-code

In the algorithm, a description of the steps for solving a given problem is provided. Here, stress is given on the text. Flowchart represents the solution of a given problem graphically. Pictorial representation of the logical steps is a flowchart. Another way to express the solution of a given problem is by means of a pseudo-code.

1.15   ALGORITHM

Algorithm is a very popular technique used to obtain a solution for a given problem. The algorithm is defined as ‘the finite set of steps, which provide a chain of actions for solving a definite nature of problem’. Each step in the algorithm should be well defined. This step will enable the reader to translate each step into a program. Gradual procedure for solving a problem is illustrated in this section.

An algorithm is a well-organized, pre-arranged and defined textual computational module that receives some value or set of values as input and provides a single value or a set of values as output. These well-defined computational steps are arranged in a sequence, which processes the given input into an output. Writing precise description of the algorithm using an easy language is most essential for understanding the algorithm. An algorithm is said to be accurate and truthful only when it provides the exact required output. Lengthy procedure is sub-divided into small parts and thus steps are made easy to solve a given problem. Every step is known as an instruction.

In our daily life, we come across numerous algorithms for solving problems. We perform several routine tasks, for example riding a bike, lifting a phone, making a telephone call, switching on a television set and so on.

For example, to establish a telephonic communication between two subscribers, following steps are to be followed:

  1. Dial a phone number
  2. Phone rings at the called party
  3. Caller waits for the response
  4. Called party picks up the phone
  5. Conversation begins between them
  6. After the conversation, both disconnect the call

Another real life example is to access Internet through Internet service provider with dial up facility. To log on to the Internet, the following steps are to be followed:

  1. Choose the Internet service provider for accessing the Internet.
  2. Obtain from service provider a dial up number.
  3. Acquire IP address of the service provider.
  4. Acquire login ID and password.
  5. Run the Internet browsing software.

When one writes an algorithm, it is essential to know how to analyse the algorithm. Analysing algorithm refers to calculating or guessing resources needed for an algorithm. Resources mean computer memory, processing time, logic gates. In all the above factors, time is the most important factor because the program developed should be faster in processing. The analysis can also be made by reading the algorithm for logical accuracy, tracing the algorithm, implementing it, and checking with some data and with mathematical techniques to confirm its accuracy.

Algorithms can also be expressed in a simple method. It will help the user to put into operation easily. However, this approach has a few drawbacks. It requires more space and time. It is very essential to consider the factors such as time and space of an algorithm. With minimum resources of system such as CPU’s time and memory, an efficient algorithm must be developed.

Practically, it is not possible to do a simple analysis of an algorithm to conclude the execution time of an algorithm. The execution time is dependent upon the machine and the way of implementation. The timing analysis depends upon the input required. To accurately carry out the time analysis, it is also very essential to know the exact directives executed by the hardware and the execution time passed for each statement.

  1.4  Write a program to swap two numbers using a third variable.

Algorithm for swapping two numbers:

STEP 1: Start.

STEP 2: Declare variables a, b, & c.

STEP 3: Read values of a & b.

STEP 4: Copy value of a to c; b to a; & c to b.

STEP 5: Print swapped values of a & b.

STEP 6: Exit.

Program:

void main()

{

int a,b,c;

clrscr();

printf(“\nEnter two numbers for A & B:”);

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

c=a;

a=b;

b=c; printf(“\nAfter swaping the values are:A=%d & B=%d.”,a,b);

getch();

}

Hint:Copy value of a in third variable c, value of b in a, and value of c in b.

Explanation:

In the above cited program, first two variables a, b & c are declared. The program invokes two values of a & b from user. The user assigns values to the variables a & b.

Now copy the value of a in third variable c, value of b in a, and value of c in b.

Here, when we assign the value of a to c (c=a), the value of a is copied in variable c. When we assign (a = b), the value of b is copied in variable a and the previous value is replaced. Now, b holds the value of variable c in statement (b = c).

The printf( ) statement prints the values of a & b.

  1.5  Write a program to swap two numbers without using a third variable.

Algorithm:

STEP 1: Start.

STEP 2: Declare two variables a & b.

STEP 3: Addition of a & b and place result in a.

STEP 4: Subtraction of a & b and place result in b.

STEP 5: Subtraction of a & b and place result in a.

STEP 6: Print values of a & b.

STEP 7: End.

Program:

void main()

{

int a=4,b=6;

clrscr();

a=a+b;

b=a-b;

a=a-b;

printf(“\nthe value of a=%d & b=%d”,a,b);

getch();

}

OUTPUT:

The value of a=6 & b=4

Explanation:

In the above cited program, first two variables a & b are declared and initialized.

Values of a & b are added in the statement a = a + b. In the next statement, b is subtracted from a and result is stored in b. Finally, the value of a is obtained by subtracting b from a.

The printf( ) statement prints the values of a & b.

1.15.1  Program Design

When you have thoroughly studied the program and examined the requirement of the program, the next step is to design the program. To make the programs simple, divide the program into smaller modules. This makes thinking process easy and you can separately apply logic on each portion. After dividing the program, according to priority and importance write the code.

Coding Programs: Coding a program is the second step. Once you have understood the program, now you can implement through the code. If a program is short, start coding from the beginning to top in a sequence. Identify the different variables and selection or control structures required. Also write comments so that you can follow them in future. While coding, appropriate messages for user’s direction should be prompted.

Testing Programs: After completing the coding of a program, the next step is to test the program. Confirm that the required source files and data files are at the specified location in the system.

1.16   CLASSIFICATION OF ALGORITHMS

The classification of algorithm is based on repetitive steps and on control transfer from one statement to another. Figure 1.17   shows the classification of Algorithms.

Figure 1.17  Classifications of algorithms

On the basis of repetitive steps, an algorithm can further be classified into two types.

  1. Direct Algorithm: In this type of algorithm, the number of iterations is known in advance.For example, for displaying numerical numbers from 1 to 10, the loop variable should be initialized from 1 to 10. The statement would be as follows:

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

    In the above statement, it is predicted that the loop will iterate 10 times.

  2. Indirect Algorithm: In this type of algorithm, repetitively steps are executed. Exactly how many repetitions are to be made is unknown.

    For example, the repetitive steps are as follows:

    • To find the first five Armstrong numbers from 1 to n, where n is the fifth Armstrong number.
    • To find the first three palindrome numbers.

Based on the control transfer, the algorithms are categorized in the following three types.

  1. Deterministic: Deterministic algorithm is based on either to follow a ‘yes’ path or ‘no’ path based on the condition. In this type of algorithm when control comes across a decision logic, two paths ‘yes and ‘no’ are shown. Program control follows one of the routes depending upon the condition.

    Example:

    Testing whether a number is even or odd. Testing whether a number is positive or negative.

  2. Non-deterministic:In this type of algorithm to reach to the solution, we have one of the multiple paths.

    Example:

    To find a day of a week.

  3. Random algorithm:After executing a few steps, the control of the program transfers to another step randomly, which is known as a random algorithm.

    Example:

    A random search

    Another kind of an algorithm is the infinite algorithm.

    Infinite algorithms:This algorithm is based on better estimates of the results. The number of steps required would not be known in advance. The process will be continued until the best results emerged. For final convergence more iterations would be required.

    Example:

    To find shortest paths from a given source to all destinations in the network.

1.17   FLOWCHARTS

A flowchart is a visual representation of the sequence of steps for solving a problem. It enlightens what comes first, second, third, and so on. A completed flowchart enables you to organize your problem into a plan of actions. Even for designing a product a designer many times has to draw a flowchart. It is a working map of the final product. This is an easy way to solve the complex designing problems. The reader follows the process quickly from the flowchart instead of going through the text.

A flowchart is an alternative technique for solving a problem. Instead of descriptive steps, we use pictorial representation for every step. It shows a sequence of operations. A flowchart is a set of symbols, which indicates various operations in the program. For every process, there is a corresponding symbol in the flowchart. Once an algorithm is written, its pictorial representation can be done using flowchart symbols. In other words, a pictorial representation of a textual algorithm is done using a flowchart.

We give below some commonly used symbols in flowcharts.

Start and end: The start and end symbols indicate both the beginning and the end of the flowchart. This symbol looks like a flat oval or is egg shaped. Figure 1.18 shows the symbol of Start/stop. Only one flow line is combined with this kind of symbol. We write START, STOP or END in the symbols of this kind. Usually this symbol is used twice in a flowchart, that is, at the beginning and at the end.

Figure 1.18  Start/stop symbol

Decision or test symbol: The decision symbol is diamond shaped. This symbol is used to take one of the decisions. Depending on the condition the decision block selects one of the alternatives. While solving a problem, one can take a single, two or multiple alternatives depending upon the situation. All these alternatives are illustrated in this section. A decision symbol with a single alternative is shown in Figure 1.18. In case the condition is satisfied /TRUE a set of statement(s) will be executed otherwise for false the control transfers to exit.

Single alternative decision: Here more than one flow line can be used depending upon the condition. It is usually in the form of a ‘yes’ or ‘no’ question, with branching flow line depending upon the answer. With a single alternative, the flow diagram will be as per Figure 1.19.

Figure 1.19  Single alternative decision

Two alternative decisions: In Figure 1.20 two alternative paths have been shown. On satisfying the condition statement(s) pertaining to 1 action will be executed, otherwise the other statement(s) for action 2 will be executed.

Figure 1.20  Two alternative decisions

Multiple alternative decisions: In Figure 1.21 multiple decision blocks are shown. Every decision block has two branches. In case the condition is satisfied, execution of statements of appropriate blocks take place, otherwise next condition will be verified. If condition 1 is satisfied then block 1 statements are executed. In the same way, other decision blocks are executed.

Figure 1.21  Multiple alternative decisions

Connector symbol: A connector symbol has to be shown in the form of a circle. It is used to establish the connection, whenever it is impossible to directly join two parts in a flowchart. Quite often, two parts of the flowcharts may be on two separate pages. In such a case, connector can be used for joining the two parts. Only one flow line is shown with the symbol. Only connector names are written inside the symbol, that is, alphabets or numbers. Figure 1.22 shows the connector symbol.

Figure 1.22  Connector symbol

Process symbol: The symbol of process block should be shown by a rectangle. It is usually used for data handling, and values are assigned to the variables in this symbol. Figure 1.23 shows the process symbol. The operations mentioned within the rectangular block will be executed when this kind of block is entered in the flowchart. Sometimes an arrow can be used to assign the value of a variable to another. The value indicated at its head is replaced by the tail values. There are two flow lines connected with the process symbol. One line is incoming and the other line goes out.

Figure 1.23  Process symbol

Loop symbol: This symbol looks like a hexagon. This symbol is used for implementation of for loops only. Four flow lines are associated with this symbol. Two lines are used to indicate the sequence of the program and remaining two are used to show the looping area, that is, from the beginning to the end.

For the sake of understanding, Figure 1.24. illustrates the working of for loop. The variable J is initialized to 0 and it is to be incremented by a step of 2 until it reaches the final value 10. For every increased value of J, body of the loop is executed. This process will be continued until the value of J reaches 10. Here the next block is shown for the repetitive operation.

Figure 1.24  For loop

Input/output symbol: Input/output symbol looks like a parallelogram, as shown in Figure 1.25. The input/output symbol is used to input and output the data. When the data is provided to the program for processing, then this symbol is used. There are two flow lines connected with the input/output symbol. One line comes to this symbol and the other line goes from this symbol.

Figure 1.25   Input/output symbol

Figure 1.26  Delay symbol

As per Figure 1.25 compiler reads the values of X, Y and in the second figure the result is displayed on the monitor or the printer.

Delay symbol: Symbol of delay is just like ‘AND’ gate. It is used for adding delay to the process. It is associated with two lines. One is incoming and the other is outgoing, as shown in Figure 1.26.

Figure 1.27  Manual input symbol

Manual input symbol: This is used for assigning the variable values through the keyboard, whereas in data symbol the values are assigned directly without manual intervention. Figure 1.27 represents the symbol of manual input.

In addition, the following symbols (Figure 1.28) can be used in the flowchart and they are parts of flowcharts.

Figure 1.28  Some other symbols used in the flowchart

1.18   PSEUDOCODE

In pseudocodes english-like words are used to represent the various logical steps. It is a prefix representation. Here solution of each step is described logically. The pseudocode is just the raw idea about the problem. By using this tip, one can try to solve the problem. The meaning of pseudocode is ‘false code.’ The syntax rule of any programming language cannot be applied to pseudocode.

Example(a): Assume a and b are two numbers and find the larger out of them. In such a case, comparison is made between them.

This can be represented as follows.

Algorithm

Pseudocode

Input a and b

get numbers a & b

Is a>b.

Compare a & b

If yes a is larger than b.

if a is large max=a

If no b is larger than a.

if b is large max=b

Print the larger number.

Larger number is max

Few skilled programmers prefer to write pseudocode for drawing the flowchart. This is because using pseudocode is analogous to writing the final code in the programming language. Few programmers prefer to write the steps in algorithm. Few programmers favour flowchart to represent the logical flow because with visualization things are clear for writing program statements. For beginners a flowchart is a straightforward tool for writing a program.

Example (b): The example (b) illustrates how the pseudo code is used to draw the flowchart for squaring a number.

  1. Accept number
  2. Calculate square of the number
  3. Display number

All the steps of the program are written down in steps. Some programs follow pseudocode to draw flowcharts. Using pseudocode, final program can be written. Majority of programs have common tasks such as input, processing and output. These are fundamental tasks of any program.Using pseudocode a flowchart can be drawn as per the following steps.

For the statement, that is, ‘Accept number’ the flowchart symbol is as per Figure 1.29.

Figure 1.29  Input symbol

The statements including arithmetic operations are examples of processing statements. The representation of second statement ‘Calculate square of the number’ can be represented as in Figure 1.30.

Figure 1.30  Processing symbol

The output statement, that is, ‘Display number’ can be represented as per Figure 1.31.

Figure 1.31  Output symbol

In addition,the flowchart has two more symbols to indicate the beginning and the end of the program as per Figure 1.32 The standard terminator symbol is racetrack.

Figure 1.32  Pseudocode and flowchart of a program

SUMMARY

This chapter presents the evolution and basics of C. C is a structural language. It has many similarities like other structural languages such as Pascal and Fortran. C is also called a system-programming language. The ANSI C standard was adopted in December 1989 and the first copy of C language was introduced in the market in 1990.

The reader is exposed to an assembler that translates the symbolic code of programs of an assembly language into machine language instructions. Similarly, compilers are the translators, which translate all the instructions of the program into machine codes and can be used again and again. An interpreter comes in the group of translators. It helps the user to execute the source program with few differences as compared to compilers.

In this chapter, an overview of algorithms was given. An algorithm is defined as ‘the finite set of the steps, which provide a chain of actions for solving a definite nature of problem’. Algorithms are of two types, direct algorithm and indirect algorithm.

EXERCISES

I  True or false:

  1. C Language is developed by Ken Thompson.
  2. C Language was developed in the year 1972.
  3. C Language is closely associated with Linux.
  4. C Programs are not portable.
  5. The ANSI C standard was developed in 1989.
  6. C Programs are translated into object code by a compiler.
  7. An interpreter reads one line at a time.
  8. Every C Program should have the main() function.
  9. In C, all the statements should be written in small letters only.
  10. After compilation, the object file of a source program is created.
  11. It is not possible to crate .exe file in C.
  12. Compiler executes a program even if the program contains warning messages.
  13. In Turbo-C editor Alt+C is used to execute the program.
  14. A comment can be split in more than one line.
  15. The source code for the UNIX operating system is in C.
  16. The assembly language program is in alphanumeric symbols.
  17. Linking software is used to bring together the source program and library code.
  18. Assembler translates low-level language to machine code.
  19. The compiler reads firstly entire program and generates the object code.
  20. C does not have automatic conversion of compatible variable.
  21. Every processor has its own assembly language.
  22. Assembly language program is portable.

II  Select the appropriate option from the multiple choices given below:

  1. The C language has been developed by
    1. Patrick Naughton
    2. Dennis Ritche
    3. Ken Thompson
    4. Martin Richards
  2. The C programming is a
    1. high-level language
    2. low-level language
    3. middle-level language
    4. assembly language
  3. The C programs are converted into machine language using
    1. an assembler
    2. a compiler
    3. an interpreter
    4. an operating system
  4. The C language was developed in the year
    1. 1972
    2. 1980
    3. 1975
    4. 1971
  5. The C language has been developed at
    1. AT & T Bell Labs, USA
    2. IBM, USA
    3. Borland International, USA
    4. Sun Microsystems
  6. The C language is an offspring of the
    1. ‘BPCL’ language
    2. ‘ALGOL’ language
    3. ‘Basic’ language
    4. None of the above
  7. The C program should be written only in
    1. lower case
    2. upper case
    3. title case
    4. sentence case
  8. The role of a compiler is to translate source program statements to
    1. object codes
    2. octal codes
    3. decimal codes
    4. None of the above
  9. The extension for C program files by default is
    1. .c
    2. .d
    3. .obj
    4. .exe
  10. The C can be used with
    1. only UNIX operating system
    2. only LINUX operating system
    3. only MS-DOS operating system
    4. All the above
  11. The C language is closely associated with
    1. MS-DOS
    2. LINUX
    3. UNIX
    4. MS-windows
  12. The C programs are highly portable means
    1. same programs execute on different computers
    2. program executes only on the same computer
    3. program needs a lot of modification to run
    4. None of the above
  13. Each instruction in C program is terminated by
    1. dot (.)
    2. comma (,)
    3. semi-colon (;)
    4. curly brace ({})
  14. Which one of the following statements is incorrect?
    1. a compiler compiles the source program
    2. an assembler takes as assembly program as input
    3. interpreter executes the complete source code just like compiler
    4. None of the above
  15. ANSI committee was set up in
    1. 1983
    2. 1985
    3. 1990
    4. 1976
  16. The program which translates high-level program into its equivalent machine language program is called
    1. a translator
    2. a language processor
    3. a converter
    4. None of the above
  17. C is an offspring of the
    1. basic combined programming language
    2. basic computer programming language
    3. basic programming language
    4. None of the above
  18. An interpreter reads the source code of a program
    1. one line at a time
    2. two lines at a time
    3. complete program in one stroke
    4. None of the above
  19. A compiler reads the source code of a program
    1. complete program in one stroke
    2. one line at a time
    3. two lines at a time
    4. None of the above
  20. C keywords are reserved words by
    1. a compiler
    2. an interpreter
    3. a header file
    4. Both (a) and (b)
  21. The declaration of C variable can be done
    1. anywhere in the program
    2. in declaration part
    3. in executable part
    4. at the end of program
  22. Variables must begin with character without spaces but it permits
    1. an underscore symbol ( _ )
    2. an asterisk symbol ( * )
    3. an ampersand symbol ( & )
    4. None of the above
  23. In C, the statements following main() are enclosed within
    1. {}
    2. ()
    3. <>
    4. None of the above
  24. CPU generates
    1. timing signals
    2. control signals
    3. analog signals
    4. both a & b
  25. The structural languages are
    1. C
    2. Pascal
    3. Fortan
    4. All the above
  26. Data type-less languages are
    1. C
    2. BCPL
    3. B
    4. Both c & b
  27. Input device/s of a computer
    1. Printer
    2. Speaker
    3. Monitor
    4. None of the above
  28. Output device/s of the computer
    1. Monitor
    2. Speaker
    3. Printer
    4. All the above
  29. CPU comprises of the
    1. Arithmetic and Logical unit
    2. Registers
    3. Control Signals
    4. All the above
  30. Advantages of high level language are
    1. fast Program Development
    2. testing and Debugging of program is easier
    3. portable
    4. All the above

III   Answer the following questions:

  1. Why to use a computer? Brief its benefits.
  2. Illustrate the functions of various parts of a computer.
  3. Why is the C language called a middle-level language?
  4. What are the functions of an interpreter and a compiler?
  5. What is the difference between an interpreter and a compiler?
  6. What is meant by compilation? Explain in detail.
  7. Write the rules for writing a C program.
  8. Elaborate different sections of a C program.
  9. Explain the functions of a linker.
  10. What is the role of curly braces ({}) in a C program?
  11. What is ANSI C standard?
  12. What are the user-defined functions?
  13. Explain the assembly-language and machine-language concepts.
  14. Write details on header files stdio.h and conio.h.
  15. Which are the standard directories? Where are .h files kept?
  16. Write any three advantages of a C language.
  17. What is an algorithm? Explain in short.
  18. Mention and explain two types of algorithms.
  19. Show the flowchart for finding cube of a number.
  20. Write the pseudo code for finding largest out of three numbers.
ANSWERS

I   True or false:

Q.

Ans.

1.

F

2.

T

3.

F

4.

F

5.

T

6.

T

7.

T

8.

T

9.

T

10.

T

11.

F

12.

T

13.

F

14.

T

15.

T

16.

T

17.

T

18.

T

19.

T

20.

T

21.

T

22.

F

II   Select the appropriate option from the multiple choices given below:

Q.

Ans.

1.

b

2.

c

3.

b

4.

a

5.

a

6.

a

7.

a

8.

a

9.

a

10.

d

11.

c

12.

a

13.

c

14.

c

15.

a

16.

a

17.

a

18.

a

19.

a

20.

a

21.

b

22.

a

23.

a

24.

d

25.

d

26.

d

27.

d

28.

d

29.

d

30.

d