# Fundamentals of C Programming

CS 102 - Introduction to Programming

Department of Computer Science and Engineering Faculty of Engineering University of Moratuwa Sri Lanka

By: Dilum Bandara, Dr. Sanath Jayasena, Samantha Senaratna

© Department of Computer Science and Engineering Faculty of Engineering University of Moratuwa Sri Lanka ∗∗∗

Table of Content
Chapter 1 – Introduction
1.1 Introduction to Programming 1.2 Program Development 1.2.1 Define the Problem 1.2.2 Outline the Solution 1.2.3 Develop the Algorithm 1.2.4 Test the Algorithm for Correctness 1.2.5 Code the Algorithm 1.2.6 Compile 1.2.7 Run the Program 1.2.8 Test, Document and Maintain the Program 1.3 Running a Program 1.4 Programming Languages 1.5 Overview of C 1.6 Steps in Developing a Program in C 1 1 1 2 2 2 2 2 2 3 3 4 5 5

Chapter 2 – Introduction to C Programming
2.1 An Example C Program 2.2 Your First C Program 2.3 C Tokens 2.4 Displaying Text 2.4.1 Escape Codes 2.5 Data Types 2.5.1 Primitive Data Types 2.5.2 Modifiers 2.6 Variables 2.6.1 Declaring Variables 2.6.2 Constants 2.7 Displaying Numbers 2.8 Formatted Input 7 7 8 9 10 10 11 11 12 12 12 13 15

Chapter 3 – Operators in C
3.1 Assignment Operator 3.2 Arithmetic Operators 3.2.1 Increment and Decrement Operators 3.2.2 Precedence and Associatively of Arithmetic Operators 3.3 Relational and Logical Operators 3.3.1 Precedence of Relational and Logical Operators 3.4 Bitwise Operators 3.4.1 Shift Operators 16 17 17 18 18 18 19 21

© Department of Computer Science and Engineering

i

1 Opening a Connection to a File 9.4 Passing Variables to Functions 7.5 Conditional Operator 4.3 The do-while Loop 5.2 The while Loop 5.Chapter 4 – Conditional Control Structures 4.1.3 Function Definition 7.1.3 The if-else-if Ladder 4.6 The continue Keyword 5.1 Declaring Pointers 8.4 Nesting of Loops 5.1 A Function 7.1.2 Function Prototypes 7.5 The break Keyword 5.4 Writing Data to a File 46 46 47 47 48 ii © Department of Computer Science and Engineering .4.1 The if Statement 4.1 The File Protocol 9.4 Nesting Conditions 4.2 Text Strings and Pointers 8.1 Initialising an Array 6.2 The if-else Structure 4.1 The for loop 5.3 Pointers and Arrays 43 44 45 Chapter 9 – Handling Files 9.2 Closing the Connection to a File 9.1.7 The exit Function 30 31 32 33 34 35 35 Chapter 6 – Arrays 6.1 The Scope of a Variable 7.2 Default Parameters 38 39 39 41 41 41 Chapter 8 – Pointers 8.6 The switch Construct 22 24 24 26 26 27 Chapter 5 – Control Structures 5.2 Multidimensional Arrays 36 37 Chapter 7 – Functions 7.3 Reading Data from a File 9.4.

Annex A – Lab 2 & 3 Annex B – Lab 4 Annex C – Lab 5 Annex D – Lab 6 Annex E – Lab 7 Annex F – Lab 9 Annex G – Lab 10 Annex H – Library Functions 50 55 56 60 61 62 63 64 © Department of Computer Science and Engineering iii .

5 – The printf conversion specifies Table 3.1 – The C language keywords Table 2.5 – Bitwise operators Table 3.4 – Basic C data types and modifiers (on a 32-bit machine) Table 2.2 – Escape codes Table 2.1 – Arithmetic operators Table 3.4 – Precedence of relational and logical operators Table 3.2 – Precedence of arithmetic operators Table 3.List of Figures Figure 2.3 – Relational and logical operators Table 3.3 – Basic C data types (on a 32-bit machine) Table 2.1 – File access modes 8 10 11 11 13 16 18 18 19 19 20 21 46 iv © Department of Computer Science and Engineering .7 – Precedence of C operators Table 9.6 – Precedence of bitwise operators Table 3.1 – C Tokens 9 List of Tables Table 2.

8. Programming is rather like a recipe. document and maintain the program Developing a program involves a set of steps: Most of these steps are common to any problem solving task. weeks. several years or even several decades. A program is simply a set of instructions that tells a computer how to perform a particular task. The problem can be divided into three components: Programmers should clearly understand “what are the inputs to the program”. 2. Program development (software development) may take several hours. © Department of Computer Science and Engineering 1 . Consider an example where a computer program is to be written to calculate and display the circumference and area of a circle when the radious . Programs are developed using programming languages. 1.2. Systems software includes operating systems and various device drivers. A person who writes a program using a programming language is called a programmer. days. a set of instructions that tells a cook how to make a particular dish. While in use the system needs to be maintained.2 1. • • • Inputs – the radius (r) Outputs – circumference (c) and area (a) Processing § 1 c = 2pr. Application software are used to perform real-world tasks and solve specific problems.e. It describes the ingredients (the data) and the sequence of steps (the process) on how to mix those ingredients. 4. After development. 3. Computer programming is the art of developing computer programs. customers will make use of the system. 1.Introduction 1. algorithm) into set of instructions understood by a computer. Therefore software development is not a onetime task. 5. months or years. His/her job is to convert a solution to a problem (i. “what is expected as output(s)” and “how to process inputs to generate necessary outputs”. The programmer should also test the program to see whether it is working properly and corrective actions should be taken if not. 6.1 . The steps are discussed in the following. Program Development Define the problem Outline the solution Develop an algorithm 1 Test the algorithm for correctness Code the algorithm using a suitable programming language Compile and correction of compile errors Run the program on the computer Test. A programming language provides a set of rules to develop a program.1 • • • Define the Problem Inputs – what do you have? Outputs – what do you want to have? Processing – how do you go from inputs to outputs? First of all the problem should be clearly defined. 7. The maintenance phase will continue for several months.1 Introduction to Programming Software refers to a program or set of instructions that instructs a computer to perform some task. Software can be divided into two major categories called system software and application software. it is a lifecycle where some of the above steps are reformed again and again. a = pr2 An algorithm is a sequence actions that is used to solve a problem.

A suitable algorithm for our example would be: Start Input r Calculate circumference c = 2 * PI* r Calculate area a = PI* r^2 Output c & a End In here PI is a constant that represents the value of p. and the order in which they are to be carried out to solve a problem. The objective is to identify major logic errors early. missing punctuations . Runtime errors occur while executing the program and those are mostly due to incorrect inputs.2.2.4 Test the Algorithm for Correctness The programmer must make sure that the algorithm is correct. symbols. Pseudocode (a structured form of the English language) can be used to express an algorithm. Test data should be applied to each step. When the written program does not adhere to the programming language rules those are called syntax errors. 1. circumference (c) Calculation – c = 2pr Variables – radius (r). to check whether the algorithm actually does what it is supposed to. etc. In order to calculate the circumference: In order to calculate the area: The next step is to develop an algorithm that will produce the desired result(s). so that they may be easily corrected.1.5 Code the Algorithm After all the design considerations have been met and when the algorithm is finalised code it using a suitable programming language. These errors occur mostly due to miss typed characters. 2 Will be introduced later.2.6 Compile The next step is to compile (section 1. selection.3 Outline the Solution the major steps required to solve the problem any subtasks the major variables and data structures the major control structures (e. sequence. An algorithm is a segment of precise steps that describes exactly the tasks to be performed. While the program is running runtime errors and sometimes logic errors can be identified. 2 © Department of Computer Science and Engineering . 1. Our simple example can be quite easily check by submitting some values for radius (r) and walking through the algorithm to see whether the resulting output is correct for each input. area (a) Calculation – a = pr2 Develop the Algorithm The programmer should define: Consider the above mentioned example . repetition loops)2 in the algorithm the underlined logic Variables – radius (r). If there are no syntax errors the program gets compiled and it produces an executable program. While compiling syntax errors can be identified.3) the program.2.g.2. 1.2 • • • • • • • • • 1.2. 1.7 Run the Program Executable program generated after compiling can then be executed.

it should be executed by the computer. what is understood by the hardware).8 Test. During this phase logic errors can be found. Programs written in programming languages such as FORTRAN.2 – Compiling and executing a program Figure 1. The saving on the compilation time is an advantage that is gain from compiling and therefore these programs run much faster.3). All the steps involved in developing the program algorithm and code should be documented for future reference. However. the interpreter converts high-level language instructions and input data to a machine readable format and executes the program. Therefore we need to convert the human readable programs into a machine language before executing. Programmers should also maintain and update the program according to new or changing requirements. into machine language programs. Document and Maintain the Program Test the running program using test data to make sure program is producing correct output(s). COBOL. This process can be slower than the process which 3 Machine language is the native language of the computer (i. C.3 Running a Program After a program is developed using a programming language. the computer understands only 1’s and 0’s (referred as the machine language3 or machine code). © Department of Computer Science and Engineering 3 . no compilation is needed again unless the source program is modified. These programs convert the high-level language program. Figure 1.2 when the executable file is available it can be executed by providing necessary input data so that it produces the desired outputs.2. This is conversion is achieved by a special set of programs calle d compilers (or interpreters). Since the source program is already compiled. Figure 1.1. Interpreters convert a source program and execute it at the same time (Figure 1.1 – Converting a human readable program into machine language Compilers translate a source program (human-readable) into an executable (machine-readable) program (Figure 1. Logic errors occur due to incorrect algorithms (although you provide correct inputs you do not get the correct outputs). Executable machine code produced by a compiler can be saved in a file (referred as the executable file) and used whenever necessary. 1.2).e. C++ and Pascal must be compiled before executing. Each time the program runs. Programmers write programmes in human readable languages called high-level languages.3 – Interpretation of a program As in Figure 1.

C# and Visual Basic can be used to develop a variety of applications. However even the Assembly language programs tend to be lengthier and tedious to write. On the other hand FORTRAN was initially developed for numerical computing.4 Programming Languages Programming languages were invented to make programming easier.compiles the source program before execution. They are much closer to natural languages. these languages are general enough to be used for a wide range of problems. 5 Running the same program on machines with different hardware configurations. Most of these 4GL support development of Graphical User Interfaces (GUIs) and responding to events such as movement of the mouse. These languages allowed programmers to ig nore the details of the hardware. They became popular because they are much easier to handle than machine language. Lisp for artificial intelligence. Programs developed in Assembly runs only on a specific type of computer. A compiler or an interpreter was used to translate the high-level code to machine code. It is general purpose if it can be applied to a wide range of situations. They consume large amount of processing power and memory and they are generally slower than the programs developed using languages belonging to other generations. C++. A language is high-level if it is independent of the underlying hardware of a computer.e. Lisp and VB Script are interpreted. All the modern languages such as Visual Basic. how to make use of registers. Perl. Programs written in languages like BASIC. etc. Programs written using machine language belongs to the first generation of programming languages. As microprocessors. Writing and understanding Assembly language programs were easier than machine language programs. instruction format. 4 © Department of Computer Science and Engineering . Languages such as C. 4 Computer organization describes. With the introduction of third generation (also referred as 3GL) high-level languages were introduced. The program need to be converted as well as executed at the same time. the internal organization of a computer. Programs written in these languages were more readable and understandable than the 3GL. C# and MatLab belong to the fourth generation (4GL). Assembly language programs were automatically translated into machine language by a program called an assembler. Each Assembly language instruction directly maps into a machine language instruction (there is a 1-to-1 mapping). COBOL. VB Script. Programming languages are designed to be both high-level and general purpose. clicking of mouse or pressing a key on the keyboard. These programs were hardly human readable. Later programs were written in a human readable version of machine code called Assembly language. Smalltalk. allocate and de allocate memory. the instruction set. a single high level language instruction maps into multiple machine language instructions). Source code of the programs written in these languages is much smaller than other generation of languages (i. Languages such as FORTRAN. C and Pascal belong to the third generation. programs developed in 4GL generally do not utilize resources optimally. However. programming languages also can be grouped into several generations and currently we are in the fourth generation. computers were programmed using machine language instructions that the hardware understood directly. Java. Further. programmers were required to have a sound knowledge about computer organization4 . 1. Some people think that fifth generation languages are likely to be close to natural languages. The programs written using those languages were portable 5 to more than one type of hardware. Java. talking to various I/O devices. therefore understanding and modifying them was a difficult task. Assembly language belongs to the second generation of programming languages. In the early days. Simula for simulation and Prolog for natural language processing (yet. There are more than two thousand programming languages and some of these languages are general purpose while others are suitable for specific classes of applications. Such languages are one of the major research areas in the filed of Artificial Intelligence.

C is also suitable for many complex engineering applications. C was used mainly in academic environments. Figure 1. The compilation of a C program is infact a three stages process. Java and C# inherit C coding style . Linux. Since C was developed along with the UNIX operating system it is strongly associated with UNIX. For many years. The syntax and coding style of C is simple and well structured. Windows and Apple Mac. If the compiler finds no errors in the source code it produces a file containing the machine code (this file referred as the executable file).1. 1. Programs written in C are efficient and fast. C is a robust language whose rich set of built-in functions and operations can be used to write any complex program. Due to this reason most of the modern languages such as C++. preprocessing. UNIX was developed at Bell Laboratories and it was written almost entirely in C. C is well suited to write both commercial applications and system software since it incorporates features of high-level languages and Assembly language. After a C source file has been created. C was introduced by Dennis Ritchie in 1972 at Bell Laboratories as a successor of the language called B (Basic Combined Programming Language – BCPL). Java and C# have branched away from C by adding object-orientation and GUI features. Today C compilers are available for a number of operating systems including all flavours of UNIX. Visual C++. that is with little or no modification and compiling. Therefore it is one of the best languages to learn the art of programming. the programmer must invoke the C compiler before the program can be executed. Most C programs are fairly portable .4 – Compilation process © Department of Computer Science and Engineering 5 . A file containing source code is called a source file (C source file s are given the extension . MS-DOS.5 Overview of C “C’ seems a strange name for a programming language but it is one of the most widely used languages in the world. C programs can be executed on different operating systems. it began to gain wide-spread interest among computer professionals. However with the release of C compilers for commercial use and increasing popularity of UNIX.c ).6 Steps in Developing a Program in C A programmer uses a text editor to create and modify files containing the C source code. compiling and linking. Various languages such as C++.

If the compiler finds any non-standard codes or conditions which are suspicious but legitimate it will notify to the programmer as warnings and it continues to compile . Preprocessor does not modify the source code stored on disk. Linking is the final step and it combines the program object code with other object codes to produce the executable file. If any linker errors are encountered the executable file will not be generated. It also strips comments and unnecessary white spaces from the source code. or object files that the programmer has created. The compiler translates the preprocessor-modified source code into object code (machine code). 6 © Department of Computer Science and Engineering . While doing so it may encounter syntax errors. A well written program should not have any compilation errors or warnings. If errors are found it will be immediately notifie d to the programmer and compiling will discontinue. It modifies the source code (in memory) according to preprocessor directives (example: #define ) embedded in the source code. Finally it saves the executable code as a file on the disk.Preprocessing is performed by a program called the preprocessor. The other object codes come from run-time libraries. every thing is done on the copy loaded into the memory. Compilation really happens then on the code produced by the preprocessor. other libraries.

Keywords are also called as reserved words. Most functions return some value and sometimes this return value indicates the success or the failure of a function. When you execute your program it should display “Hello World!” on the screen. main() is placed as the first function.e. Use your favorite text editor in Linux and type the above program.1 lists keywords supported by the C language.3 C Tokens The smallest element identified by the compiler in a source file is called a token.” does that.My First Program */ #include <stdio. } Similar to the previous program. Language specific tokens used by a programming language are called keywords. Literals can be further classified as numeric constants.out (i. Tokens can be classified as keywords. return 0. The keyword int indicates that main() function returns an integer value.h> int main() { printf("Hello World!\n"). They are defined as a part of the programming language therefore cannot be used for anything else. \$ vim HelloWorld. Table 2. character constants and string constants.out. operators. literals. in this case it returns zero (conventionally 0 is returned to indicate the success of a function).c \$ gcc HelloWorld./* Program-2.3 .My First Program */ #include <stdio./a.c). however with a slight difference. there must be a statement that indicates what this value is. Save it as HelloWorld.c (all C source files are saved with the extension . return 0. etc. Table 2. It may be a single character or a sequence of characters to form a single item.c \$ . Then your modified program should look like the following: /* Program-2.c to compiler your program. The statement “return 0.1 – The C language keywords auto double int struct break else long switch case enum register typedef char extern return union const float short unsigned continue for signed void default goto sizeof volatile do if static while 8 © Department of Computer Science and Engineering . identifiers. The keyword int is added before the function main. to execute the a. If there are no errors an executable file will be created in the same location with the default file name a. } 2.h> int main() { printf("Hello World!").2 . Use the command gcc HelloWorld. To execute the program at the prompt type . Then use the shell and go to the directory that you have saved your source file. Any user defined literals or i entifiers should not conflict with keywords or d compiler directives.out file in current directory)./a. Because function main() returns an integer value.out Hello World!\$ However you will see the prompt (\$) appearing just after the message “Hello World! ” you can avoid this by adding the new line character (\n) to the end of the message.

The C language uses several symbols such as semicolons (. .99 are examples. Figure 2. braces ([]). A sequence of characters surrounded by double quotation marks (inverted comma “”) is called a string constant. C supports large number of mathematical and logical operators such as +. One such standard is the use of underscores symbol (_) to combine two words (example: sub_total).” is a string constant. 10000 and 99. It has two parentheses which contains the string to be displayed. and parentheses (()) to group block of code as a single unit.4 */ #include <stdio. For example “4+5” is an expression containing two operands (4 and 5) and one operator (+ symbol). While defining identifiers programmers should follow some of the naming standards for better readability of the program. } If you compile this program and run it. C identifiers can be very long and so it allows descriptive names like “number_of_students” and “Total_number_of_cars_produced_per_year”. the second time printf function starts printing the second string from next position on the screen. ^. return 0. brackets ({}). % .h> int main() { printf("Hi there"). digits or underscores. quotation marks (“”). Numeric constants are an uninterrupted sequence of digits (possibly contain ing a period).. colons (:).4 given below. A statement such as “I like ice cream. Character constants represents a single character and it is surrounded by single quotation mark (‘).4 Displaying Text The printf is the most important function used to display text on the screen. apostrophes (‘). *. Operators will be discussed in chapter 3. | .Literals are factual data represented in a language.1 – C Tokens 2. Operators are used with operands to build expressions. printf("How are you?"). || .). etc. It displays two successive statements using the printf function. Consider Program-2. Numerical values such as 123. This can be modified by © Department of Computer Science and Engineering 9 . ‘\$’ and ‘4’ are examples. & .). ‘A’. /* Program-2. A valid identifier is composed of a letter followed by a sequence of letters. digits or underscore (_) symbols. && . Sometimes a C compiler may consider only the first 32 characters in an identifier. Characters such as ‘a’. Identifies are case sensitive. An identifier must begin with a letter and the rest can be letters. enclosed in quotation marks. commas (. the displayed output is: Hi thereHow are you? \$ How does this happens? The printf function first prints the string “Hi there”. /. therefore the identifier abc is different from ABC or Abc. Identifiers are also referred as names.

h> int main() { printf("Hi there\n").h> int main() { printf("Hi there "). Sri Lanka ---------------------www.5 Data Types A data type in a programming language is a set of data with values having predefined characteristics such as integers and characters. Moratuwa. return 0. Table 2.4. } Now the output is Hi there How are you?\$ By adding another \n at then end of the second string you can move the prompt (\$) to the next line. } /* Program-2. printf("\nHow are you?").adding the new line (\n) character before the start of the second string or at the end of the first string. Therefore the modified program can either be Program-2. University of Moratuwa Katubedda.lk 2.5b. /* Program-2. Note that each of these escape codes represents one character.mrt.5b */ #include <stdio.1 Escape Codes Escape codes are special characters that cannot be expressed otherwise in the source code such as new line. All of these characters or symbols are preceded by an inverted (back) slash (\). The language usually specifies the range of values for a given data 10 © Department of Computer Science and Engineering . although they cons ists of two characters. return 0. tab and single quotes. List of such escape codes are given in Table 2.2.1: Write a C program to display the following text on the screen.ac. printf("How are you?").5a or Program-2. 2 – Escape codes Escape Code \a \b \f \n \t \v \’ \” \? \\ Meaning Audible alert (bell) Back space Form feed New line Horizontal tab Vertical tab Single quote (‘) Double quote (“) Question mark (?) Backslash (\) 2. Exercise 2.5a */ #include <stdio.

These include type defined data types (using typedef keyword) and enumerated types (using enum keyword).647 -2. double precision floating point numbers (double ). 3.967.295 -2. Each of these data types requires different storage capacities and has different range of values depending on the hardware (see Table 2. structures. Storage representations and machine instructions to handle data types differ form machine to machine. 2.483. Table 2.4e-38 to 3.483.7e+308 (accuracy up to 15 digits) 3. unsigned.4e-38 to 3. unions and pointers by combining several data types together.7e-308 to 1. namely integers (int) floating point numbers (float). These can be classified as integer types. characters (char) and void (void).type.147.647 0 to 4.3).647 3.4e-4932 to 1.648 to 2.5. if they are not enough programmers can also define their own data types.4e+38 1. 4 – Basic C data types and modifiers (on a 32-bit machine) Data Type Char unsigned char signed char Int signed int unsigned int Short Short int signed short int unsigned short int Long long int unsigned long signed long Float Double long double 2.5.1 Primitive Data Types The C language supports five primitive data types.294.648 to 2.2 Modifiers Size in Bits Range of values 8 8 8 32 32 32 8 8 8 8 32 32 32 32 32 64 80 -128 to +127 0 to 255 -128 to +127 -2147483648 to +2147483647 -2147483648 to +2147483647 0 to 4294967295 -128 to +127 -128 to +127 -128 to +127 0 to 255 -2. long and short .4e+38 (accuracy up to 7 digits) 1. how the values are processed by the computer and how they are stored.7e+308 (accuracy up to 15 digits) Without value (null) Table 2. The variety of data types available allows the programmer to select the type appropriate to the needs of the application as well as the machine. floating point types and character types.147. Character (char) type is considered as an integer type and actual characters are represented based on their ASCII value.147.147.7e-308 to 1.147. The modifiers are signed . For example short int represents fairly small integer values and require hal the amount of storage as f © Department of Computer Science and Engineering 11 . Derived data types – programmers can derive data types such as arrays.648 to 2. User defined data types – based on the fundamental data types users can define their own data types. Many of these data types can be further extended as long int and long double .483.483. 2. C supports a number of data types. Primitive (or basic) data types – these are the fundamental data types supported by the language.483. C supports three classes of data types: 1.147.1e+4932 (accuracy up to 19 digits) The basic data types can be modified by adding special keywords called data type modifiers to produce new features or new types.483. 3 – Basic C data types (on a 32-bit machine) Data Type Char Int Float Double Void Size in Bits Range of values 8 32 32 64 0 -128 to +127 -2147483648 to 2147483647 3.

2.4. just after declaring it or later within the code (before accessing/evaluating its value within an expression). Multiple variables belonging to the same data type can be defined as separate set of expressions or by listing variable names one after the other (should be separated by a coma sign ( )). The syntax to declare a new variable is to first write the data type then followed by a valid variable identifier as given in the following examples: int a.141. It is a memory location that can hold a value of a certain data type. Without having to refer to a variable such a constant can be defined simply by using the #define 12 © Department of Computer Science and Engineering . Programmers refer to a variable by its name (identifier) so that it can be accessed during the course of the program. 2.6. above variables can also be defined as: int a. or int a. 2.2 Constants The value of a constant cannot be changed after an initial value is assigned to it. After declaring a variable it should be initialised with a suitable value. “total” as a floating point number. float sub_total. namely declared constants and defined constants.regular int numbers. int b. --------------a = 10. an uninitialised variable can contain any garbage value therefore the programmer must make sure all the variables are initialised before using them in any of the expressions. With the const prefix the programmer can declare constants with a specific data type exactly as it is done with variables. const float pi = 3. a = 10. The C language supports two types of constants. the modifiers can be used with all the basic data types as shown in Table 2. the programmer must first declare it specifying the data type. unsigned int index_no. “index_no” as unsigned integer (since there are no negative index numbers) and “number_of_students” as a short integer. following example s: int a. In C. Initialising a variable can be done while declaring it.b. Programmers can define their own names for constants which are used quite often in a program. Declared constants are more common and they are defined using the keyword const. short int number_of_students. In initialising a variable any of the following three approaches are valid: int a. or int a=10. The most important restriction on using a variable in C is that they have to be declared at the beginning of the program. float total. Above set of expressions declared. float total.Consider the . variables “a” as an integer. float total.6 Variables A variable has a value that can change.6. Programmers cannot use any of the keywords as variable names. sub_total.1 Declaring Variables In order to use a variable in C. Except with void type.

pre-processor directive. Table 2.128. Consider the example given below: /* Program-2. return 0.7 Displaying Numbers When displaying numbers special care must be given to the data type. Each data type has to be used with printf function in a specific format.8 which makes use of variables. In this program variables “ ” and “ ” are a b initialised with values 10.000000 The first number is of the type integer while the second number is of the type float.7.6 */ #include <stdio. These are called defined constants. Following expression illustrates the use of the #define pre-processor directive #define pi 3. which in turn determines the suitable memory storage locations. Consider Program-2. Exercise 2. Execute the program and observe the outputs.5 summarises conversion specifies supported by the printf function. They are used to instruct the compiler about the type of numbers appearing in the program. © Department of Computer Science and Engineering 13 . Exercise 2. Table 2. Run your program and observe the output.141 2. Conversion specifier %d stands for decimal while %f stands for float. 5 – The printf conversion specifiers Conversion Specifiers %c %d %e or %E %f %g or %G %i %o %p %s %u %x or %X %% Meaning of the output format Character Decimal integer Scientific notation Floating point Scientific notation or floating point (whichever shorter) Decimal integer Octal number Pointer String of characters Unsigned decimal integer Hexadecimal number Display the % sign The conversion specifiers are also referred as format characters or format specifiers.3: Identify the output of each printf function call given in Program-2. } Executing above program will display the following: 128 128. printf("%f\n".0).0 and 3 and the answer (b/a) is stored in variable “c”. In order to display the correct values using the printf function conversion specifiers should be used.2: Rewrite Program-2.h> int main() { printf("%d\n".3 and try swapping the %d and %f. Incorrect use of format characters would result in wrong outputs.128).

The format %. float c. first_letter).a). first_letter).8 so that it displays an answer which is correct up to 2 decimal points.333333 In Program-2.9 illustrates the use of character variables.3 or 3. This can be achieved by using modifiers along with the format characters in order to specify the required field width.b).5: Write a program to assign the number 34. } //decimal value //decimal value //floating point value Executing Program-2.5678 to a variable named “number” then display the number rounded to the nearest integer value and next the number rounded to two decimal places. return 0.2f will display first two digits after that decimal point.9 */ #include <stdio.33 rather than 3. Exercise2. Exercise 2. printf("%f\n".0f will suppress all the digits to the right of the decimal point. c = b/a.h> int main() { printf("%d\n". printf("%d\n".65).h> int main() { char first_letter. printf("A is %d\n". Program-2.0. return 0.0/2).8 you may wish to see the answer appearing in a more manageable form like 3. while the format %.h> int main() { int a = 3. } Executing Program-2.9 will display the following: Character A ASCII value 65 14 © Department of Computer Science and Engineering . printf("Character %c\n".65. printf("B is %d\n".4: Modify Program-2.333333. //display character printf("ASCII value %d\n". first_letter = ‘A’. /* Program-2. printf("%x\n".8 */ #include <stdio.8 will display the following: A is 3 B is 0 Answer is 3. printf("Answer is %f\n". printf("%c\n".255). } /* Program-2.65/2). float b = 10. //display ASCII value return 0.7 */ #include <stdio./* Program-2.c).65*2).

*.1 Assignment Operator The assignment operator is the simple equal sign (=). a*b. b. // // // // is is is is same same same same as as as as a a a a = = = = a-b. The assignment operator can be combined with the major arithmetic operations such as. The operators define how the variables and literals in the expression will be manipulated. 3. a%b. a = a + b. Therefore many similar assignments can be used such as: a a a a -= *= /= %= b. The assignment operation always takes place from right to left. // value b + c. the programmer may use the shorthand format: a += b. Consider the following set of examples: a a a a a = = = = = 5. variables and operators. For example. C supports several types of operators and they can be classified as: • • • • • • • Assignment operator Arithmetic operators Relational operators Logical operators Bitwise operators Special operators Pointer operators Pointer operators and special operators will not be covered in this chapter. The assignment operator is used to assign a value to a variable. or it may contain variables. -. a/b. They will be introduced later under relevant sections. The format of an assignment statement is: variable-name = expression. of of of of variable variable variable variable ‘a’ ‘a’ ‘a’ ‘a’ becomes becomes becomes becomes 5 15 5 + value of b value of b + value of c In C lots of shortcuts are possible. The expression can be a single variable or a literal. instead of the statement. // value 5+10.3 – Operators in C Expressions can be built up from literals. / and %. Such operators are called compound assignment operators.1 – Arithmetic operators Operator + * / % ++ -16 Action Addition Subtraction Multiplication Division Modulo division Increment (extended) Decrement (extended) © Department of Computer Science and Engineering . // value (x*x + y*y)/2. Table 3. . literals and operators. b. // value 5 + b. b. +.

3.2

Arithmetic Operators

C supports five major arithmetic operators and two extended (shortcuts) operators (Table 3.1). Program-3.1 illustrates the usage of major arithmetic operators.
/* Program-3.1 */ #include <stdio.h> int main() { int a,b; printf("Enter a: "); scanf("%d", &a); printf("Enter b: "); scanf("%d", &b); printf("\na+b = %d", a+b); printf("\na-b = %d", a-b); printf("\na*b = %d", a*b); printf("\na/b = %d", a/b); printf("\na%%b = %d", a%b); return 0; }

//read value of a //read value of b //display sum of a & b //display subtraction of b from a //display multiplication of a & b //display division of a by b //display modulus of a divided by b

Executing Program-3.1 with “a” as 5 and “b” as 2 will display the following:
Enter a: 5 Enter b: 2 a+b a-b a*b a/b a%b = = = = = 7 3 10 2 1

3.2.1

Increment and Decrement Operators

Increment and decrement operators are very useful operators. The operator ++ means “add 1” or “increment by 1”. Similarly operator -- mean “subtract 1” or “decrement by 1”. They are also equivalent to +=1 and -=1. For example, instead of using the following expression to increment a variable:
a = a + 1;

you may use:
a +=1;

or

a++;

Also expression:
a = a - 1;

can be written as:
a -=1;

or

a--;

Both increment and decrement operators can be used as a prefix or as a suffix . The operator can be written before the identifier as a prefix (++a ) or after the identifier as a suffix (a++). In simple operations such as a++ or ++a both have exactly the same meaning. However in some cases there is a difference. Consider the following set of statements:
int a, x; a = 3; x = ++a;

After executing above segment of code, “a” will be 4 and “x” will be 4. In line 3, first the variable “a” is incremented before assigning it to variable “x”. Consider the following segment of code. © Department of Computer Science and Engineering 17

int a, x; a = 3; x = a++;

After executing above code segment “a” will be 4 and “x” will be 3. In the second approach in line 3 first “a” is assigned to “x” and then “a” is incremented. Exercise 3.1 – Predict the values of variables “a”, “b”, “sum1” and “sum2” if the following code segment is executed.
int a, b; a = b = 2; sum1 = a + (++b); sum2 = a + (b++);

3.2.2

Precede nce and Associatively of Arithmetic Operators

Precedence defines the priority of an operator while associativity indicates which variable(s) an operator is associated with or applied to. Table 3.2 illustrates the precedence of arithmetic operators and their associativity.
Table 3. 2 – Precedence of arithmetic operators

Operator ++, -*/% +–

Precedence Highest ↓ Lowest

Associativity Right to left Left to right Left to right

In the same expression, if two operators of the same precedence are found, they are evaluated from left to right, except for increment and decrement operators which are evaluated from right to left. Parentheses can also be used to change the order of evaluation and it has the highest precedence. It is recommended to use parentheses to simplify expressions without depending on the precedence.

3.3

Relational and Logical Operators

The relational operators are used to compare values forming relational expressions. The logical operators are used to connect relational expressions together using the rules of formal logic. Both types of expressions produce TRUE or FALSE results. In C, FALSE is the zero while any nonzero number is TRUE. However, the logical and relational expressions produce the value “1” for TRUE and the value “0” for FALSE. Table 3.3 shows relational and logical operators used in C.
Table 3. 3 – Relational and logical operators

Operator Relational Operators > >= < <= == != Logical Operators && || ! 3.3.1

Action Greater than Greater than or equal Less than Less than or equal Equal Not equal AND OR NOT

Precedence of Relational and Logical Operators

As arithmetic operators, relational and logical operators also have precedence. Table 3.4 summarises the relative precedence of the relational and logical operators. These operators are lower in precedence than arithmetic operators. 18 © Department of Computer Science and Engineering

Table 3. 4 – Precedence of relational and logical operators

Operator ! > >= < <= = = != && ||

Precedence Highest ↓ ↓ ↓ Lowest

Associativity Right to left Left to right Left to right Left to right Left to right

For an example consider the following expression:
10 > 8+1

is equivalent to the expression:
10 > (8+1)

In order to understand how logical expressions are evaluated consider the following expression:
a==b && c > d

This expression says that; “(a is equivalent to b) AND (c is greater than d)”. In other words this expression is evaluated as TRUE if both the conditions are met. That is if a == b is TRUE and c > d is also TRUE. If AND (&&) is replaced by logical OR (|| ) operation then only one condition needs to be TRUE. Consider another expression (assume both “a” and “b” are integers and their value is 5) :
!(a==b)

In this case, since both “a” and “b” have similar value 5, the logical value of the expression within the parenthesis is TRUE. However the NOT operation will negate the result which is TRUE. Therefore the final result will be FALSE. In order to see the effect of precedence consider the following expression:
a==b && x==y || m==n

Since equal operator (==) has a higher precedence than the logical operators the equality will be checked first. Then the logical AND operation will be performed and finally logical OR operation will be performed. Therefore this statement can be rewritten as:
((a==b) && (x==y)) || (m==n)

This expression is evaluated as TRUE if: • •
a==b is evaluated as TRUE and x==y is evaluated as TRUE Or m==n is evaluated as TRUE.

3.4

Bitwise Operators

Using C you can access and manipulate bits in variables, allowing you to perform low level operations. C supports six bitwise operators and they are listed in Table 3.5. Their precedence is lower than arithmetic, relational and logical operators (see Table 3.6).
Table 3. 5 – Bitwise operators

Operator & | ^ ~ >> << © Department of Computer Science and Engineering

Action Bitwise AND Bitwise OR Bitwise XOR One’s complement Right shift Left shift 19

2 with character “b” as the input will display the following: Character to convert: b Converted character: B Executing Program-3.2 */ #include <stdio. printf("Character to convert: "). ASCII values of the uppercase and lowercase characters have a difference of 32. scanf("%c". /* Program-3. This is the concept used in Program 3. only difference between the two characters is the 5th bit. Bitwise XOR operation can be used to invert bits. 6 – Precedence of bitwise operators Operator ~ << >> & ^ | Precedence Highest ↓ ↓ ↓ Lowest Associativity Left to right Left to right Left to right Left to right Left to right Bitwise AND.Table 3.c. Therefore any ASCII value XOR with 32 will invert its case form upper to lower and lower to upper. 12. OR and XOR operations at the bit level.h> int main() { char input. 8. “A” is represented by 6510 while “a” is represented by 9710 (97-65 = 32). At the bit level.2 with character “Q” as the input will display the following: Character to convert : Q Converted character : q 20 © Department of Computer Science and Engineering . in ASCII. 65 = 0 1 0 0 0 0 0 12 97 = 0 1 1 0 0 0 0 12 32 = 0 0 1 0 0 0 0 02 Therefore by inverting the 5th bit of a character it can be changed from uppercase to lowercase and vice versa.&input).b. Consider following set of expressions: int a = b = c = a. The bitwise AND operation will be performed at the bit level as follows: a = 12 à 00001100 b = 8 à 00001000 & 00001000 Then the variable “c” will hold the result of bitwise AND operation between “a” and “b” which is 000010002 (810 ).2 which converts a given character from uppercase to lowercase and vice versa.1 – Write a C program to convert a given character from uppercase to lowercase and vice versa. } Executing Program-3. OR and XOR operators perform logical AND. For example . //input XOR 32 return 0. a & b. input ^ 32). //read character printf("Converted character: %c". Example 3.

We know that 8 is represented in binary as: and when it is shifted by one bit to right. their precedences and associativit ies. therefore any additional bits are removed and missing bits will be filled with zero. we get: 16 = 00010000 ß 00001000 = 8 The C right shift (>>) operator shifts an 8-bit number by one or more bits to right while left shift (<<) operator shifts bits to left. as they use the same characters (for example .7 summarises all the operators supported by C. The unary operators (operators with only one operand such as &a (address of a)) have a higher precedence than the binary operators (operators with two operands such as a*b). * is used for multiplication and also to denote pointers). Table 3. Shifting a binary number to left by one bit will multiply it by 2 while shifting it to right by one bit will divide it by 2.4. In general the right shift operator is used in the form: variable >> number-of-bits and left shift is given in the form: variable >> number-of-bits In the following expression the value in the variable “a” is shift by 2 bits to right: a >> 2 Table 3. 7 – Precedence of C operators Operator ( ) [ ] -> . When operators have the same precedence an expression is evaluated left to right. After the shift operation the final result should also be a 8-bit number. ! ~ ++ -&* */% +<< >> < <= > >= = = != & ^ | && || ?: = += -= *= /= .3. we get: 8 = 00001000 à 00000100 = 4 Similarly when the number is shifted by one bit to left. Precedence Highest ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ Lowest Associativity Left to right Right to left Left to right Left to right Left to right Left to right Left to right Left to right Left to right Left to right Left to right Left to right Left to right Right to left Left to right © Department of Computer Science and Engineering 21 . However the following rule will reduce any confusion.1 Shift Operators 8 = 00001000 Shift operators allow shifting of bits either to left or right. However some operators can be confusing.

This chapter introduces ifelse and switch constructs. the message “You have passed the exam! ” will not be displayed. } Executing Program-4. Example 4. In C.h> int main() { int marks. All these are done only if the condition is TRUE. In real life. there are many control structures that are used to handle conditions and the resultant decisions. Program 4. Then display the final amount that the customer has to pay.2 is an implementation of this. if it is the case a 5% discount should be given. printf("Enter marks: ").1 The if Statement if (condition) statement. Then the final amount needs to be displayed.1 with different inputs will behave as follows: Case 1: Enter marks: 73 You have passed the exam! Case 2:Enter marks: 34 Case 3:Enter marks: 50 In the second and third cases. If the amount is greater than or equal to 1000 rupees. The resulting statement is executed if the condition is evaluated as TRUE. &marks). A simple condit ion is expressed in the form: It starts with the keyword if. Program 4. /* Program-4.4 – Conditional Control Structures A Program is usually not limited to a linear sequence of instructions. Note that there is no semicolon (.) after the condition expression. If the value of the variable “marks ” is greater than 50.1 */ #include <stdio. followed by the result statement. So instructions which compute discount and final amount should be executed as a block. //get marks if (marks >50) // if marks >50 display message printf("You have passed the exam!"). Consider the following example: if (marks >50) printf("You have passed the exam!"). the message “You have passed the exam! ” is displayed on the screen. a programme usually needs to change the sequence of execution according to some conditions. More than one statement can be executed as a result of the condition by embedding set of statements in a block (between two braces {}). 22 © Department of Computer Science and Engineering . scanf("%d".1 illustrates the use of this in a C program.1 – Write a program which accepts a number (an amount of money to be paid by a customer in rupees) entered from the keyboard. followed by a condition (a logical expression) enclosed within parenthesis. 4. First the program needs to check whether the given amount is greater than or equal to 1000. return 0. a 5% discount is given to the customer. otherwise the statement is skipped and no message is displayed.

printf("Enter amount: ").2 so that it displays the message “No discount…” if the amount is less than 1000.05. final_amount).2f". discount). /* Program-4. //get amount if (amount >= 1000) // if amount >= 1000 give discount { discount = amount* 0. printf ("\nTotal: %. printf ("Discount: %.2 to address this. discount.05. return 0. In such cases.discount. discount). scanf("%f"..final_amount. Another if clause is required to check whether the amount is less than 1000.final_amount.2f". printf("Enter amount: "). } Exercise 4.1 if the condition is TRUE.25 as the keyboard input display the following: Enter amount: 1250. } Executing Program-4. In example 4.2f". the if clause can be used to check the TRUE condition and act upon it.3 below has been modified from e Program-4. the set of statements inside the block are executed.1 – Modify Program-4.").1 so that it displays the message “You are failed!”. if marks are less than or equal to 50. © Department of Computer Science and Engineering 23 . The second if clause can be used before or after the first ( xisting) if clause.25 Discount: 62. Example 4.h> int main() { float amount. printf ("\nTotal: %. However it does not act upon the FALSE condition. If the condition is FALSE (if the amount is less than 1000) those statements will not be executed. //get amount if (amount >= 1000) // if amount >= 1000 give discount { discount = amount* 0.51 Total: 1187.2 – Modify Program-4.h> int main() { float amount. &amount).2 with 1250.2 when we wanted to identify the case where the amount is not greater than 1000 (the FALSE case) we were checking whether it is less than 1000 (<1000). final_amount). Therefore the expression resulting the FALSE condition needs to be reorganised. final_amount = amount . scanf("%f"./* Program-4. } return 0. discount. printf ("Discount: %. In many programs it is required to perform some action when a condition is TRUE and another action when it is FALSE. &amount).3 */ #include <stdio.2f".2 */ #include <stdio.discount.74 In Program-4. final_amount = amount .. } if (amount < 1000) // if amount < 1000 no discount printf ("No discount. Program-4.

Blocks make it possible to use many statements rather than just one. if marks are greater than 50.05.final_amount. } Exercise 4. else if (condition-2) statement-2..3 The if-else-if Ladder In certain cases multiple conditions are to be detected.discount. You can include both the cases (TRUE and FALSE) using the if-else structure. 4.3 – Write a program to display the student’s grade based on the following table: 24 © Department of Computer Science and Engineering . scanf("%f".1 so that it displays the message “You have passed the exam!”. one of the two statements will be executed and then the program resumes its original flow.2f". &amount).3 can be modified as follows: /* Program-4.2 The if-else Structure if (condition) statement-1. else if (condition-3) statement-3.3 – Write a program to identify whether a number input from the keyboard is even or odd. If not display the message “You have failed!”. 4.The C language allows us to use the if-else structure in such scenarios. the program should display the message “Number is even”. } else // else no discount printf ("No discount. Example 4. printf("Enter amount: ").4 */ #include <stdio. else it should display “Number is odd”. printf ("Discount: %. else statement-2. The above construct is referred as the if-else-if ladder.. … else statement-n. printf ("\nTotal: %.h> int main() { float amount. Exercise 4. discount). final_amount = amount . the corresponding statement(s) are executed and the rest of the construct it skipped. The different conditions are evaluated starting from the top of the ladder and whenever a condition is evaluated as TRUE. If it is even. In such cases the conditions and their associated statements can be arranged in a construct that takes the form: if (condition-1) statement-1.2f". return 0. The if-else structure ta kes the form: When the condition is evaluated.2 – Modify Program-4. //get amount if (amount >= 1000) // if amount >= 1000 give discount { discount = amount* 0. final_amount). discount."). Then the Program-4.

In nesting you must be careful to keep track of different ifs and corresponding elses. This can be accomplished by two approaches.4 Nesting Conditions Sometimes we need to check for multiple decisions.5 Conditional Operator Conditional operator (?:) is one of the special operators supported by the C language. An else matches with the last if in the same block. Therefore if both a >= 2 AND b >= 4 are TRUE “Result 1” will be displayed. 26 © Department of Computer Science and Engineering . to find the correct acceleration t has to be non zero and positive (since we cannot go back in time and a number should not be divided by zero).7 calculates the acceleration given u. v and t can be given as v = u + at . if else is to be associated with the first if then we can write as follows: if (a>=2) { if (b >= 4) printf("Result 1"). The conditional operator evaluates an expression and returns one of two values based on whether condition is TRUE or FALSE. if a>= 2 is TRUE but if b >= 4 is FALSE “Result 2 will be displayed. The Program-4. } else printf("Result 2"). When conditions are nested the if-else/ifelse-if construct may contain other if-else/if-else-if constructs within themselves. Therefore the acceleration can be found by the formula a = v −u . However. v and t. In this example the else corrosponds to the second if. It has the form: condition ? result-1 : result-2. v and t. In the program we implement users can input t any values for u. If a >= 2 is FALSE nothing ” will be displayed. Consider the following example: if (a>=2) if (b >= 4) printf("Result 1"). So our program should make sure it accepts only the correct inputs. The relationship among acceleration (a).4 – Rewrite the program in Example 4. u. using braces ‘{‘ and ‘}’. 4. Therefore the above can be rewritten as follows: if (a>=2) { if (b >= 4) printf("Result 1").5 – Consider the following example which determines the value of variable “b” based on the whether the given input is greater than 50 or not. To reduce any confusion braces can be used to simplify the source code.e. using compound relational tests or using nested conditions.4 – A car increases it velocity from u ms-1 to v ms-1 within t seconds. If the condition is TRUE the expression returns result-1 and if not it returns result-2. Example 4. Write a program to calculate the acceleration. } In the above. Example 4.3 using nested conditions (i. else printf("Result 2"). else printf("Result 2").4. Exercise 4.

Conditional operator can be used to implement simple if-else constructs. printf("acceleration is: %. 4. &a). return 0.6 The switch Construct Instead of using if-else-if ladder. &v). //get starting velocity printf("Enter v (m/s): "). The syntax of the switch construct is different from if-else construct. &u). scanf("%f". //get current velocity printf("Enter t (s) : "). printf("Enter value of a: ").a. such as menu options. } /* Program-4.2f m/s". b). printf("Value of b: %d".v. //get starting velocity b = a > 50 ? 1 : 2. return 0.b. the switch construct can be used to handle multiple choices.8 */ #include <stdio.7 */ #include <stdio.h> int main() { int a. break. scanf("%f". scanf("%d". } Executing Program-4.t./* Program-4. &t). case constant-2: statement(s). break. The objective is to check several possible constant values for an expression. } else printf ("Incorrect time"). printf("Enter u (m/s): "). It has the form: switch (control variable) { case constant-1: statement(s). … © Department of Computer Science and Engineering 27 .h> int main() { float u. a).8 display the following: Enter value of a: 51 Value of b: 1 Enter value of a: 45 Value of b: 2 If the input is greater than 50 variable “b” will be assigned “1” and if not it will be assigned “2”. However use of conditional operator is not recommended in modern day programming since it may reduce the readability of the source code. scanf("%f". //get time if(t >= 0) { a = (v-u)/t.

} return 0. } © Department of Computer Science and Engineering 29 . default: printf(“Invalid input”). default: printf("\nIncorrect input"). A sample run of you program should be similar to the following: Enter number 1: 20 Enter number 2: 12 Mathematical Operation ----------------------------------1 . break. break.AutoCAD 4 .5 – Develop a simple calculator to accept two floating point numbers from the keyboard.Microsoft Word 2 .break. Then display the answer. Then display a menu to the user and let him/her select a mathematical operation to be performed on those two numbers. In such cases several cases can be grouped together as follows: switch (x) { case 1: case 2: case 3: printf(“Valid input”).Add 2 .Subtract 3 . } Executing Program-4.Divide ----------------------------------Enter your preference: 2 Answer : 8.00 In certain cases you may need to execute the same statement(s) for several cases of a switch block.Multiply 4 .Yahoo messenger 3 .9 will display the following: Menu ----------------------------------1 .Java Games ----------------------------------Enter number of your preference: 1 Personal Computer Software Exercise 4.

but you have to use suitable control expression and an initial value. The construct includes the initialization of the counter. Since the “counter” is “2” the expression will be TRUE. The C language supports three constructs. The third expression is the incrimination of the counter. } //loop 5 times Execution of program-5.1 displays: This This This This This is is is is is a a a a a loop loop loop loop loop In the above example . 5. Then the loop will terminate and the control is given to rest of the instructions which are outside the loop. } return 0. In addition it provides ways to initialize the counter and increment (or decrement) the counter. Then the “counter” is incremented by the ++ operator and now its new value becomes “2”. “as long as the counter is less than or equal to 5 repeat the statement(s)”. Therefore the printf function gets executed for the second time. It reads as. Exercise 5. This process continues for another 2 rounds. counter <= 5. Then the expression “counter <= 5” is evaluated. for(counter=1.h> int main() { int counter. At this point the first round of the loop is completed. In the first round of execution the “counter” is set to “1”. When the expression is evaluated at the 6 beginning of the sixth round the “counter” is greater than 5 therefore expression becomes FALSE.1 – Write a C program to display all the integers from 100 to 200. namely for. Therefore the printf function gets executed. The main function of the for loop is to repeat the statement(s) while the condition remains true. Example 5. Consider the following example: /* Program-5. the variable “ counter” starts with an initial value of “1”. Rest of this chapter introduces these control structures.1 */ #include <stdio. The general form of a for loop is: for (counter-initialization.while loops. increment) statement(s).1 – Write a program to calculate the sum of all the even numbers up to 100.1 The for loop The for loop construct is used to repeat a statement or block of statements a specified number of times. These repetitive constructs are called loops or control structures.5 – Control Structures A Program is usually not limited to a linear sequence of instructions or conditional structures and it is sometimes required to execute a statement or a block of statements repeatedly. Therefore the for loop is designed to perform a repetitive action for a pre-defined number of times. it is achieved by the ++ operator. You may also decrement the counter depending on the requirement. Then the “counter” is incremented once more and its new value becomes “3”. 30 © Department of Computer Science and Engineering . Since the current value of the “counter” is “1” expression is evaluated as TRUE. while and do. the condition and the increment. counter++) { printf("This is a loop\n"). Then in the second round the expression is evaluated again. After a total of five rounds the “ counter” becomes “ ”. The condition should check for a specific value of the counter. The second expression inside the parenthesis determines the number of repetit ions of the loop. condition.

h> int main() { int counter. the only thing you can do is to abort the program (a program can be aborted by pressing Ctrl+Break). By adding 2 to an even number the next even number can be found. printf("Enter second number: ").3 – Write a program to compute the sum of all integers form 1 to 100. sum. (counter += 2)) //increment by 2 { sum += counter.First even number is 0 and the last even number is 100. /* Program-5. for(. Exercise 5. num1++) { sum += num1. You can omit even all the expressions as in the following example: for(. Program-5. for(counter=0. scanf("%d". This loop is an infinite one (called an infinite loop). Even the statement(s) inside the loop are optional. &num1). num1 <= num2.) printf("Hello World\n"). Each of the three parts inside the parentheses of the for statement is optional. } printf("Total : %d".. The general form of the while loop is: 31 © Department of Computer Science and Engineering . } //read num1 //read num2 //sum = sum+num1 5. It is repeated continuously unless you include a suitable condition inside the loop block to terminate the execution. Example 5. In this program both inputs should be given from the keyboard.2 such that it computes the sum of all the odd numbers up to 100. The programmer has to take care about the other elements (initialization and incrementing). return 0.. /* Program-5.2 – Modify Program-5. sum=0. printf("Enter first number: ").2 is an implementation of the above requirement. Therefore at the time of development both initial value and the final value are not known. num2. scanf("%d". You may omit any of them as long as your program contains the necessary statements to take care of the loop execution. sum. } printf("Total : %d". Therefore the counter should be incremented by 2 in each round.2 – Write a program to compute the sum of all integers between any given two numbers. return 0.4 – Write a program to calculate the factorial of any given positive integer. If there is no such condition.h> int main() { int num1. &num2). } Exercise 5. Exercise 5.2 The while Loop The while loop construct contains only the condition.3 */ #include <stdio. sum). sum = 0.2 */ #include <stdio. sum). counter <= 100.

Next we need to make sure that the program loops only 5 times. You need to make sure that the expression will stop at some point otherwise it will become an infinite loop. Consider the following example: 32 © Department of Computer Science and Engineering .4 with 5 as the input will display the following: Enter Hello Hello Hello Hello Hello number of times to repeat: 5 World! World! World! World! World! In Program-5. } while (condition).) at each round. Exercise 5. printf("Enter number of times to repeat: "). while (num != 0) { printf("Hello World!\n"). Consider the following example: /* Program-5. It takes the following form: do { statement(s).while loop. scanf("%d". 5.4 */ #include <stdio. That is achieved by decrementing the counter (num-. The only difference between the do-while loop and other loops is that in the do. If the counter is not decremented the program will loop forever. } Execution of Program-5.while (condition) { statement(s). The loop continues as long as the expression is TRUE.5 – What would happen if we enter -1 as the number of times to loop in Program-5. In such cases use of while loop is desirable than the for loop. { The loop is controlled by the logical expression that appears between the parentheses.4 so that it works only for positive integers.4 variable “num” act as the counter. The while loop is suitable in cases where the exact number of repetitions is not known in advance. } return 0. In program-5.3 The do-while Loop Another useful loop is the do.4 the number of times to loop. num--. This means that the statement(s) inside the loop will be executed at least once regardless of the condition being evaluated. depends on the user input. It will stop when the condition becomes FALSE it will stop. The conditions inside the while loop check whether the counter is not equal to zero (num != 0) if so it will execute the printf function.while loop the condition comes after the statement(s).4? Modify Program-5.h> int main() { int num. &num).

} while (price > 0). return 0. Therefore first you need to fully complete the first row and then you should go to the next. Example 5.h> int main() { float price. the for loop is recommended for cases where the number of repetitions is known in advance. The program should exit when the user enter 0. total.5 with some inputs will display the following: Enter Enter Enter Enter Total price (0 price (0 price (0 price (0 : 122. } Execution of Program-5. After displaying the correct message it should again display the menu.5 accepts prices of items from the keyboard and then it computes the total.4 Nesting of Loops Like the conditional structures loops can also be nested inside one another. Therefore in this type of a program do-while loop is recommended than the while loop. The while loop is recommended for cases where the number of repetitions are unknown or unclear during the development process. However.3 – Write a C program to display the following pattern: \$\$\$\$\$\$\$\$\$\$ \$\$\$\$\$\$\$\$\$\$ \$\$\$\$\$\$\$\$\$\$ \$\$\$\$\$\$\$\$\$\$ \$\$\$\$\$\$\$\$\$\$ There are 10 “\$” symbols in a single row (10 columns) and there are 5 rows. The do-while loop is recommended for cases where the loop to be executed needs to run at least once regardless of the condition. 5. Exercise 5. Therefore the loop which handles printing of individual rows should be the outer loop and one which prints elements within a row (columns) should be the inner loop. Then based on the user selection it should display the correct message.2f". // if valid price continue loop printf("Total : %. © Department of Computer Science and Engineering 33 . each type of loop can be interchanged with the other two types by including proper control mechanisms.8 such that it first displays the menu.99 0 Program-5. User can enter any number of prices and the program will add them up. However the printf function does not support displaying text on a row that you have already printed. This can be implemented by having a two loops one nested inside another which print individual “\$” symbols. Program-5. However having large number of nesting will reduce the readability of your source code. You can nest loops of any kind inside another to any depth you want. //set initial value to 0 do //request for price { printf("Enter price (0 to end): ")./* Program-5. //get price total += price. scanf("%f".5 */ #include <stdio.49 to to to to end): end): end): end): 10 12. &price).6 displays the above symbol pattern. It will terminate only if zero or any negative number is entered. In summary. total). In order to calculate the total or terminate the program there should be at least one input from the keyboard.50 99. total = 0 .6 – Modify Program-4.

During the first 5 iterations the program executes normally displaying the message “Hello World! ”. If you have nested loops. Consider the following example: /* Program-5. then the break statement inside one loop transfers the control to the immediate outer loop. Therefore the if condition which evaluates whether “ n==5” becomes TRUE. At this point the loop will terminate because of the break keyword.h> int main() { int n. The control will be transferred to the first statement following the loop block. } } return 0. } Under normal circumstances the Program-5. break.7 – Write a C program to display the following symbol pattern: * ** *** **** ***** ****** 5. 34 © Department of Computer Science and Engineering . for(i=0.h> int main() { int i.j.7 */ #include <stdio.n>0. Then at the beginning of the sixth iteration variable “n” becomes “5”. } return 0. The program should allow users to terminate the program at any time by pressing any key before it displays all the 10000 messages.j++) { printf("\$")./* Program-5. Example 5. Notice that in this example the for loop is written as a decrement rather than an increment. The break statement can be used to terminate an infinite loop or to force a loop to end before its normal termination. if(n == 5) { printf("Countdown aborted!"). for(n=10. immediately bypassing any conditions.7 will display the “ Hello World! ” message 10 times.j<=10.4 – Write a C program to display the message “Hello World!” 10000 times.6 */ #include <stdio.i<=5.n--) { printf("Hello World!\n"). } printf("\n").i++) { for(j=0. } //outer loop // inner loop // end of inner loop //end of outer loop Exercise 5. so it will execute the printf function and then the break instruction.5 The break Keyword The break keyword is used to terminate a loop.

Exercise 5. © Department of Computer Science and Engineering 35 . However a number should not be divided by 0. for(i=0. i.i). By convention. when “i” is 0 (when the if condition is TRUE) the continue keyword is used to skip the rest of the iteration which will skip the printf function. In Program-5. statement in within the main function following code can be used: exit (0).9 */ #include <stdio. } return 0.h. for(i=-5.9.8 – Write a C program to display a sine table.2f \n". /* Program-5. The kbhit function is defined in the header file conio. The program should display all the sine values from 0 to 360 degrees (at 5 degrees increments) and it should display only 20 rows at a time. } 5.i<=5. If a key has been pressed. printf("5 divided by %d is: \t %. break.i++) // loop from -5 to 5 { if (i == 0) // if 0 skip continue. (5.h> #include <conio.i++) // loop 10000 times { printf("Hello World! %d\n". 5. /* Program-5.The C function kbhit can be used to check for a keystroke. it returns the value “1” otherwise it returns “0”. causing it to jump to the next iteration. If a program is to be terminated before the return 0. It takes the following form: exit (int exit-code) The exit-code is used by the operating systems and may also be used by the calling program.i<=10000.0/i)).7 The exit Function The exit function (defined in the header file stdlib.9. if(kbhit() != 0) // if a key is pressed { printf("Loop terminated").6 The continue Keyword The keyword continue causes the program to skip the rest of the loop in the current iteration. } In program-5. Consider the following example.h> int main() { int i.h) is used to terminate the running program with a specific exit code. 5 is divided by all the integers from -5 to +5. an exit-code of 0 indicates a normal exit where as any other value indicates an abnormal exit or an error. //terminate loop } } return 0.8 */ #include <stdio.h> int main() { int i.

81. 36 © Department of Computer Science and Engineering . This approach makes use of the format: array-name[index]. such as grades received by the students.) is used to separate one value from another. &marks[i]).h> int main() { int i. 86.sum. 33. scanf("%d". For example: marks[5] = {55. i+1). When declaring an array. the compiler must be able to determine exactly how much memory to allocate at compilation time. 6. 67. int marks[5]. //array of 5 elements float average.i++) //total marks { sum +=marks[i]. 67}.1 */ #include <stdio. int marks[5]. In the first approach. sum=0. The elements of an array can be initialised in two ways. The typical declaration of an array is: data-type array-name[no-of-elements]. In the second approach elements of the array can be initialised one at a time. For example: marks[0] marks[1] marks[2] marks[3] marks[4] = = = = = 55. 86. The following array can hold marks for five subjects. Like any other variable in C an array must be declared before it is used. As arrays are blocks of static memory locations of a given size. sine values of a series of angles. etc. 33. Arrays are useful when you store related data items. the number of array elements should be constant. Notice that the array name must not be separated from the square brackets containing the index. the value of each element of the array is listed within two curly brackets ({}) and a comma (.i<=5. Therefore in an array with “n” elements first index is “ and the last index is “ 0” n-1”.1 Initialising an Array An array will not be initialised when it is declared.i++) { printf("Enter marks for subject %d: ". Using an array we can store five values of type int with a single identifier without having to declare five different variables with a different identifier. 81.6 – Arrays Arrays are a series of elements of the same data type placed consecutively in memory that can be individually referenced by adding an index to a unique name. Consider the following example: /* Program-6.i<5. for(i=0. In an array index of the first element is considered as zero rather than one. //get the marks } for(i=0. therefore its contents are undetermined until we store some values in it. This confusion can be overcome by initialising an array with “n+1” elements and neglecting the first element (element with zero index).

2 Multidimensional Arrays The type of arrays that we discussed up to now is called a one-dimensional (or single dimensional) array. 59. //5. © Department of Computer Science and Engineering 37 . 86. 33.0.1 hold only marks of one student. 81. 82. Marks[0][0] marks[0][1] marks[0][2] marks[0][3] marks[0][4] = = = = = 55. 30. {45.} average = sum/5. Similarly we can define arrays with n dimensions and such arrays are called n-dimensional or multidimensional arrays. return 0. 33. as it takes one index and store only one type of data.0 indicates a float value printf("Average : %. The array that was used in Program-6. 46. You can declare an array to hold marks of 100 students with store marks of 5 subjects as in the following example: int students[100][5]. 57.2f". Altogether it declares 500 (100×5) memory locations. It can be extended to store marks of many students using a twodimensional array. Such an array is declared in the following form: data-type array-name[size-1][size-2].1 displays the following: Enter marks for Enter marks for Enter marks for Enter marks for Enter marks for Average : 64. 67. 86.1 – Write a program to store marks of 5 students for 5 subjects given through the keyboard. 60} }. {39. int students[3][5]= { {55. Initialising marks of the first student can be performed in the following manner. 6.60 subject subject subject subject subject 1: 2: 3: 4: 5: 55 33 86 81 67 The Program-6. 67}. Exercise 6. average). 86. A two-dimensional array is initialised in the same way. 47}. The first index defines the number of students and the second index defines the number of subjects. 81. Then in the second loop it computes total of all marks stored in the array and finally it computes the average. Calculate the average of each students marks and the average of marks taken by all the students. } Execution of Program-6. The following statement declares and initialises a two-dimensional array of type int which holds the scores of three students in five different tests.1 accepts marks for 5 subjects from the keyboard and stores them in an array named marks .

Prototypes of functions int main( ) { ………. Well designed functions perform a specific and easily understood task. Complicated tasks should be broken down into multiple functions and then each can be called in the proper order. Therefore functions can be classified as built-in and user defined. but you can also write your own functions. followed by the #define directive (if any) then followed by the proto types of functions. some may return a value of a certain data type (such as kbhit ) and some may accept as well as return a value (sqrt ). Then comes the program building block which includes the main( ) function and implementation of the user defined functions. The prototype is a declaration of a function used in the program. 7. A modular program is usually made up of different functions. } function_1( ) { ………. } ………… function_n( ) { ………. each one accomplishing a specific task such as calculating the square root or the factorial.1 A Function A function is a subprogram that can act on data and return a value.. It starts with the #include directive. In general a modular program consists of the main( ) function followed by set of user defined functions as given below: #include …… #define …. 38 © Department of Computer Science and Engineering . Each function has a unique name and when the name is encountered while in execution the control of the program is transferred to the statement(s) within the function... When a program is executed the main( ) is called automatically. } The source code contains other elements in addition to the function blocks. When the function is ended (returns) the control is resumed to the next statement following the function call. the main( ).. } function_2( ) { ……….7 – Functions The C functions that you have used so far (such as printf and scanf) are built into the C libraries. Some functions may accept certain input parameters (such as printf). The main( ) may call other functions and some of them might call other functions. Every C program has at least one function.

4. 7. The program accepts an integer from the keyboard and when the expression area(radius). A well written C source code should not have any global variables unless they are specifically required since an accidental change to a global variable may produce erroneous results. The value passed must be of the declared type. converts the integer value to a floating point number (this process is called casting) before calling the function..2 executes each function based on the given input. Scope of a local variable is limited to the function. you still have two local variables isolated from each other. //global variable float sub_total(float total). It is also possible to have the same name for functions with different behaviour with different input parameters. Thus if you have a function declared as: long my_function(int a).1 The Scope of a Variable A variable has a scope. If the function definition differs or if you pass a value of a wrong data type you will get a compilation error. For example you can define a global variable “discount” as follows: #include <stdio. 7. You can modify its value in either place and read it from another place. In order to avoid errors when using functions. The global variable can be defined within the program but anywhere outside function block including the main function.2 Default Parameters For every parameter you declare in a function prototype and declaration the calling function must pass in a value. you cannot have functions with the same name with a different output parameter.h> float discount. the function must in fact take an integer value as an input. however best practices suggest that no two functions should have the same name unless they perform identical tasks. but not the variable it self. you have to have a clear understanding about the mechanism of passing variables from one function to another. The expression area((float)radius). This means that the value of the passed variable cannot be changed by any other function. On the other hand you can also define global variables which are accessible from any function within the same source file. is executed it calls the function which accepts and integer as the input parameter and it display the message “ Integer input” and the area. © Department of Computer Science and Engineering 41 . When it is called since the input is a floating point value it executes the function which displays the message “Floating point input”. A variable declared inside a function is called a local variable . Although you can have multiple functions with the same name but with different input parameters. A variable defined in such a manner is visible to the main function and the “sub_total” function.. When you pass a variable to a function (such as the variable radius in Program-7. which determines how long it is available to your program (or function) and where it can be accessed from.Program-7.1). Variables declared within a block are scoped only to that block.. you are actually passing a copy of the variable (called passed by value). Even if you use another variable with the same name in the function. they can be accessed only within that block and go out of existence when the execution of the block is completed. //function prototype int main() { .4.4 Passing Variables to Functions You can use as many functions as you need in your programs and you can call a function from another or even from it-self. 7. However when you declare the function prototype you can define a default value for the parameter as follows: long my_function(int a = 50). Such variables are not seen by any other functions including the main function.

z = x.c). a=5. void swap2(int x). } void swap2(int x) { int z. swap2(b). int y) { int z. Exercise 7.int y). printf("\nValue after 2nd function a= %d. } 42 © Department of Computer Science and Engineering . b= %d c= %d" . b= %d c= %d" .3. b=10. printf("\nValue before 1st function a= %d.c).c). /*Program-7. c=15. y = z. Similarly a function with many input parameters can have a default value for each parameter.The default value is used if no input is supplied to the function.a.c. a = z. } void swap1(int x. printf("Test"). swap1(b. x = a.b.a. int main() { int b.3 */ #include <stdio.h> void swap1(int x. printf("\nValue after 1st function a= %d. z = x.b. int a. return 0. x = y.1 – Predict the output of each printf function in Program-7.c).b. b= %d c= %d" .a.

2 displays: Before swapping a= 5: b= 10 After swapping a= 10: b= 5 8. Example 8. &b). a = "Hello World!". a.b. b = 10. The final statement displays the value of the pointer “pnt” which holds the value of the variable “number”.int *b). Consider the following example: 44 © Department of Computer Science and Engineering . } void swap(int *a. Strings in C are handled differently than most other languages.return 0.2 Text Strings and Pointers An array of characters is called a string. the program can locate it. //call function printf("\nAfter swapping a= %d: b= %d". It will point to the first character of the string. The fourth printf function displays the address of the pointer.1 displays: The The The The The number is: 20 address of the number is: 1245064 pointer is: 1245064 address of the pointer is: 1245060 value of the pointer is: 20 The first printf function displays the value of variable “number”. x = *b.2 */ #include <stdio. int *b) { int x. A pointer is used to keep track of a text string stored in memory. } Execution of Program-8. b). } Execution of Program-8.1 – Write a program to swap two integer numbers using pointers. printf("\nBefore swapping a= %d: b= %d". *a = x. a. swap(&a. int main() { int a. *b = *a. The third statement displays the value of the “pnt” which is assigned by the expression pnt = &number. A character pointer is used to point to the first character of a string as given in the following example: char *a. return 0. /* Program-8. By knowing the beginning address and the length of the string. The second printf statement displays the address of the memory location occupied by the variable named “number”. a = 5.. Note that now the address of variable “number” and value of pointer “pnt” is the same. b).h> void swap(int *a.

*a). a). printf("First character: %c\n".3 the first printf function displays the string pointed by pointer “a”.. you can point to the first element of the array using either one of the following pointers: marks &marks[0] //first element //first element Also the following pairs of pointers are equivalent: marks+1 == &marks[1] . } Exaction of Program-8. /* Program-8. a).. 73. The name of an array points to the first element of the array. The second printf function display the value pointed by pointer “a” which is the first character of the string.3 */ #include <stdio. printf("Starting memory address: %d\n". 98. *a).3 Pointers and Arrays An array is a series of elements of the same data type. printf("String: %s\n"..h> int main() { int marks[5]= {89. } marks). index and pointers. printf("%d\n". printf("First character: %d\n". *marks). marks+4 == &marks[4] Or you can use the array name to refer to the contents of the array elements like: *(marks) *(marks+1) //value of 1st element //value of 2nd element Program 8. 39}. //memory address pointed by pointer //memory address of 1st element //value pointed by pointer //value of 1st array element © Department of Computer Science and Engineering 45 .3 will display: String: Hello World First character: H Starting memory address: 4235496 First character: 72 In Program-8. If you declare an array in the following manner: int marks[5]. printf("%d\n". The final printf function displa ys the ASCII value of the first character in the string.4 illustrates the use of array name... Pointers can be used to manipulate arrays rather than using an index. 8.h> int main() { char *a. The third printf function displays the starting memory address of the string which is the value of pointer “a”. &marks[0]). return 0. printf("%d\n"./* Program-8. a = "Hello World". marks[0]). return 0. printf("%d\n".4 */ #include <stdio. 45.

ac. //write character pointed by pointer fclose(fp). namely fputs and fprintf can be used for this purpose.fp). 2. //loop counter char *message. Add new friend.txt file as follows: --------------Contact info--------------Name Tel-No e-Mail Kamala 077-7123123 kamala@yahoo.ac.2 – Develop a simple telephone directory which saves your friends contact information in a file named directory. file_pointer) fprintf(file_pointer. A pointer is used to point to the string and the pointer is incremented by one memory location at a time. } Writing a String to a File The advantage of putc is that it allows you to control every byte that you write into the file. Exit -----------------------------------------------Enter menu number: When you press “1” it should request you to enter following data: ---------New friend info-------Name : Saman Phone-No: 011-2123456 e-Mail : saman@cse.h> int main() { FILE *fp.com Saman 011-2123456 saman@cse. 3. /* Program-9. The program should have a menu similar to the following: ----------------Menu------------------------1.lk ----------------------------------------- © Department of Computer Science and Engineering 49 . Two functions . “%s”.txt. The format of each function is: fputs(string.i++) putc(*(message+i).function which returns the number of characters in a string is used. i < strlen(message). Exercise 9.com Kalani 033-4100101 kalani@gmail.3 such that it uses the fputs rather than the fputc function to write the message to the file . "w").1 – Modify Program-9.mrt.3 */ #include <stdio. However sometimes you may want to write one string at a time. message = "Introduction C Programming".mrt.lk After adding new contact information it should again display the menu. //open for writing if(fp != NULL) //if success { for (i =0 . //close the file } else printf("\nError while opening file"). return 0. fp = fopen("c:\\message.h> #include <string. When you press “2” it should display all the contact information stored in the directory. string) Exercise 9.txt". The fprintf function is identical to the printf function only difference being that it writes to a file rather than to the screen. int i. Display contact info.

Step 1: The program given below calculates the roots of the quadratic equation provided that ax 2 + bx + c = 0 b 2 − 4ax ≥ 0 .2f\n". scanf("%lf %lf %lf". Some of these errors result in source code that does not confirm to the syntax of the programming language and are caught by the compiler at compile time. enter the following command. 8 Why is it that we have to type . go ahead and modify the program given above to display its source code on standard output.out Hello world! \$ Step 5: Now.e. &c). b. b and c //if complex roots //if roots are not complex //get the square root //end main Step 2: Now.out file is created. #include <stdio. surface only at runtime and cause programs to fail at performing their intended tasks. execute the file a. //Pre-processor directives Type the following program using a text editor and then save it as test2. to compile and link the program saved in Step 1. Such defects in programs are called bugs and the process of eliminating them is called debugging. \$ gcc test1./a. double r1 = (-b -t) / (2*a). printf("Enter a.out as shown below. printf("%.4*c.c \$ Step 4: Lastly. The text below also shows what you may expect next! Notice that we are not trying to link the output of the compiler yet. Use the ls command to see whether a. &b. double delta = b*b . else { double t = sqrt(delta). } //read a. enter the command gcc -c test2. why won’t typing a.2 Syntax Errors and Bugs Programmers been humans more often than not they end up writing incorrect source code. c.c.out to execute the file a.Step 3: Next.c.out alone work?) © Department of Computer Science and Engineering 51 . \$ ls a.h> #include <math. double r2 = (-b + t) / (2*a). c: ). Some others however. r1.out test1. to compile the program. b.out in the working directory. \$ . r2) } return 0.2f %. 8 A. delta.c \$ By default.out in the working directory? (i. Hint: Study the use of escape sequences (escape codes) \n and \t with printf. to run the new program./a.h> int main() //Start main Function { double a. the output of the linker will be saved as a file named a. if (delta < 0) printf("complex roots!\n"). &a.

c:9:20: warning: multi-line string literals are deprecated test2. In this case we are not using any IDE and the compiler used is GNU C compiler.c:8: stray ’\’ in program test2. test1. modify the line 10 to be like as shown below.c again and see whether it compiles without errors now. test2. If you corrected the error on line 8 properly. Warnings on the other hand indicate bad coding practices on part of the programmer such as unused variables. you should now get set of messages similar to the following: test2. delta = b*b . Errors.c:19:22: warning: multi-line string literals are deprecated test2.c:8: (Each undeclared identifier is reported only once test2.c:8:16: possible start of unterminated string literal After fixing line 8.c: In function ‘main’: test2. there will be two types of messages reported errors and warnings.c.c) try to figure out what is wrong and correct it on your own.c:8: parse error before string constant test2. the compiler reports the file name and the line number where it found the error.c:14:27: warning: multi-line string literals are deprecated test2.c:8: stray ’\’ in program test2. This is because of the errors in the source code.c: In function ‘main’: test2. Typically. you should not get any more error messages.c:8: for each function it appears in. test2.e.c:6: ‘delta’ previously declared here test2.c:8:16: warning: multi-line string literals are deprecated test2.c:6: ‘delta’ previously declared here Both the first and the second error messages are in fact caused by the same error.c:19:22: missing terminating " character test2.c:20: parse error before ’}’ token test2. You may also want to take in to consideration the following warning: test2.) test2. make an attempt to correct it on your own by comparing this particular printf statement with other printf statements that you know to be correct. The way errors are reported depends on the compiler and the IDE used. Notice that for each syntax error.c:10: redeclaration of ‘delta’ test2. recompile the program. Open the file test2.c test2. i.c:8: ‘lf’ undeclared (first use in this function) test2.c:8:16: possible start of unterminated string literal \$ All of the above messages are reported by the C compiler when it attempted to compile the source file.4*c.\$ gcc -c test2. Step 3: Lets.c in Kwrite editor and to jump straight to line 8 Comparing the printf statement on line 8 with what you found in the earlier program (i. go back to command mode and locate the cursor at the point of first error. Now. After correcting the error.c:20: parse error before ’}’ token Given the fact that this error concerns the printf statement on line 19. Notice that most of the error messages are concerned with line 8. To correct it.e. try to correct some of the errors reported above. go back and try compiling test2. 52 © Department of Computer Science and Engineering . If you correctly followed all the above instructions.c:10: redeclaration of ‘delta’ test2. are cases where the supplied source code does not confirm to the syntax of the language.

2 – Given a date as a triplet of numbers ( m. If not zero marks will be given./a. the corresponding day of the week f (f = 0 for Sunday. } © Department of Computer Science and Engineering 55 . if (a > b ) if (b < c) { .out Temperature reading: 100F 37C Exercise B./a. f = 1 f r Monday. Exercises Exercise B. } else { .. No need of submission. The temperature reading consists of a decimal number followed by letter ”F” or ”f” if the temperature is in Fahrenheit scale or letter ”C ” or ”c” if it is in Celsius scale. Before you leave the lab make sure you show your instructor that you have saved your file in Lab4 folder.out Temperature reading: 100C 212F \$ . with y indicating the year.Annex B – Lab 4 Conditional Structures (1) Remarks • • • This lab session will be evaluated and it will carry 4% of your final marks. month (m = 1 for January. All divisions indicated above are integer divisions.1 (c) let a = 2m + 6 (m + 1) / 10 (d) let b = y + y/4 – y/100 + y/400 (e) let f1 = d + a + b + 1 (t) let f = f1 mod 7 (g) stop. int a. m the y. m = 2 for February. write down 2 possible ways in which it can be implemented properly.. b. . etc. and d the day of the month. Discussion Given that the else clause in the following code fragment belongs to the outer statement. All the source codes and executables related to this lab session should be saved in a folder named Lab4 which should be created within your home directory. .1 – Write a program to input a temperature reading in either Celsius(c) or Fahrenheit(f) scale and convert it to the other scale. Note: c= 5( f − 32) 9 \$ .). c. . You may use a similar format for the output of the program. d)..) can be found as o follows: (a) if m < 3 (b) let m = m + 12 and let y = y . etc. Write a program that will read a date and print the corresponding day of the week..

You can either use a simple text editor or IDE such as KDevelop. Exercises Exercise D. ****** ***** **** *** ** * ** *** **** ***** ****** 60 © Department of Computer Science and Engineering . All the source codes and executables related to this lab session should be saved in a folder named Lab6 which should be created within your home directory.1 – Write a program to input a series of positive integers and determine whether they are prime. If not zero marks will be given. 28 = 1 + 2 + 4 + 7 + 14 \$ . A perfect number is a number whose factors other than itself add up to itself./a.out 1 2 Prime 3 Prime 4 5 Prime 6 -1 \$ Exercise D. The program should terminate if a negative integer is given as the input. A prime number is a number that is divisible by only one and itself.3 – Write a program to display the following symbol pattern. Execution of your program should produce something similar to the following: \$ . Example: 6 = 1 + 2 + 3. 2 – Write a program to find out whether a given number is a perfect number. The program should terminate if a negative integer is given as the input./a. Before you leave the lab make sure you show your instructor that you have saved your file in Lab6 folder.Annex D – Lab 6 Control Structures (1) Remarks • • • • This lab session will be evaluated and it will carry 4% of your final marks.out 6 Perfect 7 28 Perfect 11 -1 \$ Exercise D. You must use loops. However one is not considered a prime number.

8 9.Annex E – Lab 7 Control Structures and Arrays Remarks • • • This lab session will be evaluated and it will carry 4% of your final marks. on four rows: 80 90 99 67 Total marks of four students: 190 225 178 191 © Department of Computer Science and Engineering 61 . The numbers can be non-integers. If not zero marks will be given.2 Exercise E. An example would be as follows: Enter 50 60 60 75 30 49 66 58 the marks of four students.2 Maximum = 54 Exercise E. Write a program to read the marks from the keyboard and calculate and display the total marks of each student.6 54 3. An example would be as follows: Enter 10 numbers: 5 7. Use a single-dimensional array to store the numbers entered. An example would be as follows: Enter 10 integers: 5 78 96 54 34 12 3 7 88 5 Total = 382 Average = 38. Before you leave the lab make sure you show your instructor that you have saved your file in Lab7 folder.2 – Write a program to find and display the minimum and the maximum among 10 numbers entered from the keyboard. All the source codes and executables related to this lab session should be saved in a folder named Lab7 which should be created within your home directory.1 – Write a program to calculate and display the total and the average of 10 integer numbers input from the keyboard. Exercises Exercise E. Use a 2D (two-dimensional) array to store the marks.2 3 7 8.4 1.3 – Suppose there are 4 students each having marks of 3 subjects.8 5 Minimum = 1.

Break down the program in to three main functions to: • • • Read in the elements of matrices A and B Compute the product of the two matrices Display the resultant matrix AB 62 © Department of Computer Science and Engineering . Before you leave the lab make sure you show your instructor that you have saved your file in Lab0 folder. Assume that the elements of the matrices are integers.Annex F – Lab 9 Functions Remarks • • • This lab session will be evaluated and it will carry 4% of your final marks. and compute and display their product AB (of dimensions 3×3). Exercises Exercise F. \$ . All the source codes and executables related to this lab session should be saved in a folder named Lab9 which should be created within your home directory. If not zero marks will be given./a. Use functions to while implementing this program.out Matrix A: 1 2 4 5 3 3 4 4 4 4 5 5 Matrix B: 1 3 5 7 7 7 3 4 5 3 4 5 Matrix AB: 42 53 64 48 62 76 62 80 98 \$ Hint: Define global variables of two-dimensional arrays to store the values of the matrices.1 – Write a program to read in two matrices A and B of dimensions 3 ×4 and 4 ×3 respectively.

a semicolon and a colon. in S. Exercises Exercise G. a question mark. Use file-handling mechanism of C language to access the files.e. Further. N. the number of characters in S (i./a. length of S).out Number of words: 4 © Department of Computer Science and Engineering 63 . you may assume that there may be only one word delimiter at most between any two words in S. The input will be given in the text file problem. All the source codes and executables related to this lab session should be saved in a folder named Lab10 which should be created within your home directory.in and the output should be written to the text file problem.out.Annex G – Lab 10 File Handling Remarks • • • This lab session will be evaluated and it will carry 4% of your final marks. an exclamation mark. a period.1 – Given a string S of length N from a text file. count the total number of words T. will be at least 1 and at most 100. If not zero marks will be given. a comma. Before you leave the lab make sure you show your instructor that you have saved your file in Lab10 folder. \$ . An example would be as follows: problem. Assume words to be delimited by a space.in This is a test.

For a more complete list reader should refer to the manual (or help) of the version of C compiler that is being used.h Prototype int isalnum(int character) int isalpha(int character) int isascii(int character) int isdigit(int character) int islower(int character) int ispunct(int character) int isspace(int character) int isupper(int character) int isdigit(int character) int toascii(int character) int tolower(int character) int toupper(int character) description Determines if the character is alphanumeric.h Prototype int abs(int x) double acos(double radians) description Return absolute value of x. else 0.h ctype. else 0. Determines if the character is a punctuation character. Return negative value if str1 < str2.2 String Manipulation Functions Header file string. Determines if the character is a h exadecimal digit. else 0. Convert a character to uppercase. If true return nonzero value. Determines if the character is a whitespace.h ctype. else 0. If true return nonzero value.h ctype.Library Functions The C language is accomplished by a number of library functions that performs various tasks. If true return nonzero value. else 0. else 0.h ctype. Copy str2 to str1. If true return nonzero value. return positive value is str1 > str2 and if both are identical return 0. Function abs acos 64 © Department of Computer Science and Engineering . Compare 2 strings without considering the case. If true return nonzero value.char *str2) strcpy strlen string. Determines if the character is an ASCII character. If true return nonzero value.h ctype. Convert a character to lowercase. char *str2) description Compare 2 strings.1 Character Manipulation Functions Header file ctype.h int strcmpi(char *str1. If true return nonzero value.h ctype. Function isalnum isalpha isascii isdigit islower ispunct isspace isupper isxdigit toascii tolower toupper H. char *str2) int strlen(char *str) H.h math.h ctype. return positive value is str1 > str2 and if both are identical return 0. Return negative value if str1 < str2.3 Mathematical Functions Header file stdlib. else 0. If true return nonzero value. If true return nonzero value. Function strcmp strcmpi string. Count the number of characters in a string. Determines if the character is a uppercase.h char *strcpy(char *str1.h Prototype int strcmp(char *str1. Following is a list of commonly used functions. Determines if the character is a lowercase. Convert value of argument to ASCII.h ctype.h ctype. H. Determines if the character is a decimal digit. else 0.h string. Return the arc cosine. else 0.Annex H .h ctype.h ctype. Determines if the character is alphabetic.

.h math.h stdio. double y) double sin(double radians) double sqrt(double x) double tan(double radians) Return the arc sine. Return the arc tangent.h math. Function fclose feof fgetc fgets fopen fprintf fputc fputs getc gets puts H.h math. Read single string from file Open file. Is a key press. Return the absolute value of x. Raise e to the power x.h stdio. Enter string from standard input.5 Miscellaneous Functions Header file stdlib.h stdio.h math. Return the sine.asin atan ceil cos exp fabs log log10 pow sin sqrt tan math. Function exit kbhit © Department of Computer Science and Engineering 65 .h math. char *accessmode) int fprintf(FILE *fp. Send string to standard output. arg1.h stdio.h stdio. Determine whether end of file is reached. Read single character from file.h stdio.h math.h math. int sizeofbuffer.h Prototype void exit(int number) int kbhit(void) description Close all files and buffers and terminate the program.h math. Return the tangent. FILE *fp) int getc(FILE *fp) char *gets(char *string) int *gets(char *string) Description Close file pointed by fp. Send character to file. H. If so return none zero else zero is returned. Enter single character from file.h double asin(double radians) double atan(double radians) double atan(double value) double cos(double radians) double exp(double x) double fabs(double x) double log(double x) double log10(double x) double pow(double x. Return xy. FILE *fp) FILE *fopen(char *filename. Return a value rounded up to the next higher integer Return the cosine. char *format.4 I/O Functions Header file stdio..) to file of the given data format.h stdio. arg2.h Prototype int fclose(FILE *fp) int feof(FILE *fp) int fgetc(FILE *fp) char *fgets(char *buffer.h stdio.h math. arg2. Return the natural logarithm of x. If key is pressed return nonzero and if not return 0. Return square root of x.h math. FILE *fp) Int fputs(char *string. Send string to file.h stdio. Return the logarithm of x (base 10).h stdio. …) Int fputc(char c.h math. Send data (arg1.h conio.

Second Edition by E.Acknowledgements Some sections in this handout are extracted from: • • Learn C in Three Days by Sam A. Abolrous. BPB Publications Programming in ANSI C. Tata McGraw-Hill 66 © Department of Computer Science and Engineering . Balagurusamy.