You are on page 1of 59

Comp 111: Introduction to Programming

Introduction to C
C is a programming language which was developed at AT& Ts Bell laboratories in USA in 1972. It was designed and written by Dennis Ritchie. The languages that existed before C are: FORTRAN (FORmula TRANslation) ALGOL (ALGOrithmic Language) PL/1 (Programming Language 1) BASIC (Beginner's All-purpose Symbolic Instruction Code) Pascal The languages that supersede C are C++, C# and Java.

Why Use C?
In today's world of computer programming, there are many high-level languages to choose from, such as Pascal, BASIC, and Java. But C stands apart from all these languages. This is due to its many desirable qualities. It is a robust language whose rich set of built-in functions and operators can be used to write any complex logic program. The C language compiler combines the capabilities of a low level language with the features of a high level language. Therefore the language is suitable for writing both system software as well as business packages & other software. Many compilers available in the market written in C. Program written in C are very efficient and fast. This is due to its variety of data types and powerful operators. It is many time faster than BASIC. This helps developers in saving their valuable time. C is a powerful and flexible language which helps system developers to deliver various complex tasks with ease. C is used for diverse projects as operating systems, word processors, graphics, spreadsheets, and even compilers for other languages. C is popular among professional programmers for programming, as a result, a wide variety of C compilers and helpful accessories are available. C is highly portable language. This means that a C program written for one computer system (an IBM PC, for example) can be run on another system (a DEC VAX system, perhaps) with little or no modification. Portability is enhanced by the ANSI standard for C, the set of rules for C compilers. Cs another striking feature is its ability to extend itself. A C program is basically a collection of various function supported by C library (also known as header files). We can also add our own functions to the C library. These functions can be reused in other applications or programs by passing pieces of information to the functions, you can create useful, reusable code. Writing C program with user-defined functions makes program more simple and easy to understand. Breaking a problem in terms of functions makes program debugging, maintenance and testing easier. As these features shows that C is an excellent choice for your first programming language. But what is C+ +? You might have heard this term C++ and the programming technique called Object-Oriented Programming (OOP). Possibly you're wondering what the differences are between C and C++ and whether you should learn C or C++. C++ is a superset of C, means that C++ is the new improved version of C for the latest programming needs. It contains everything C does, plus new additions for OOP concept. If you will learn C++ later, you will find that almost everything which you learnt in C is applicable in C++ too. In learning C, you are not only learning one of today's most powerful and popular programming languages, but you are also preparing yourself for other similar programming languages.

1 Pre pared by Z. Mwololo

Comp 111: Introduction to Programming Another language that has gotten lots of attention is Java for its OOP and portability. Java, just like C++, is based on C. If later you decide to learn Java, you will find that almost everything you learned about C applies here. Characteristics of C We briefly list some of C's characteristics that define the language and also have lead to its popularity as a programming language. Naturally we will be studying many of these aspects throughout the course. Small size Extensive use of function calls Loose typing -- unlike PASCAL Structured language Low level (Bitwise) programming readily available Pointer implementation - extensive use of pointers for memory, array, structures and functions. C has now become a widely used professional language for various reasons. It has high-level constructs. It can handle low-level activities. It produces efficient programs. It can be compiled on a variety of computers. Its main drawback is that it has poor error detection which can make it off putting to the beginner. However diligence in this matter can pay off handsomely since having learned the rules of C we can break them. Not many languages allow this. This if done properly and carefully leads to the power of C programming. C Programming Language Communicating with a computer involves speaking a language that is understandable to it. Therefore there is a close analogy between learning English Language and learning C language. In English we first learn the alphabets, and then combine alphabets to form words which in turn are combined to form sentences and sentences are combined to form paragraphs. Learning C is similar and easier. Therefore we will learn the several building blocks of a program. These are: Character set Constants, variables & keywords. Instructions Program Character Set The character set in C Language can be grouped into the following categories. i. Alphabets ii. Digits iii. Special Characters iv. White Spaces White Spaces are ignored by the compiler until they are a part of string constant. White Space may be used to separate words, but are strictly prohibited while using between characters of keywords or identifiers. C Character-Set Table
Letters Digits

2 Pre pared by Z. Mwololo

Comp 111: Introduction to Programming


Upper Case A to Z Lower Case a to z 0 to 9 .

Special Characters
, . ; : ? ' .Comma .Period .Semicolon .Colon .Question Mark .Apostrophe & ^ * + < .Ampersand .Caret .Asterisk .Minus Sign .Plus Sign .Opening Angle (Less than sign) .Closing Angle (Greater than sign) .Left Parenthesis .Right Parenthesis .Left Bracket .Right Bracket .Left Brace .Right Bracket .Number Sign .

" ! | / \ ~ $ %

.Quotation Marks .Exclamation Mark .Vertical Bar .Slash .Backslash .Tilde .Underscore .Dollar Sign .Percentage Sign

> ( ) [ ] { } # .

White Space i. Blank Space ii. Horizontal Tab iii. Carriage Return iv. New Line v. Form Feed The alphabets, numbers and special symbols when properly combined form constants, variables and keywords. CONSTANTS 3 Pre pared by Z. Mwololo

Comp 111: Introduction to Programming A constant is an entity that doesnt change. In programming we deal with values which have to be stored in various locations but for the case of a constant its stored in a fixed location. Types of Constants There are two major types of constants. These are: i. Primary constants ii. Secondary constants The primary constants are: Integer constants Real constants Character constants The secondary constants include: Array Pointer Structure Union Enumaration At this stage we would restrict our discussion to only Primary Constants, namely, Integer, Real and Character constants. Let us see the details of each of these constants. For constructing these different types of constants certain rules have been laid down. These rules are as under: Rules for Constructing Integer Constants i. It must have at least one digit. ii. It must not have a decimal point. iii. It can be either positive or negative. If no sign precedes an integer constant it is assumed to be positive. iv. No commas or blanks are allowed within an integer constant. v. The allowable range for integer constants is -32768 to 32767. Ex.: 426 +782 -8000 -7605

Real Constants Real constants are often called Floating Point constants. The real constants could be written in two forms: Fractional form Exponential form. Following rules must be observed while constructing real constants expressed in fractional form: i. It must have at least one digit. ii. It must have a decimal point. iii. It could be either positive or negative. Default sign is positive. iv. No commas or blanks are allowed within a real constant. Ex.: +325.34 426.0 -32.76 -48.5792

The exponential form of representation of real constants is usually used if the value of the constant is either too small or too large. It however doesnt restrict us in any way from using exponential form of representation for other real constants. In exponential form of representation, the real constant is represented in two parts. The part appearing before e is called mantissa, whereas the part following e is called exponent. Following rules must be observed while constructing real constants expressed in exponential form: 4 Pre pared by Z. Mwololo

Comp 111: Introduction to Programming

i. ii. iii. iv.

The mantissa part and the exponential part should be separated by a letter e. The mantissa part may have a positive or negative sign. Default sign of mantissa part is positive. The exponent must have at least one digit, which must be a positive or negative integer. Default sign is positive. Range of real constants expressed in exponential form is -3.4e38 to 3.4e38. 4.1e8 -0.2e+3 -3.2e-5

Ex.: +3.2e-5

Rules for Constructing Character Constants i. A character constant is a single alphabet, a single digit or a single special symbol enclosed within single inverted commas. Both the inverted commas should point to the left. For example, A is a valid character constant whereas A is not. ii. The maximum length of a character constant can be 1 character. Ex.: 'A' 'I' '5' '='

VARIABLES An entity that may vary during program execution is called a variable. Variable names are names given to locations in memory. These locations can contain integer, real or character constants. In any language, the types of variables that it can support depend on the types of constants that it can handle. This is because a particular type of variable can hold only the same type of constant. For example, an integer variable can hold only an integer constant, a real variable can hold only a real constant and a character variable can hold only a character constant. The rules for constructing different types of constants are different. However, for constructing variable names of all types the same set of rules apply. These rules are given below. Rules for Constructing Variable Names i. A variable name is any combination of 1 to 31 alphabets, digits or underscores. Some compilers allow variable names whose length could be up to 247 characters. Still, it would be safer to stick to the rule of 31 characters. Do not create unnecessarily long variable names as it adds to your typing effort. ii. The first character in the variable name must be an alphabet or underscore. iii. No commas or blanks are allowed within a variable name. No special symbol other than an underscore (as in gross_sal) can be used in a variable name. Ex.: si_int m_hra pop_e_89

C compiler is able to distinguish between the variable names by making it compulsory for you to declare the type of any variable name that you wish to use in a program. This type declaration is done at the beginning of the program. Following are the examples of type declaration statements: Ex.: int si, m_hra; float bassal; char code ;

Since, the maximum allowable length of a variable name is 31 characters; an enormous number of variable names can be constructed using the above-mentioned rules. It is a good practice to exploit this enormous choice in naming variables by using meaningful variable names. Thus, if we want to calculate simple interest, it is always advisable to construct meaningful variable names like: prin, roi, noy to represent Principle, Rate of interest and Number of years rather than using the variables 5 Pre pared by Z. Mwololo

Comp 111: Introduction to Programming a, b, c. Keywords and Identifiers Keywords are the words whose meaning has already been explained to the C compiler (or in a broad sense to the computer). The keywords cannot be used as variable names because if we do so we are trying to assign a new meaning to the keyword, which is not allowed by the computer. Some C compilers allow you to construct variable names that exactly resemble the keywords. However, it would be safer not to mix up the variable names and the keywords. The keywords are also called Reserved words. There are only 32 keywords available in C. These are shown in the table below: .auto .else .register .union .break .enum .return .unsigned .case .char .const .continue .default .do .double .extern .float .for .goto .if .int .long .short .signed .size of .static .struct .switch .typedef .void .volatile .while . . . .

Note that compiler vendors (like Microsoft, Borland, etc.) provide their own keywords apart from the ones mentioned above. These include extended keywords like near, far, asm, etc. Though it has been suggested by the ANSI committee that every such compiler specific keyword should be preceded by two underscores (as in __asm), not every vendor follows this rule. Identifiers refer to the name of user-defined variables, array and functions. A variable should be essentially a sequence of letters and or digits and the variable name should begin with a character. Both uppercase and lowercase letters are permitted. The underscore character is also permitted in identifiers. INSTRUCTIONS There are basically three types of instructions in C: i. Type Declaration Instruction ii. Arithmetic Instruction iii. Control Instruction The purpose of each of these instructions is given below: Type declaration instruction To declare the type of variables used in a C program. Arithmetic instruction To perform arithmetic operations between constants and variables. Control instruction To control the sequence of execution of various statements in a C program. Type Declaration Instruction This instruction is used to declare the type of variables being used in the program. Any variable used in the program must be declared before using it in any statement. The type declaration statement is written after the main ( ) function. Therefore this requires one to know the different data types in C. These are: Size and Range of Data Types. 6 Pre pared by Z. Mwololo

Comp 111: Introduction to Programming


TYPE Char or Signed Char Unsigned Char Int or Signed int Unsigned int SIZE (Bits) 8 8 16 16 Range -128 to 127 0 to 255 -32768 to 32767 0 to 65535 -128 to 127 0 to 255 -2147483648 to 2147483647 0 to 4294967295 3.4 e-38 to 3.4 e+38 1.7e-308 to 1.7e+308 3.4 e-4932 to 3.4 e+4932

Short int or Signed short int 8 Unsigned short int Long int or signed long int Unsigned long int Float Double Long Double 8 32 32 32 64 80

Each data type has a format specifier which can be used with the input and output function which we will discuss soon. They are as follows: Specifier %c %d %e %f %o %s %x %X %a %p %ld Meaning Print a character Print an Integer Print float value in exponential form. Print float value Print octal value Print a string Print a hexadecimal integer (Unsigned) using lower case a F Print a hexadecimal integer (Unsigned) using upper case A F Print a unsigned integer. Print a pointer value long

The following fundamental data types and their equivalent keywords:


Data type Character Unsigned Character Signed Character Signed Integer Signed Short Integer Keyword Equivalent char unsigned char signed char signed int (or) int signed short int (or) short int (or) short

7 Pre pared by Z. Mwololo

Comp 111: Introduction to Programming

Signed Long Integer UnSigned Integer UnSigned Short Integer UnSigned Long Integer Floating Point Double Precision Floating Point Extended Double Precision Floating Point

signed long int (or) long int (or) long unsigned int (or) unsigned unsigned short int (or) unsigned short unsigned long int (or) unsigned long float double long double

The following are examples of type declaration instructions: Ex.: int bas ; float rs, grosssal ; char name, code ; There are several subtle variations of the type declaration instruction. These are discussed below: a) While declaring the type of variable we can also initialize it as shown below. int i = 10, j = 25; float a = 1.5, b = 1.99 + 2.4 * 1.44; b) The order in which we define the variables is sometimes important sometimes not. For example, int i = 10, j = 25 ; Is same as int j = 25, j = 10; However, float a = 1.5, b = a + 3.1; is alright, but float b = a + 3.1, a = 1.5 ; is not. This is because here we are trying to use a even before defining it. c) The following statements would work int a, b, c, d ; a = b = c = 10 ; However, the following statement would not work int a = b = c = d = 10 ; Once again we are trying to use b (to assign to a) before defining it. User defined type declaration 8 Pre pared by Z. Mwololo

Comp 111: Introduction to Programming In C language a user can define an identifier that represents an existing data type. The user defined data type identifier can later be used to declare variables. This can be through the use of the keyword typedef. The general syntax is typedef type identifier; here type represents existing data type and identifier refers to the row name given to the data type. Example: typedef int salary; typedef float average; Here salary symbolizes int and average symbolizes float. They can be later used to declare variables as follows: Units dept1, dept2; Average section1, section2; Therefore dept1 and dept2 are indirectly declared as integer data type and section1 and section2 are indirectly float data type. The second type of user defined data type is enumerated data type which is defined by the use of the keyword Enum as follows. Enum identifier {value1, value2 . Value n}; The identifier is a user defined enumerated data type which can be used to declare variables that have one of the values enclosed within the braces. After the definition we can declare variables to be of this new type as below. enum identifier V1, V2, V3, Vn The enumerated variables V1, V2, .. Vn can have only one of the values value1, value2 .. value n Example: enum day {Monday, Tuesday, . Sunday}; enum day week_st, week end; week_st = Monday; week_end = Friday; Arithmetic Instruction A C arithmetic instruction consists of a variable name on the left hand side of = and variable names & constants on the right hand side of =. The variables and constants appearing on the right hand side of = are connected by arithmetic operators like +, -, *, and /. Before proceeding we should know the different operators used in C. Operators Introduction An operator is a symbol which helps the user to command the computer to do a certain mathematical or logical manipulations. Operators are used in C language program to operate on data and variables. C has a rich set of operators which can be classified as 9 Pre pared by Z. Mwololo

Comp 111: Introduction to Programming

i. ii. iii. iv. v. vi. vii.

Arithmetic operators Relational Operators Logical Operators Assignment Operators Increments and Decrement Operators Conditional Operators Bitwise Operators Special Operators

1) Arithmetic Operators All the basic arithmetic operations can be carried out in C. All the operators have almost the same meaning as in other languages. Both unary and binary operations are available in C language. Unary operations operate on a singe operand, therefore the number 5 when operated by unary will have the value 5. Arithmetic Operators Operator Meaning + * / % Addition or Unary Plus Subtraction or Unary Minus Multiplication Division Modulus Operator

Examples of arithmetic operators are x+y x-y -x + y a*b+c -a * b etc. Here a, b, c, x, y are known as operands. The modulus operator is a special operator in C language which evaluates the remainder of the operands after division. Integer Arithmetic When an arithmetic operation is performed on two whole numbers or integers than such an operation is called as integer arithmetic. It always gives an integer as the result. Let x = 27 and y = 5 be 2 integer numbers. Then the integer operation leads to the following results. x + y = 32 x y = 22 x * y = 115 x%y=2 10 Pre pared by Z. Mwololo

Comp 111: Introduction to Programming x/y=5 In integer division the fractional part is truncated. Floating point arithmetic When an arithmetic operation is preformed on two real numbers or fraction numbers such an operation is called floating point arithmetic. The floating point results can be truncated according to the properties requirement. The remainder operator is not applicable for floating point arithmetic operands. Let x = 14.0 and y = 4.0 then x + y = 18.0 x y = 10.0 x * y = 56.0 x / y = 3.50 Mixed mode arithmetic When one of the operand is real and other is an integer and if the arithmetic operation is carried out on these 2 operands then it is called as mixed mode arithmetic. If any one operand is of real type then the result will always be real thus 15/10.0 = 1.5 2) Relational Operators Often it is required to compare the relationship between operands and bring out a decision in a program accordingly. This is when the relational operator comes into picture. C supports the following relational operators. Operator Meaning < <= > >= == != is less than is less than or equal to is greater than is greater than or equal to is equal to is not equal to

It is required to compare the marks of 2 students, salary of 2 persons, we can compare them using relational operators. A simple relational expression contains only one relational operator and takes the following form. exp1 relational operator exp2 where exp1 and exp2 are expressions, which may be simple constants, variables or combination of them. Given below is a list of examples of relational expressions and evaluated values. 11 Pre pared by Z. Mwololo

Comp 111: Introduction to Programming

6.5 <= 25 TRUE -65 > 0 FALSE 10 < 7 + 5 TRUE Relational expressions are used in decision making statements of C language such as if, while and for statements to decide the course of action of a running program. There result is either TRUE or FALSE 3) Logical Operators C has the following logical operators; they compare or evaluate logical and relational expressions. Operator Meaning && || ! Logical AND Logical OR Logical NOT

Logical AND (&&) This operator is used to evaluate 2 conditions or expressions with relational operators simultaneously. If both the expressions to the left and to the right of the logical operator is true then the whole compound expression is true. Example a > b && x = = 10 The expression to the left is a > b and that on the right is x == 10 the whole expression is true only if both expressions are true i.e., if a is greater than b and x is equal to 10. Logical OR (||) The logical OR is used to combine 2 expressions or the condition evaluates to true if any one of the 2 expressions is true. Example a < m || a < n the expression evaluates to true if any one of them is true or if both of them are true. It evaluates to true if a is less than either m or n and when a is less than both m and n. Logical NOT (!) The logical not operator takes single expression and evaluates to true if the expression is false and evaluates to false if the expression is true. In other words it just reverses the value of the expression. For example ! (x >= y) the NOT expression evaluates to true only if the value of x is neither greater than or equal to y 12 Pre pared by Z. Mwololo

Comp 111: Introduction to Programming

4) Assignment Operators The Assignment Operator evaluates an expression on the right of the expression and substitutes it to the value or variable on the left of the expression. Example x=a+b Here the value of a + b is evaluated and substituted to the variable x. In addition; C has a set of shorthand assignment operators of the form. var oper = exp; Here var is a variable, exp is an expression and oper is a C binary arithmetic operator. The operator oper = is known as shorthand assignment operator

C Language Operator Precedence Chart


Operator precedence describes the order in which C reads expressions. For example, the expression a=4+b*2 contains two operations, an addition and a multiplication. Does the C compiler evaluate 4+b first, then multiply the result by 2, or does it evaluate b*2 first, then add 4 to the result? The operator precedence chart contains the answers. Operators higher in the chart have a higher precedence, meaning that the C compiler evaluates them first. Operators on the same line in the chart have the same precedence, and the "Associativity" column on the right gives their evaluation order. Operator Type Primary Expression Operators Unary Operators Binary Operators Operator Precedence Chart Operator
() [] . -> expr++ expr-* & + - ! ~ ++expr --expr (typecast) sizeof() * / % + >> << < > <= >= == != & ^ | && || ?: = += -= *= /= %= >>= <<= &= ^= |=

Associativity left-to-right right-to-left left-to-right

Ternary Operator Assignment Operators

right-to-left right-to-left
Pre

13 pared by Z. Mwololo

Comp 111: Introduction to Programming

Comma

left-to-right

Though Arithmetic instructions look simple to use one often commits mistakes in writing them. Let us take a closer look at these statements. Note the following points carefully. a. C allows only one variable on left-hand side of =. That is, z = k * l is legal, whereas k * l = z is illegal. b. In addition to the division operator C also provides a modular division operator. This operator returns the remainder on dividing one integer with another. Thus the expression 10 / 2 yields 5, whereas, 10 % 2 yields 0. Note that the modulus operator (%) cannot be applied on a float. Also note that on using % the sign of the remainder is always same as the sign of the numerator. Thus 5 % 2 yields 1, whereas, 5 % -2 yields 1. c. An arithmetic instruction is often used for storing character constants in character variables. char a, b, d ; a = 'F' ; b = 'G' ; d = '+' ; When we do this the ASCII values of the characters are stored in the variables. ASCII values are used to represent any character in memory. The ASCII values of F and G are 70 and 71. Arithmetic operations can be performed on ints, float s and chars. Thus the statements, char x, y ; int z ; x = 'a'; y = 'b'; z = x + y; Are perfectly valid, since the addition is performed on the ASCII values of the characters and not on characters themselves. The ASCII values of a and b are 97 and 98, and hence can definitely be added. e. No operator is assumed to be present. It must be written explicitly. In the following example, the multiplication operator after b must be explicitly written. a = c.d.b(xy) f. usual arithmetic statement b = c * d * b * ( x * y ) C statement

d.

Unlike other high level languages, there is no operator for performing exponentiation operation. Thus following statements are invalid. a = 3 ** 2 ; b = 3 ^ 2 ; If we want to do the exponentiation we can get it done this way: #include <math.h> main( ) { int a ; a = pow ( 3, 2 ) ; 14 Pre

pared by Z. Mwololo

Comp 111: Introduction to Programming printf ( %d, a ) ; } Here pow ( ) function is a standard library function. It is being used to raise 3 to the power of 2. #include <math.h> is a preprocessor directive. It is being used here to ensure that the pow( )function works correctly.

C Programming - Managing Input and Output Operation


Introduction One of the essential operations performed in C language programs is to provide input values to the program and output the data produced by the program to a standard output device. We can assign values to variable through assignment statements such as x = 5 a = 0 ; and so on. Another method is to use the input function scanf ( ) which can be used to read data from a key board. For outputting results we use the function printf () which sends results out to a terminal. There exists several functions in C language that can carry out input output operations. These functions are collectively known as standard Input/Output Library. Each program that uses standard input / out put function must contain the statement. # include < stdio.h > at the beginning. Single character input output: The basic operation done in input output is to read a character from the standard input device such as the keyboard and to output or writing it to the output unit usually the screen. The getchar function can be used to read a character from the standard input device. The scanf can also be used to achieve the function. The getchar has the following form. Variable name = getchar: Variable name is a valid C variable, that has been declared already and that possess the type char. Example program :
# include < stdio.h > // assigns stdio-h header file to your program void main ( ) // Indicates the starting point of the program. { char C, // variable declaration printf (Type one character:) ; // message to user C = getchar () ; // get a character from key board and Stores it in variable C. Printf ( The character you typed is = %c, C) ; // output } // Statement which displays value of C on // Standard screen.

The putchar function which in analogous to getchar function can be used for writing characters one at a time to the output terminal. The general form is putchar (variable name); 15 Pre pared by Z. Mwololo

Comp 111: Introduction to Programming

Where variable is a valid C type variable that has already been declared Ex:Putchar ( ); Displays the value stored in variable C to the standard screen. Program shows the use of getchar function in an interactive environment. #include < stdio.h > void main ( ) // Beginning of main function. { char in; // character declaration of variable in. printf ( please enter one character); // message to user in = getchar ( ) ; // assign the keyboard input value to in. putchar (in); // out put in value to standard screen. } String input and output: The gets function relieves the string from standard input device while put S outputs the string to the standard output device. A strong is an array or set of characters. The function gets accepts the name of the string as a parameter, and fills the string with characters that are input from the keyboard till newline character is encountered. (That is till we press the enter key). All the end function gets appends a null terminator as must be done to any string and returns. The puts function displays the contents stored in its parameter on the standard screen. The standard form of the gets function is gets (str) Here "str" is a string variable. NOTE: It is recommended NOT to make use of gets() function. It is unsafe and can even crash the C program itself. Above description is for theoretical illustration purpose only. The standard form for the puts character is puts (str) Where str is a string variable. Example program (Involving both gets and puts) # include < stdio.h > Void main ( ) { char s [80]; printf (Type a string less than 80 characters:); gets (s); 16 Pre pared by Z. Mwololo

Comp 111: Introduction to Programming printf (The string types is:); puts(s); } } Formatted Input For Scanf: The formatted input refers to input data that has been arranged in a particular format. Input values are generally taken by using the scanf function. The scanf function has the general form. Scanf (control string, arg1, arg2, arg3 .argn); The format field is specified by the control string and the arguments arg1, arg2 .argn specifies the address of location where address is to be stored. The control string specifies the field format which includes format specifications and optional number specifying field width and the conversion character % and also blanks, tabs and newlines. The Blanks tabs and newlines are ignored by compiler. The conversion character % is followed by the type of data that is to be assigned to variable of the assignment. The field width specifier is optional. The general format for reading a integer number is %xd Here percent sign (%) denotes that a specifier for conversion follows and x is an integer number which specifies the width of the field of the number that is being read. The data type character d indicates that the number should be read in integer mode. Example: scanf (%3d %4d, &sum1, &sum2); If the values input are 175 and 1342 here value 175 is assigned to sum1 and 1342 to sum 2. Suppose the input data was follows 1342 and 175. The number 134 will be assigned to sum1 and sum2 has the value 2 because of %3d the number 1342 will be cut to 134 and the remaining part is assigned to second variable sum2. If floating point numbers are assigned then the decimal or fractional part is skipped by the computer. To read the long integer data type we can use conversion specifier % ld. Input specifications for real number: Field specifications are not to be use while representing a real number therefore real numbers are specified in a straight forward manner using % f specifier. The general format of specifying a real number input is Scanf (% f , &variable); Example: Scanf (%f %f % f, &a, &b, &c); With the input data 17 Pre pared by Z. Mwololo

Comp 111: Introduction to Programming 321.76, 4.321, 678 The values 321.76 is assigned to a , 4.321 to b & 678 to C. If the number input is a double data type then the format specifier should be % lf instead of %f. Input specifications for a character. Single character or strings can be input by using the character specifiers. The general format is % xc or %xs Where C and S represent character and string respectively and x represents the field width. The address operator need not be specified while we input strings. Example : Scanf (%C %15C, &ch, nname): Here suppose the input given is a, Robert then a is assigned to ch and name will be assigned to Robert. Printing One Line: printf(); The most simple output statement can be produced in C Language by using printf statement. It allows you to display information required to the user and also prints the variables we can also format the output and provide text labels. The simple statement such as Printf (Enter 2 numbers); Prompts the message enclosed in the quotation to be displayed. A simple program to illustrate the use of printf statement:#include < stdio.h > main ( ) { printf (Hello!); printf (Welcome to the world of Engineering!); } Output: Hello! Welcome to the world of Engineering. Both the messages appear in the output as if a single statement. If you wish to print the second message to the beginning of next line, a new line character must be placed inside the quotation marks. 18 Pre pared by Z. Mwololo

Comp 111: Introduction to Programming For Example : printf (Hello!\n); OR printf (\n Welcome to the world of Engineering); Conversion Strings and Specifiers: The printf ( ) function is quite flexible. It allows a variable number of arguments, labels and sophisticated formatting of output. The general form of the printf ( ) function is Syntax Printf (conversion string, variable list); The conversion string includes all the text labels, escape character and conversion specifiers required for the desired output. The variable includes the entire variable to be printed in order they are to be printed. There must be a conversion specifies after each variable. E. g. a=2; b=4; c=a+b; Printf (the total is %d, c); The Structure of C Program Before we begin with our first C program do remember the following rules that are applicable to all C programs: i. Each instruction in a C program is written as a separate statement. Therefore a complete C program would comprise of a series of statements. ii. The statements in a program must appear in the same order in which we wish them to be executed; unless of course the logic of the problem demands a deliberate jump or transfer of control to a statement, which is out of sequence. iii. Blank spaces may be inserted between two words to improve the readability of the statement. However, no blank spaces are allowed within a variable, constant or keyword. iv. All statements are entered in small case letters. v. C has no specific rules for the position at which a statement is to be written. Thats why it is often called a free-form language. vi. Every C statement must end with a; thus ; acts as a statement terminator. Every C program has the following structure: #include<stdio.h> Main () { Statement; Statement; } Where #include is a directive statement which helps the preprocessor to include the header files in the stdio.h which means standard Input Output. Since in the program we have to use the functions scanf () 19 Pre pared by Z. Mwololo

Comp 111: Introduction to Programming and printf () these functions are usually pre-defined in the header file stdio.h. The main () is the statement from which the compiler begins to execute your program. Then starting braces {after which you include the statements to be executed after completing the statements you close the braces }. Let us now write down our first C program. It would simply calculate simple interest for a set of values representing principle, number of years and rate of interest. /* Calculation of simple interest */ /* Author gekay Date: 25/05/2004 */ #include<stdio.h> main ( ) { int p, n ; float r, si ; p = 1000; n = 3; r = 8.5; /* formula for simple interest */ si = p * n * r / 100; printf (%f, si ) ; } Now a few useful tips about the program... Comment about the program should be enclosed within /* */. For example, the first two statements in our program are comments. Though comments are not necessary, it is a good practice to begin a program with a comment indicating the purpose of the program, its author and the date on which the program was written. Any number of comments can be written at any place in the program. For example, a comment can be written before the statement, after the statement or within the statement as shown below: /* formula */ si = p * n * r / 100; si = p * n * r / 100; /* formula */ si = p * n * r / /* formula */ 100 ; Sometimes it is not so obvious as to what a particular statement in a program accomplishes. At such times it is worthwhile mentioning the purpose of the statement (or a set of statements) using a comment. For example: /* formula for simple interest */ si = p * n * r / 100; Often programmers seem to ignore writing of comments. But when a team is building big software well commented code is almost essential for other team members to understand it. The normal language rules do not apply to text written within /*... */. Thus we can type this text in small case, capital or a combination. This is because the comments are solely given for the understanding of the programmer or the fellow programmers and are completely ignored by the compiler. NB: After writing your program you are supposed to compile it then execute. The row code is called the source code, then after compiling it is termed as the executable code. Therefore before compiling one is supposed to save the source code with the extension .C. Thus: sinterest.C, add.c, etc. usually the executable file is stored with the extension .exe. Control Instructions in C As the name suggests the Control Instructions enable us to specify the order in which the various instructions in a program are to be executed by the computer. In other words the control instructions determine the flow of control in a program. There are four types of control instructions in C. They are: i. Sequence Control Instruction 20 Pre pared by Z. Mwololo

Comp 111: Introduction to Programming ii. iii. iv. Selection or Decision Control Instruction Repetition or Loop Control Instruction Case Control Instruction

The Sequence control instruction ensures that the instructions are executed in the same order in which they appear in the program. Decision and Case control instructions allow the computer to take a decision as to which instruction is to be executed next. The Loop control instruction helps computer to execute a group of statements repeatedly.

DECISION CONTROL STATEMENTS We all need to alter our actions in the face of changing circumstances. If the weather is fine, then I will go for a stroll. If the highway is busy I would take a diversion. If the pitch takes spin, we would win the match. If she says no, I would look elsewhere. If you like this book, I would write the next edition. You can notice that all these decisions depend on some condition being met. C language too must be able to perform different sets of actions depending on the circumstances. In fact this is what makes it worth its salt. C has three major decision making instructions The if statement The if-else statement The switch statement. A fourth, somewhat less important structure is the one that uses conditional operators. In the programs written previously we have used sequence control structure in which the various steps are executed sequentially, i.e. in the same order in which they appear in the program. In fact to execute the instructions sequentially, we dont have to do anything at all. By default the instructions in a program are executed sequentially. However, in serious programming situations, seldom do we want the instructions to be executed sequentially. Many a times, we want a set of instructions to be executed in one situation, and an entirely different set of instructions to be executed in another situation. This kind of situation is dealt in C programs using a decision control instruction.

The if Statement
Like most languages, C uses the keyword if to implement the decision control instruction. The general form of if statement looks like this: if (condition) { statement ; } The keyword if tells the compiler that what follows is a decision control instruction. The condition following the keyword if is always enclosed within a pair of parentheses. If the condition, whatever it is, is true, then the statement is executed. If the condition is not true then the statement is not executed; instead the program skips past it. But how do we express the condition itself in C? And how do we evaluate its truth or falsity? As a general rule, we express a condition using Cs relational operators. The relational operators allow us to compare two values to see whether they are equal to each other, unequal, or whether one is greater than the other. Here is a simple program, which demonstrates the use of if and the relational operators. Example 1 /* Demonstration of if statement */ 21 Pre pared by Z. Mwololo

Comp 111: Introduction to Programming

main( ) { int num ; printf ( "Enter a number less than 10 " ) ; scanf ( "%d", &num ) ; if ( num <= 10 ) printf ( "What an obedient servant you are !" ) ; }
On execution of this program, if you type a number less than or equal to 10, you get a message on the screen through printf( ). If you type some other number the program doesnt do anything. Example 2 While purchasing certain items, a discount of 10% is offered if the quantity purchased is more than 1000. If quantity and price per item are input through the keyboard, write a program to calculate the total expenses. /* Calculation of total expenses */

main ( ) { int qty, dis = 0; float rate, tot; printf (Enter quantity and rate " ) ; scanf (%d %f", &qty, &rate) ; if ( qty > 1000 ) dis = 10 ; tot = ( qty * rate ) - ( qty * rate * dis / 100 ) ; printf ( "Total expenses = Rs. %f", tot ) ; }
Here is some sample interaction with the program. Enter quantity and rate 1200 15.50 Total expenses = Rs. 16740.000000 Enter quantity and rate 200 15.50 Total expenses = Rs. 3100.000000 In the first run of the program, the condition evaluates to true, as 1200 (value of qty) is greater than 1000. Therefore, the variable dis, which was earlier set to 0, now gets a new value 10. Using this new value total expense are calculated and printed. In the second run the condition evaluates to false, as 200 (the value of qty) isnt greater than 1000. Thus, dis, which is earlier set to 0, remains 0, and hence the expression after the minus sign evaluates to zero, thereby offering no discount. Is the statement dis = 0 necessary? The answer is yes, since in C, a variable if not specifically initialized contains some unpredictable value (garbage value). The if statement can take the form:

if (expression)
statement; 22 Pre pared by Z. Mwololo

Comp 111: Introduction to Programming Here the expression can be any valid expression including a relational expression. We can even use arithmetic expressions in the if statement. For example all the following if statements are valid if ( 3 + 2 % 5 ) printf ( "This works" ) ; if ( a = 10 ) printf ( "Even this works" ) ; if ( -5 ) printf ( "Surprisingly even this works" ) ; Note that in C a non-zero value is considered to be true, whereas a 0 is considered to be false. In the first if, the expression evaluates to 5and since 5is non-zero it is considered to be true. Hence the printf ( ) gets executed. In the second if, 10 gets assigned to a so the if is now reduced to if (a) or if (10). Since 10 is non-zero, it is true hence again printf ( ) goes to work. In the third if, -5 is a non-zero number, hence true. So again printf ( ) goes to work. In place of -5 even if a float like 3.14 were used it would be considered to be true. So the issue is not whether the number is integer or float, or whether it is positive or negative. Issue is whether it is zero or non-zero.

Multiple Statements within if


It may so happen that in a program we want more than one statement to be executed if the expression following if is satisfied. If such multiple statements are to be executed then they must be placed within a pair of braces as illustrated in the following example. Example 3: The current year and the year in which the employee joined the organization are entered through the keyboard. If the number of years for which the employee has served the organization is greater than 3 then a bonus of Ksh. 2500/- is given to the employee. If the years of service are not greater than 3, then the program should do nothing. /* Calculation of bonus */

main( ) { int bonus, cy, yoj, yr_of_ser ; printf ( "Enter current year and year of joining " ) ; scanf ( "%d %d", &cy, &yoj ) ; yr_of_ser = cy - yoj ; if ( yr_of_ser > 3 ) { bonus = 2500 ; printf ( "Bonus = Rs. %d", bonus ) ; } }
Observe that here the two statements to be executed on satisfaction of the condition have been enclosed within a pair of braces. If a pair of braces is not used then the C compiler assumes that the programmer wants only the immediately next statement after the if to be executed on satisfaction of the condition. In other words we can say that the default scope of the if statement is the immediately next statement after it.

The if-else Statement


23 Pre pared by Z. Mwololo

Comp 111: Introduction to Programming The if statement by itself will execute a single statement, or a group of statements, when the expression following if evaluates to true. It does nothing when the expression evaluates to false. Can we execute one group of statements if the expression evaluates to true and another group of statements if the expression evaluates to false? Of course! This is what the purpose of the else statement that is demonstrated in the following example: Example 2.3: In a company an employee is paid as under: If his basic salary is less than Rs. 1500, then HRA = 10% of basic salary and DA = 90% of basic salary. If his salary is either equal to or above Rs. 1500, then HRA = Rs. 500 and DA = 98% of basic salary. If the employee's salary is input through the keyboard write a program to find his gross salary. /* Calculation of gross salary */

main( ) { float bs, gs, da, hra ; printf ( "Enter basic salary " ) ; scanf ( "%f", &bs ) ; if ( bs < 1500 ) { hra = bs * 10 / 100 ; da = bs * 90 / 100 ; } else { hra = 500 ; da = bs * 98 / 100 ; } gs = bs + hra + da ; printf ( "gross salary = Rs. %f", gs ) ; }
A few points worth noting... The group of statements after the if up to and not including the else is called an if block. Similarly, the statements after the else form the else block. Notice that the else is written exactly below the if. The statements in the if block and those in the else block have been indented to the right. This formatting convention is followed to enable you to understand the working of the program better. Had there been only one statement to be executed in the if block and only one statement in the else block we could have dropped the pair of braces. As with the if statement, the default scope of else is also the statement immediately after the else. To override this default scope a pair of braces as shown in the above example must be used.

Nested if-elses
It is perfectly all right if we write an entire if-else construct within either the body of the if statement or the body of an else statement. This is called nesting of ifs. This is shown in the following program. /* A quick demo of nested if-else */ 24 Pre pared by Z. Mwololo

Comp 111: Introduction to Programming

main( ) { int i ; printf ( "Enter either 1 or 2 " ) ; scanf ( "%d", &i ) ; if ( i == 1 ); printf ( "You would go to heaven !" ) ; else { if ( i == 2 ) printf ( "Hell was created with you in mind" ) ; else printf (How about mother earth !" ) ; } }
Note that the second if-else construct is nested in the first else statement. If the condition in the first if statement is false, then the condition in the second if statement is checked. If it is false as well, then the final else statement is executed. You can see in the program how each time a if-else construct is nested within another if-else construct, it is also indented to add clarity to the program. Inculcate this habit of indentation; otherwise you would end up writing programs which nobody (you included) can understand easily at a later date. In the above program an if-else occurs within the else block of the first if statement. Similarly, in some other program an if-else may occur in the if block as well. There is no limit on how deeply the ifs and the elses can be nested.

Forms of if
The if statement can take any of the following forms: if ( condition ) do this ; if ( condition ) { do this ; and this ; } if ( condition ) do this ; else do this ; if ( condition ) { do this ; and this ; } else { do this ; and this ; } if ( condition ) 25 Pre pared by Z. Mwololo

Comp 111: Introduction to Programming do this ; else { if ( condition ) do this ; else { do this ; and this ; } } if ( condition ) { if ( condition ) do this ; else { do this ; and this ; } } else do this ; Example of a program using the logical operators: The marks obtained by a student in 5 different subjects are input through the keyboard. The student gets a grade as per the following rules: Percentage above or equal to 60 - A Percentage between 50 and 59 - B Percentage between 40 and 49 - C Percentage less than 40 Fail Write a program to calculate the grades obtained by the student. There are two ways in which we can write a program for this example. These methods are given below. /* Method I */

main( ) { int m1, m2, m3, m4, m5, per ; printf ( "Enter marks in five subjects " ) ; scanf ( "%d %d %d %d %d", &m1, &m2, &m3, &m4, &m5 ) ; per = ( m1 + m2 + m3 + m4 + m5 ) / 5 ; if ( per >= 60 ) printf ( "First division ") ; else { if ( per >= 50 ) printf ( "Second division" ) ; else {
26 Pre pared by Z. Mwololo

Comp 111: Introduction to Programming

if ( per >= 40 ) printf ( "Third division" ) ; else printf ( "Fail" ) ; } } }


This is a straight forward program. Observe that the program uses nested if-elses. This leads to three disadvantages: As the number of conditions go on increasing the level of indentation also goes on increasing. As a result the whole program creeps to the right. Care needs to be exercised to match the corresponding ifs and elses. Care needs to be exercised to match the corresponding pair of braces. All these three problems can be eliminated by usage of Logical operators. The following program illustrates this. /* Method II */

main( ) { int m1, m2, m3, m4, m5, per ; printf ("Enter marks in five subjects "); scanf ("%d %d %d %d %d", &m1, &m2, &m3, &m4, &m5); per = (m1 + m2 + m3 + m4 + m5) / 5; if (per >= 60) printf ("First division"); if (( per >= 50) && (per < 60)) printf ("Second division"); if ((per >= 40) && (per < 50)) printf ("Third division"); if(per < 40) printf ("Fail"); }
As can be seen from the second if statement, the && operator is used to combine two conditions. Second division gets printed if both the conditions evaluate to true. If one of the conditions evaluate to false then the whole thing is treated as false. Two distinct advantages can be cited in favor of this program: The matching (or do I say mismatching) of the ifs with their corresponding elses gets avoided, since there are no elses in this program. In spite of using several conditions, the program doesn't creep to the right. In the previous program the statements went on creeping to the right. This effect becomes more pronounced as the number of conditions goes on increasing. This would make the task of matching the ifs with their corresponding elses and matching of opening and closing braces that much more difficult.

The else if Clause


There is one more way in which we can write the program above. This involves usage of else if blocks as shown below: /* else if ladder demo */

main( )
27 Pre pared by Z. Mwololo

Comp 111: Introduction to Programming

{ int m1, m2, m3, m4, m5, per; per = ( m1+ m2 + m3 + m4+ m5 ) / per; if (per >= 60) printf ("First division"); else if (per >= 50) printf ("Second division"); else if (per >= 40) printf ("Third division"); else printf ("fail") ; }
You can note that this program reduces the indentation of the statements. In this case every else is associated with its previous if. The last else goes to work only if all the conditions fail. Even in else if ladder the last else is optional. Note that the else if clause is nothing different. It is just a way of rearranging the else with the if that follows it. This would be evident if you look at the following code: if( i==2) printf(with you); else { If(j==2) printf(All the time); } OR if( i==2) printf(with you); elseif(j==2) printf(All the time); Another place where logical operators are useful is when we want to write programs for complicated logics that ultimately boil down to only two answers. For example, consider the following example: Example: A company insures its drivers in the following cases: If the driver is married. If the driver is unmarried, male & above 30 years of age. If the driver is unmarried, female & above 25 years of age. In all other cases the driver is not insured. If the marital status, sex and age of the driver are the inputs, write a program to determine whether the driver is to be insured or not. Here after checking a complicated set of instructions the final output of the program would be one of the twoEither the driver should be ensured or the driver should not be ensured. As mentioned above, since these are the only two outcomes this problem can be solved using logical operators. But before we do that let us write a program that does not make use of logical operators. /* Insurance of driver - without using logical operators */

main( )
28 Pre pared by Z. Mwololo

Comp 111: Introduction to Programming

{ char sex, ms ; int age ; printf ( "Enter age, sex, marital status " ) ; scanf ( "%d %c %c", &age, &sex, &ms ) ; if ( ms == 'M' ) printf ( "Driver is insured" ) ; else { if ( sex == 'M' ) { if ( age > 30 ) printf ( "Driver is insured" ) ; else printf ( "Driver is not insured" ) ; } else { if ( age > 25 ) printf ( "Driver is insured" ) ; else printf ( "Driver is not insured" ) ; } } }
From the program it is evident that we are required to match several ifs and elses and several pairs of braces. In a more real-life situation there would be more conditions to check leading to the program creeping to the right. Let us now see how to avoid these problems by using logical operators. As mentioned above, in this example we expect the answer to be either Driver is insured or Driver is not insured. If we list down all those cases in which the driver is insured, then they would be: Driver is married. Driver is an unmarried male above 30 years of age. Driver is an unmarried female above 25 years of age. Since all these cases lead to the driver being insured, they can be combined together using && and || as shown in the program below: /* Insurance of driver - using logical operators */

main( ) { char sex, ms ; int age ; printf ( "Enter age, sex, marital status " ) ; scanf ( "%d %c %c" &age, &sex, &ms ) ; if ( ( ms == 'M') || ( ms == 'U' && sex == 'M' && age > 30)||( ms == 'U' && sex == 'F' && age > 25 )) printf ("Driver is insured");
29 Pre pared by Z. Mwololo

Comp 111: Introduction to Programming

else printf ( "Driver is not insured" ) ; }


In this program it is important to note that: The driver will be insured only if one of the conditions enclosed in parentheses evaluates to true. For the second pair of parentheses to evaluate to true, each condition in the parentheses separated by && must evaluate to true. Even if one of the conditions in the second parentheses evaluates to false, then the whole of the second parentheses evaluates to false. The last two of the above arguments apply to third pair of parentheses as well. Thus we can conclude that the && and || are useful in the following programming situations: When it is to be tested whether a value falls within a particular range or not. When after testing several conditions the outcome is only one of the two answers (This problem is often called yes/no problem).

The switch Statement


This is another form of the multi way decision. It is well structured, but can only be used in certain cases where;

Only one variable is tested, all branches must depend on the value of that variable. The variable must be an integral type. (int, long, short or char). Each possible value of the variable can control a single branch. A final, catch all, default branch may optionally be used to trap all unspecified cases.

Hopefully an example will clarify things. This is a function which converts an integer into a vague description. It is useful where we are only concerned in measuring a quantity when it is quite small.
estimate(number) int number; /* Estimate a number as none, one, two, several, many */ { switch(number) { case 0 : printf("None\n"); break; case 1 : printf("One\n"); break; case 2 : printf("Two\n"); break; case 3 : case 4 : case 5 : printf("Several\n"); break; default : printf("Many\n");

30 Pre pared by Z. Mwololo

Comp 111: Introduction to Programming


break;

} }

Each interesting case is listed with a corresponding action. The break statement prevents any further statements from being executed by leaving the switch. Since case 3 and case 4 have no following break, they continue on allowing the same action for several values of number. The other main type of control statement is the loop. Loops allow a statement, or block of statements, to be repeated. Computers are very good at repeating simple tasks many times, the loop is C's way of achieving this. The Conditional Operators
The conditional operators ? and : are sometimes called ternary operators since they take three arguments. In fact, they form a kind of foreshortened if-then-else. Their general form is, expression 1 ? expression 2 : expression 3 What this expression says is: if expression 1 is true (that is, if its value is non-zero), then the value returned will be expression 2, otherwise the value returned will be expression 3. Let us understand this with the help of a few examples: i.

int x, y ; scanf ( "%d", &x ) ; y = ( x > 5 ? 3 : 4 ) ;


This statement will store 3 in y if x is greater than 5, otherwise it will store 4 in y. The equivalent if statement will be,

if ( x > 5 ) y = 3; else y = 4 ; ii. char a ; int y ; scanf ( "%c", &a ) ; y = ( a >= 65 && a <= 90 ? 1 : 0 ) ;
Here 1 would be assigned to y if a >=65 && a <=90 evaluates to true, otherwise 0 would be assigned. The following points may be noted about the conditional operators: Its not necessary that the conditional operators should be used only in arithmetic statements. This is illustrated in the following examples: Ex.:

int i ; scanf ( "%d", &i ); (i==1 ?printf("Paul") : printf ( "All and sundry")) ;
Ex.:

char a = 'z' ; printf ( "%c" , ( a >= 'a' ? a : '!' ) ) ;


The conditional operators can be nested as shown below. 31 Pre pared by Z. Mwololo

Comp 111: Introduction to Programming

int big, a, b, c ; big = (a > b ? (a > c ? 3: 4) : (b > c ? 6: 8));


Check out the following conditional expression:

a > b ? g = a : g = b ;
This will give you an error Lvalue Required. The error can be overcome by enclosing the statement in the : part within a pair of parenthesis. This is shown below:

a > b ? g = a : ( g = b );
In absence of parentheses the compiler believes that b is being assigned to the result of the expression to the left of second =. Hence it reports an error. The limitation of the conditional operators is that after the ?or after the : only one C statement can occur. In practice rarely is this the requirement. Therefore, in serious C programming conditional operators arent as frequently used as the if-else.

Loops
The versatility of the computer lies in its ability to perform a set of instructions repeatedly. This involves repeating some portion of the program either a specified number of times or until a particular condition is being satisfied. This repetitive operation is done through a loop control instruction. There are three methods by way of which we can repeat a part of a program. They are: Using a for statement Using a while statement Using a do-while statement

The While Loop It is often used if one wants to do something a fixed number of times. Perhaps you want to calculate gross salaries of ten different persons, or you want to convert temperatures from centigrade to Fahrenheit for 15 different cities. The while loop is, ideally suited for such cases. For example: /* Calculation of simple interest for 3 sets of p, n and r */ main( ) { int p, n, count ; float r, si ; count=1; while ( count <= 3 ) { printf ( "\nEnter values of p, n and r " ) ; scanf(%d %d %f", &p, &n, &r ) ; si= p* n * r / 100 ; printf ( "Simple interest = Rs. %f", si ) ; count=count+1 ; } }

The do while Loop


32 Pre pared by Z. Mwololo

Comp 111: Introduction to Programming

This is very similar to the while loop except that the test occurs at the end of the loop body. This guarantees that the loop is executed at least once before continuing. Such a setup is frequently used where data is to be read. The test then verifies the data, and loops back to read again if it was unacceptable. The general syntax is: do { Statements; } while (condition);
do { printf("Enter 1 for yes, 0 for no :"); scanf("%d", &input_value); } while (input_value != 1 && input_value != 0);

The for Loop


The for loop works well where the number of iterations of the loop is known before the loop is entered. The head of the loop consists of three parts separated by semicolons.

The first is run before the loop is entered. This is usually the initialization of the loop variable. The second is a test, the loop is exited when this returns false.

The third is a statement to be run every time the loop body is completed. This is usually an increment of the loop counter. The general syntax is : for (initialize; condition; increment/ decrement) { Statements; }

The example is a function which calculates the average of the numbers stored in an array. The function takes the array and the number of elements as arguments.
float average(float array[], int count) { float total = 0.0; int i; for(i = 0; i < count; i++) total += array[i]; return(total / count); }

The for loop ensures that the correct number of array elements are added up before calculating the average. The three statements at the head of a for loop usually do just one thing each, however any of them can be left blank. A blank first or last statement will mean no initialization or running increment. A blank comparison statement will always be treated as true. This will cause the loop
33 Pre pared by Z. Mwololo

Comp 111: Introduction to Programming

to run indefinitely unless interrupted by some other means. This might be a return or a break statement. It is also possible to squeeze several statements into the first or third position, separating them with commas. This allows a loop with more than one controlling variable. The example below illustrates the definition of such a loop, with variables hi and lo starting at 100 and 0 respectively and converging.
for (hi = 100, lo = 0; hi >= lo; hi--, lo++)

The for loop is extremely flexible and allows many types of program behaviour to be specified simply and quickly.

The break Statement


We have already met break in the discussion of the switch statement. It is used to exit from a loop or a switch, control passing to the first statement beyond the loop or a switch. With loops, break can be used to force an early exit from the loop, or to implement a loop with a test to exit in the middle of the loop body. A break within a loop should always be protected within an if statement which provides the test to control the exit condition.

The continue Statement


This is similar to break but is encountered less frequently. It only works within loops where its effect is to force an immediate jump to the loop control statement.

In a while loop, jump to the test statement. In a do while loop, jump to the test statement. In a for loop, jump to the test, and perform the iteration. Like a break, continue should be protected by an if statement. You are unlikely to use it very often.

Functions in C
A function in C language is a block of code that performs a specific task. It has a name and it is reusable i.e. it can be executed from as many different parts in a C Program as required. It also optionally returns a value to the calling program So function in a C program has some properties discussed below.

Every function has a unique name. This name is used to call function from main() function. A function can be called from within another function. A function is independent and it can perform its task without intervention from or interfering with other parts of the program.

34 Pre pared by Z. Mwololo

Comp 111: Introduction to Programming

A function performs a specific task. A task is a distinct job that your program must perform as a part of its overall operation, such as adding two or more integer, sorting an array into numerical order, or calculating a cube root etc. A function returns a value to the calling program. This is optional and depends upon the task your function is going to accomplish. Suppose you want to just show few lines through function then it is not necessary to return a value. But if you are calculating area of rectangle and wanted to use result somewhere in program then you have to send back (return) value to the calling function.

C language is collection of various inbuilt functions. If you have written a program in C then it is evident that you have used Cs inbuilt functions. Printf, scanf, clrscr etc. all are Cs inbuilt functions.

Structure of a Function
A general form of a C function looks like this: <return type> FunctionName (Argument1, Argument2, Argument3) { Statement1; Statement2; Statement3; } An example of function. int sum (int x, int y) { int result; result = x + y; return (result); }

Example of a simple function to add two integers.


1. #include<stdio.h> 2. #include<conio.h> 3. void add(int x, int y) 4. { 5. int result; 6. result = x+y; 7. printf("Sum of %d and %d is %d.\n\n",x,y,result);
35 Pre pared by Z. Mwololo

Comp 111: Introduction to Programming

8. } 9. void main() 10. { 11. clrscr(); 12. add(10,15); 13. add(55,64); 14. add(168,325); 15. getch(); 16. }

Explanation
Before I explain, let me give you an overview of above c program code. This is a very simple program which has only function named add() . This add() function takes two values as arguments, adds those two values and prints the result. Line 3-8 is a function block of the program. Line no. 3 is the header of function, void is return type of function, add is function name and (int x, int y) are variable which can hold integer values to x and y respectively. When we call function, line no. 12, 13, 14, we need to send two integer values as its argument. Then these two values get stored in variable x and y of line no. 3. Now we have two values to perform addition; in line no. 5 there is an integer declaration named result. This integer will store the sum of x and y (please see line no. 6). Line no. 7 simply prints the result with message. Now imagine the same program without using function. We have called add() function three times, to get the same output without using function we have to write Line no. 6 & 7 three time. If you want to add more value later in the program then again you have to type those two lines. Above example is a small and simple program so it does not appear great to use function. But assume a function consist 20 30 or more lines then it would not be wise to write same block of code wherever we need them. In such cases functions come handy, declare once, use wherever you want.

Advantages of using functions:


There are many advantages in using functions in a program they are: 1. It makes possible top down modular programming. In this style of programming, the high level logic of the overall problem is solved first while the details of each lower level functions is addressed later. 2. The length of the source program can be reduced by using functions at appropriate places.
36 Pre pared by Z. Mwololo

Comp 111: Introduction to Programming 3. It becomes uncomplicated to locate and separate a faculty function for further study.

4. A function may be used later by many other programs this means that a c programmer can use function written by others, instead of starting over from scratch. 5. A function can be used to keep away from rewriting the same block of codes which we are going use two or more locations in a program. This is especially useful if the code involved is long or complicated.

Types of functions:
A function may belong to any one of the following categories: 1. 2. 3. 4. 5. Functions with no arguments and no return values. Functions with arguments and no return values. Functions with arguments and return values. Functions that return multiple values. Functions with no arguments and return values.

1. Functions with no arguments and no return value.


A C function without any arguments means you cannot pass data (values like int, char etc) to the called function. Similarly, function with no return type does not pass back data to the calling function. It is one of the simplest types of function in C. This type of function which does not return any value cannot be used in an expression it can be used only as independent statement. Lets have an example to illustrate this. 1. #include<stdio.h> 2. #include<conio.h> 3. void printline() 4. { 5. int i; 6. printf("\n"); 7. for(i=0;i<30;i++) 8. { 9. printf("-"); 10. } 11. printf("\n"); 12. } 13. void main() 14. { 15. clrscr(); 16. printf("Welcome to function in C"); 17. printline(); 18. printf("Function easy to learn."); 19. printline();
37 Pre pared by Z. Mwololo

Comp 111: Introduction to Programming

20. getch(); 21. }

Source Code Explanation:


The above C program example illustrates that how to declare a function with no argument and no return type. I am going to explain only important lines only because this C program example is for those who are above the beginner level. Line 3-12: This C code block is a user defined function (UDF) whose task is to print a horizontal line. This is a simple function and a basic programmer can understand this. As you can see in line no. 7 I have declared a for loop which loops 30 time and prints - symbol continuously. Line 13-21: These line are main() function code block. Line no. 16 and 18 simply prints two different messages. And line no. 17 and 18 calls our user defined function printline().

2. Functions with arguments and no return value.


In our previous example what we have noticed that main() function has no control over the UDF printfline(), it cannot control its output. Whenever main() calls printline(), it simply prints line every time. So the result remains the same. A C function with arguments can perform much better than previous function type. This type of function can accept data from calling function. In other words, you send data to the called function from calling function but you cannot send result data back to the calling function. Rather, it displays the result on the terminal. But we can control the output of function by providing various values as arguments. Lets have an example to get it better. 1. #include<stdio.h> 2. #include<conio.h> 3. void add(int x, int y) 4. { 5. int result; 6. result = x+y; 7. printf("Sum of %d and %d is %d.\n\n",x,y,result); 8. } 9. void main() 10. { 11. clrscr(); 12. add(30,15); 13. add(63,49); 14. add(952,321); 15. getch(); 16. }
38 Pre pared by Z. Mwololo

Comp 111: Introduction to Programming

Source Code Explanation:


This program simply sends two integer arguments to the UDF add() which, further, calculates its sum and stores in another variable and then prints that value. So simple program to understand. Line 3-8: This C code block is add() which accepts two integer type arguments. This UDF also has a integer variable result which stores the sum of values passed by calling function (in this example main()). And line no. 7 simply prints the result along with argument variable values. Line 9-16: This code block is a main() function but only line no. 12, 13, 14 is important for us now. In these three lines we have called same function add() three times but with different values and each function call gives different output. So, you can see, we can control functions output by providing different integer parameters which was not possible in function type 1. This is the difference between function with no argument and function with argument.

3. Functions with arguments and return value.


This type of function can send arguments (data) from the calling function to the called function and wait for the result to be returned back from the called function back to the calling function. And this type of function is mostly used in programming world because it can do two way communications; it can accept data as arguments as well as can send back data as return value. The data returned by the function can be used later in our program for further calculations. 1. #include<stdio.h> 2. #include<conio.h> 3. int add(int x, int y) 4. { 5. int result; 6. result = x+y; 7. return(result); 8. } 9. void main() 10. { 11. int z; 12. clrscr(); 13. z = add(952,321); 14. printf("Result %d.\n\n",add(30,55)); 15. printf("Result %d.\n\n",z); 16. getch(); 17. }

Source Code Explanation:


39 Pre pared by Z. Mwololo

Comp 111: Introduction to Programming

This program sends two integer values (x and y) to the UDF add(), add() function adds these two values and sends back the result to the calling function (in this program to main() function). Later result is printed on the terminal. Line No. 3-8: Look line no. 3 carefully, it starts with int. This int is the return type of the function, means it can only return integer type data to the calling function. If you want any function to return character values then you must change this to char type. On line no. 7 you can see return statement, return is a keyword and in bracket we can give values which we want to return. You can assign any integer value to experiment with this return which ultimately will change its output. Do experiment with all you program and dont hesitate. Line No. 9-17: In this code block only line no. 13, 14 and 15 is important. We have declared an integer z which we used in line no. 13. Why we are using integer variable z here? You know that our UDF add() returns an integer value on calling. To store that value we have declared an integer value. We have passed 952, 321 to the add() function, which finally return 1273 as result. This value will be stored in z integer variable. Now we can use z to print its value or to other function. You will also notice some strange statement in line no. 14. Actually line no. 14 and 15 does the same job, in line no. 15 we have used an extra variable whereas on line no. 14 we directly printed the value without using any extra variable. This was simply to show you how we can use function in different ways.

4. Functions with no arguments but returns value.


We may need a function which does not take any argument but only returns values to the calling function then this type of function is useful. The best example of this type of function is getchar() library function which is declared in the header file stdio.h. We can declare a similar library function of own. Take a look. 1. #include<stdio.h> 2. #include<conio.h> 3. int send() 4. { 5. int no1; 6. printf("Enter a no : "); 7. scanf("%d",&no1); 8. return(no1); 9. } 10. void main() 11. { 12. int z; 13. clrscr(); 14. z = send(); 15. printf("\nYou entered : %d.", z);
40 Pre pared by Z. Mwololo

Comp 111: Introduction to Programming

16. getch(); 17. }

Source Code Explanation:


In this program we have a UDF which takes one integer as input from keyboard and sends back to the calling function. This is a very easy code to understand if you have followed all above code explanation. So I am not going to explain this code.

POINTERS What is a Pointer?


A pointer is a secondary data type (also known as derived data type) in C. It is built from one of the primary data types available in C language. Basically pointer contains memory address of other variable or function as their value. As pointer deals with memory address, it can be used to access and manipulate data stored in memory.

Benefits of using Pointer in C Program


Pointer is one of the most exciting features of C language and it has added power and flexibility to the language. Pointer is in C language because it offers following benefits to the programmers: 1. 2. 3. 4. 5. Pointers can handle arrays and data table efficiently. Pointers support dynamic memory management. Pointer helps to return multiple values from a function through function argument. Pointer increases program execution speed. Pointer is an efficient tool for manipulating structures, linked lists, queues stacks etc.

We can achieve these and much more benefits from pointer only if we can use it properly.

The * And & Operators


Take a look on the following declaration, int x=10; When we make such declaration how C compiler treat this statement: 1. Reserve memory space for this integer value.
41 Pre pared by Z. Mwololo

Comp 111: Introduction to Programming

2. Name this memory location as x. 3. Store the value 10 at this location. This can be illustrated by a simple diagram:

Integer variable location in memory. So when we declared an integer variable x and assigned value 10 then compiler occupied a 2 byte memory space at memory address 65325 and stored value 10 at that location. Compiler named this address x so that we can use x instead of 65325 in our program. But we can use address or variable in our program and both will point to the same value (example given below). The memory address of a variable could differ from PC to PC and entirely depends on available free space in memory at time of program execution. As this differs from PC to PC thus we cannot rely on that address (numeric value representing variable address) and we cannot use this address in our program. But have you noticed one thing that address is an integer. We can print address of any variable or function, following program shows how we can do that:

Address of variable example.


1. #include<stdio.h> 2. #include<conio.h> 3. 4. void main() 5. { 6. int i=9; 7. clrscr(); 8. 9. printf("Value of i : %d\n",i); 10. printf("Address of i : %u",&i); 11. 12. getch(); 13. } This is a very simple c program which prints value and address of an integer. But did you notice line no. 10 in above program? This line output the address of i variable and to get address of i variable we have used ampersand (&) operator. This operator is known as "Address of" operator and we already used this operator many times in our program, just recall scanf statement which
42 Pre pared by Z. Mwololo

Comp 111: Introduction to Programming

is used to accept input from computer keyboard. So when we use ampersand operator (&i) before any variable then we are instructing c compiler to return its address instead of value. Another operator we going to deal with in this entire pointer tutorial is "*" called "Value at address" operator. It is the same operator which we use for multiplication of numbers. As the name suggest, "value at address" operator returns value stored at particular address. The "value at address" operator also called indirection operator. Following example extends above C program and puts "value at address" operator in action.

Value at address (*) example


1. #include<stdio.h> 2. #include<conio.h> 3. 4. void main() 5. { 6. int i=9; 7. clrscr(); 8. 9. printf("Value of i : %d\n",i); 10. printf("Address of i : %u\n",&i); 11. printf("Value at address of i : %d",*(&i)); 12. 13. getch(); 14. } Now in this program notice line no. 11 and use of & and * operators also see the output of program which prints value of variable i and *(&i) same. This is how these two operator works.

Pointer with an example


Since this tutorial is already become lengthy so I am going to give a small example on how we can use pointer in our C program. Syntax: Example : datatype *pointer_name; int *iPtr; float *fPtr;

Pointer Example
43 Pre pared by Z. Mwololo

Comp 111: Introduction to Programming

1. #include<stdio.h> 2. #include<conio.h> 3. 4. void main() 5. { 6. int i=9, *ptr; 7. ptr=&i; 8. clrscr(); 9. 10. printf("Value of i : %d\n",i); 11. printf("Address of i : %u\n",&i); 12. printf("Value of ptr : %u\n",ptr); 13. printf("Address of ptr : %u\n",&ptr); 14. printf("Ptr pointing value : %d", *ptr); 15. 16. getch(); 17. } In the above example in line no. 6 we have declared an integer i and assigned 9 to it. Along with variable i, we have also declared an integer pointer. To declare a pointer of any data type we just need to put an * (asterisk) before variable name or identifier. In our example ptr is an integer variable and is capable of holding address of any integer variable. Remember one thing integer pointer can hold only integer variable address, you cannot use integer pointer to hold address of float or char variable. To hold char or float variable address in a pointer you need to declare char or float pointer respectively. In line no. 7 we assigned integer variable is address to ptr, now ptr is pointing to i. Line no 10 prints value of i and line no. 11 prints address of i. Next line prints value stored in ptr pointer variable, line no. 13 prints address of ptr pointer. As pointer is different entity so it also requires space in memory. Memory occupied by a pointer depends on its data type. Integer pointer will occupy 2 bytes whereas character pointer will occupy 1 byte. Finally line no. 14 prints the value of address stored in ptr pointer i.e. value of i. And to print value of stored address in a pointer we need write *pointer variable name (in our example *ptr). A memory map will help you to understand this.

5. Functions that return multiple values.


So far, we have learned and seen that in a function, return statement was able to return only single value. That is because; a return statement can return only one value. But if we want to send back more than one value then how we could do this?
44 Pre pared by Z. Mwololo

Comp 111: Introduction to Programming

We have used arguments to send values to the called function, in the same way we can also use arguments to send back information to the calling function. The arguments that are used to send back data are called Output Parameters. It is a bit difficult for novice because this type of function uses pointer. Lets see an example: 1. #include<stdio.h> 2. #include<conio.h> 3. void calc(int x, int y, int *add, int *sub) 4. { 5. *add = x+y; 6. *sub = x-y; 7. } 8. void main() 9. { 10. int a=20, b=11, p,q; 11. clrscr(); 12. calc(a,b,&p,&q); 13. printf("Sum = %d, Sub = %d",p,q); 14. getch(); 15. }

Source Code Explanation:


Logic of this program is that we call UDF calc() and sends argument then it adds and subtract that two values and store that values in their respective pointers. The * is known as indirection operator whereas & known as address operator. We can get memory address of any variable by simply placing & before variable name. In the same way we get value stored at specific memory location by using * just before memory address. These things are a bit confusing but when you will understand pointer then these thing will become clearer. Line no. 3-7: This UDF function is different from all above UDF because it implements pointer. I know line no. 3 looks something strange, lets have a clear idea of it. Calc() function has four arguments, first two arguments need no explanation. Last two arguments are integer pointer which works as output parameters (arguments). Pointer can only store address of the value rather than value but when we add * to pointer variable then we can store value at that address. Line no. 8-15: When we call calc() function in the line no. 12 then following assignments occurs. Value of variable a is assigned to x, value of variable b is assigned to y, address of p and q to add and sub respectively. In line no. 5 and 6 we are adding and subtracting values and storing the result at their respective memory location. This is how the program works.

45 Pre pared by Z. Mwololo

Comp 111: Introduction to Programming

ARRAYS What is an Array?


An array in C language is a collection of similar data-type, means an array can hold value of a particular data type for which it has been declared. Arrays can be created from any of the C datatypes int, float, and char. So an integer array can only hold integer values and cannot hold values other than integer. When we declare array, it allocates contiguous memory location for storing values whereas 2 or 3 variables of same data-type can have random locations. So this is the most important difference between a variable and an array. Types of Arrays: 1. One dimension array (Also known as 1-D array). 2. Two dimension array (Also known as 2-D array). 3. Multi-dimension array.

Declaration of One Dimensional Arrays:


Syntax: data_type array_name[width]; Example: int roll[8]; In our example, int specifies the type if the variable, roll specifies the name of the variable and the value in bracket [8] is new for newbie. The bracket ([ ]) tells compiler that it is an array and number mention in the bracket specifies that how many elements (values in any array is called elements) it can store. This number is called dimension of array. So, with respect to our example we have declared an array of integer type and named it roll which can store roll numbers of 8 students.

C Array Assignment and Initialization:


We can initialize and assign values to the arrays in the same way as we do with variable. We can assign value to an array at the time of declaration or during runtime. Lets look at each approach. Syntax: data_type array_name[size]={list of values}; Example: int arr[5]={1,2,3,4,5}; int arr[]={1,2,3,4,5}; In our above array example we have declared an integer array and named it arr which can hold 5 elements, we are also initializing arrays in the same time.
46 Pre pared by Z. Mwololo

Comp 111: Introduction to Programming

Both statements in our example are valid method to declare and initialize single dimension array. In our first example we mention the size (5) of an array and assigned it values in curly brace, separating elements value by comma (,). But in second example we left the size field blank but we provided its elements value. When we only give element values without providing size of an array then C compiler automatically assumes its size from given element values. There is one more method to initialize array C programming; in this method we can assign values to individual element of an array. For this lets look at example:

Array Initialization Example


1. #include<stdio.h> 2. #include<conio.h> 3. 4. void main() 5. { 6. int arr[5],i; 7. clrscr(); 8. arr[0]=10; 9. arr[1]=20; 10. arr[2]=30; 11. arr[3]=40; 12. arr[4]=50; 13. 14. printf("Value in array arr[0] : %d\n",arr[0]); 15. printf("Value in array arr[1] : %d\n",arr[1]); 16. printf("Value in array arr[2] : %d\n",arr[2]); 17. printf("Value in array arr[3] : %d\n",arr[3]); 18. printf("Value in array arr[4] : %d\n",arr[4]); 19. printf("\n"); 20. 21. for(i=0;i<5;i++) 22. { 23. printf("Value in array arr[%d] : %d\n",i,arr[i]); 24. } 25. getch(); 26. } In the above c arrays example we have assigned the value of integer array individually like we do with an integer variable. We have called array elements value individually and using for loop so that it would be clear for beginner and semi-beginner C programmers. So, from the above example it is evident that we can assign values to an array element individually and can call them individually whenever we need them.
47 Pre pared by Z. Mwololo

Comp 111: Introduction to Programming

TWO DIMENSIONAL ARRAYS We know how to work with an array (1D array) having one dimension. In C language it is possible to have more than one dimension in an array. We are going to learn how we can use two dimensional arrays (2D arrays) to store values. Because it is a 2D array so its structure will be different from one dimension array. The 2D array is also known as Matrix or Table, it is an array of array.

Declaration of 2D array:
Syntax: data_type array_name[row_size][column_size]; Example: int arr[3][3]; So the above example declares a 2D array of integer type. This integer array has been named arr and it can hold up to 9 elements (3 rows x 3 columns).

Code for assigning & displaying 2D Array


1. #include<stdio.h> 2. #include<conio.h> 3. 4. void main() 5. { 6. int i, j; 7. int arr[3][3]={ 8. {12, 45, 63}, 9. {89, 34, 73}, 10. {19, 76, 49} 11. }; 12. clrscr(); 13. printf(":::2D Array Elements:::\n\n"); 14. for(i=0;i<3;i++) 15. { 16. for(j=0;j<3;j++) 17. { 18. printf("%d\t",arr[i][j]); 19. } 20. printf("\n"); 21. } 22. getch(); 23. }

48 Pre pared by Z. Mwololo

Comp 111: Introduction to Programming

So in the above example we have declared a 2D array named arr which can hold 3x3 elements. We have also initialized that array with values, because we told the compiler that this array will contain 3 rows (0 to 2) so we divided elements accordingly. Elements for column have been differentiated by a comma (,). When compiler finds comma in array elements then it assumes comma as beginning of next element value. We can also define the same array in other ways, like. int arr[3][3]={12, 45, 63, 89, 34, 73, 19, 76, 49}; or, int arr[ ][3]={12, 45, 63, 89, 34, 73, 19, 76, 49}; But this kind of declaration is not acceptable in C language programming. int arr[2][ ]={12, 45, 63, 89, 34, 73, 19, 76, 49}; or, int arr[ ][ ]={12, 45, 63, 89, 34, 73, 19, 76, 49}; To display 2D array elements we have to just point out which element value we want to display. In our example we have a arr[3][3], so the array element reference will be from arr[0][0] to arr[2] [2]. We can print display any element from this range. But in our example I have used for loop for my convenience, otherwise I had to write 9 printf statements to display all elements of array. So for loop i handles row of 2D array and for loop j handles column. I have formatted the output display of array so that we can see the elements in tabular form.

STRUCTURES

C Structure Introduction
We used variable in our C program to store value but one variable can store only single piece information (an integer can hold only one integer value) and to store similar type of values we had to declare many variables. To overcome this problem we used array which can hold numbers of similar data type. But array too have some limitations, like in our real world application we deal with set of dissimilar data types and single array cannot store dissimilar data. For example think about storing book information or product information, a product can have different information to store like product code (an integer), product name (a char array), product price (a float) etc. And to store 20 products information we can declare integer array for product code, 2D character array for storing product name and float array to store product price. This approach definitely achieves your goals, but try to consider these things too. What if you wanted to add more products than 20, what if you want to add more information on products like stock, discount, tax etc? It will become difficult to differentiate these variables with other variables declared for calculation etc. To solve this problem C language has a unique data type called Structure. C structure is nothing but collection of different related data types. If we are using C structure then we are combining
49 Pre pared by Z. Mwololo

Comp 111: Introduction to Programming

different related data types in one group so that we can use and manage those variables easily. Here related data type means, a structure holding information about book will contains variable and array related to book.

Syntax for C Structure declaration


struct structure_name { data type member1; data type member2; }; Example: struct products { char name[20]; int stock; float price; }; So structure declaration begins with struct keyword and with a space we need to provide a structure name. Within open and closed curly braces we can declare required and related variable, you can see it in our example structure declaration. And most important point to remember in case of C structure is that it ends with semicolon (;).

Example of C Structure
1. #include<stdio.h> 2. #include<conio.h> 3. 4. struct product 5. { 6. char name[30]; 7. int stock; 8. float price, dis; 9. }; 10. 11. void main() 12. {
50 Pre pared by Z. Mwololo

Comp 111: Introduction to Programming

13. 14. 15. 16.

struct product p1 ={"Apple iPod Touch 32GB", 35,298.56, 2.32}; clrscr(); printf("Name=%s,\nStock=%d,\nPrice=$%.2f,\nDiscount=%.2f%.", p1.name, p1.stoc k, p1.price,p1.dis); 17. getch(); 18. }

Code Explanation
So line no.4-9 declares a C structure named product, this structure contains four variables to store different information about product. In the beginning there is a character array (char name[30]) which stores name of the product, next we have integer variable (int stock) to store stock of product and last two variable are float type (float price, discount) to product price & discount on product respectively. Guys we just declared product structure and now we have to use it in main(). Line no. 14 declares a product type variable p1. Here product type variable means, in our C program product is a structure and to use that structure we need to create its variable. Declaring a product structure variable is simple just use following syntax: struct structure_name variable_name; Remember struct is a C keyword, structure_name is name of structure you used while declaring a C structure (in above C program its product) and variable_name could be any name of your choice (in above C program its p1) but standard naming convention applies. Along with declaring C structure variable p1 we have also initialized it and to initialize C structure you need to assign values in proper order. Proper order means assign value in the order they are declared in structure. For example, in our product structure we declare variable in following orders: char name[30]; int stock; float price, discount; So for this structure proper order will be: char name[30]; int stock; float price; float discount;

51 Pre pared by Z. Mwololo

Comp 111: Introduction to Programming

You dont need to rewrite your structure, you just need to keep it in mind that structure variable initialization should be performed in orderly manner (top bottom and left right manner) otherwise it will show error or you may get strange output. So in above program we have initialized p1 variable in following way: struct product p1 ={"Apple iPod Touch 32GB", 35, 298.56, 2.32}; means struct product p1 ={char name[30], int stock, float price, float discount}; //this line of code is only assumption. Next in line no. 16 we just printed the values stores in product structure. You cannot print values stored in product structure member variable (like name, stock etc.) directly, you have to link member variable with structure variable and you can do this using (.) dot operator. For example: character array name is unknown to main() because it is declared in structure product, so to access member variable we will follow the following syntax: structure_variable.member_variable; Example: p1.name; We can rewrite printf("Name=%s,\nStock=%d,\nPrice=$%.2f,\nDiscount=%.2f%.", p1.name, p1.stock, p1.price,p1.discount); in the following manner: printf(Name = %s,p1.name); printf(Stock = %d,p1.stock); printf(Price = $%.2f,p1.price); printf(Stock = %.2f,p1.discount); Here is full working code sample of C Structure 1. #include<stdio.h> 2. #include<conio.h> 3. 4. struct product 5. { 6. char name[30]; 7. int stock; 8. float price, discount; 9. }; 10. 11. void main() 12. {
52 Pre pared by Z. Mwololo

Comp 111: Introduction to Programming

13. 14. 15. 16. 17. 18. 19. 20.

struct product p1 ={"Apple iPod Touch 32GB", 35,298.56, 2.32}; clrscr(); printf("Name = %s\n",p1.name); printf("Stock = %d\n",p1.stock); printf("Price = %.2f\n",p1.price); printf("Discount= %.2f\n",p1.discount); getch(); }

THE C STORAGE CLASSES, SCOPE AND MEMORY ALLOCATION


INTRODUCTION The storage class determines the part of memory where storage is allocated for an object (particularly variables and functions) and how long the storage allocation continues to exist. A scope specifies the part of the program which a variable name is visible, that is the accessibility of the variable by its name. In C program, there are four storage classes: automatic, register, external, and static. Keep in mind that in the hardware terms we have primary storage such as registers, cache, memory (Random Access Memory) and secondary storage such as magnetic and optical disk. 1. AUTOMATIC VARIABLE - auto They are declared at the start of a programs block such as in the curly braces ( { } ). Memory is allocated automatically upon entry to a block and freed automatically upon exit from the block. The scope of automatic variables is local to the block in which they are declared, including any blocks nested within that block. For these reasons, they are also called local variables. No block outside the defining block may have direct access to automatic variables (by variable name) but, they may be accessed indirectly by other blocks and/or functions using pointers. Automatic variables may be specified upon declaration to be of storage class auto. However, it is not required to use the keyword auto because by default, storage class within a block is auto. Automatic variables declared with initializers are initialized every time the block in which they are declared is entered or accessed.
53 Pre pared by Z. Mwololo

Comp 111: Introduction to Programming

2. REGISTER VARIABLE - register Automatic variables are allocated storage in the main memory of the computer; however, for most computers, accessing data in memory is considerably slower than processing directly in the CPU. Registers are memory located within the CPU itself where data can be stored and accessed quickly. Normally, the compiler determines what data is to be stored in the registers of the CPU at what times. However, the C language provides the storage class register so that the programmer can suggest to the compiler that particular automatic variables should be allocated to CPU registers, if possible and it is not an obligation for the CPU to do this. Thus, register variables provide a certain control over efficiency of program execution. Variables which are used repeatedly or whose access times are critical may be declared to be of storage class register. Variables can be declared as a register as follows: register int var; 3. EXTERNAL VARIABLE - extern All variables we have seen so far have had limited scope (the block in which they are declared) and limited lifetimes (as for automatic variables). However, in some applications it may be useful to have data which is accessible from within any block and/or which remains in existence for the entire execution of the program. Such variables are called global variables, and the C language provides storage classes which can meet these requirements; namely, the external (extern) and static (static) classes. Declaration for external variable is as follows: extern int var; External variables may be declared outside any function block in a source code file the same way any other variable is declared; by specifying its type and name (extern keyword may be omitted). Typically if declared and defined at the beginning of a source file, the extern keyword can be omitted. If the program is in several source files, and a variable is defined in let say file1.c and used in file2.c and file3.c then the extern keyword must be used in file2.c and file3.c. But, usual practice is to collect extern declarations of variables and functions in a separate header file (.h file) then included by using #include directive. Memory for such variables is allocated when the program begins execution, and remains allocated until the program terminates. For most C implementations, every byte of memory allocated for an external variable is initialized to zero. The scope of external variables is global, i.e. the entire source code in the file following the declarations. All functions following the declaration may access the external variable by using its name. However, if a local variable having the same name is declared within a function, references to the name will access the local variable cell. The following program example demonstrates storage classes and scope. /* storage class and scope */ #include <stdio.h>
54 Pre pared by Z. Mwololo

Comp 111: Introduction to Programming

void funct1(void); void funct2(void); /* external variable, scope is global to main(), funct1() and funct2(), extern keyword is omitted here, coz just one file */ int globvar = 10; int main() { printf("\n****storage classes and scope****\n"); /* external variable */ globvar = 20; printf("\nVariable globvar, in main() = %d\n", globvar); funct1(); printf("\nVariable globvar, in main() = %d\n", globvar); funct2(); printf("\nVariable globvar, in main() = %d\n", globvar); return 0; } /* external variable, scope is global to funct1() and funct2() */ int globvar2 = 30; void funct1(void) { /* auto variable, scope local to funct1() and funct1() cannot access the external globvar */ char globvar; /* local variable to funct1() */ globvar = 'A'; /* external variable */ globvar2 = 40; printf("\nIn funct1(), globvar = %c and globvar2 = %d\n", globvar, globvar2); } void funct2(void) { /* auto variable, scope local to funct2(), and funct2() cannot access the external globvar2 */ double globvar2; /* external variable */
55 Pre pared by Z. Mwololo

Comp 111: Introduction to Programming

globvar = 50; /* auto local variable to funct2() */ globvar2 = 1.234; printf("\nIn funct2(), globvar = %d and globvar2 = %.4f\n", globvar, globvar2); }

Output:

External variables may be initialized in declarations just as automatic variables; however, the initializers must be constant expressions. The initialization is done only once at compile time, i.e. when memory is allocated for the variables. In general, it is a good programming practice to avoid using external variables as they destroy the concept of a function as a 'black box' or independent module. The black box concept is essential to the development of a modular program with modules. With an external variable, any function in the program can access and alter the variable, thus making debugging more difficult as well. This is not to say that external variables should never be used. There may be occasions when the use of an external variable significantly simplifies the implementation of an algorithm. Suffice it to say that external variables should be used rarely and with caution.

4. STATIC VARIABLE - static As we have seen, external variables have global scope across the entire program (provided extern declarations are used in files other than where the variable is defined), and have a lifetime over the entire program run.

56 Pre pared by Z. Mwololo

Comp 111: Introduction to Programming

Similarly, static storage class provides a lifetime over the entire program, however; it provides a way to limit the scope of such variables, and static storage class is declared with the keyword static as the class specifier when the variable is defined. These variables are automatically initialized to zero upon memory allocation just as external variables are. Static storage class can be specified for automatic as well as external variables such as: static extern varx; Static automatic variables continue to exist even after the block in which they are defined terminates. Thus, the value of a static variable in a function is retained between repeated function calls to the same function. The scope of static automatic variables is identical to that of automatic variables, i.e. it is local to the block in which it is defined; however, the storage allocated becomes permanent for the duration of the program. Static variables may be initialized in their declarations; however, the initializers must be constant expressions, and initialization is done only once at compile time when memory is allocated for the static variable. /* static storage class program example */ #include <stdio.h> #define MAXNUM 3 void sum_up(void); int main() { int count; printf("\n*****static storage*****\n"); printf("Key in 3 numbers to be summed "); for(count = 0; count < MAXNUM; count++) sum_up(); printf("\n*****COMPLETED*****\n"); return 0; } void sum_up(void) { /* at compile time, sum is initialized to 0 */ static int sum = 0; int num; printf("\nEnter a number: "); scanf("%d", &num); sum += num; printf("\nThe current total is: %d\n", sum); }
57 Pre

pared by Z. Mwololo

Comp 111: Introduction to Programming

Output:

While the static variable, sum, would be automatically initialized to zero, it is better to do so explicitly. In any case, the initialization is performed only once at the time of memory allocation by the compiler. The variable sum retains its value during program execution. Each time the sum_up() function is called, sum is incremented by the next integer read. To see the different you can remove the static keyword, re-compile and re-run the program.

DYNAMIC MEMORY ALLOCATION In the previous section we have described the storage classes which determined how memory for variables is allocated by the compiler. When a variable is defined in the source program, the type of the variable determines how much memory the compiler allocates. When the program executes, the variable consumes this amount of memory regardless of whether the program actually uses the memory allocated. This is particularly true for arrays. However, in many situations, it is not clear how much memory the program will actually need. For example, we may have declared arrays to be large enough to hold the maximum number of elements we expect our application to handle. If too much memory is allocated and then not used, there is a waste of memory. If not enough memory is allocated, the program is not able to fully handle the input data. We can make our program more flexible if, during execution, it could allocate initial and additional memory when needed and free up the memory when it is no more needed. Allocation of memory during execution is called dynamic memory allocation. C provides library functions to allocate and free up memory dynamically during program execution. Dynamic memory is allocated on the heap by the system. It is important to realize that dynamic memory allocation also has limits. If memory is repeatedly allocated, eventually the system will run out of memory.
58 Pre pared by Z. Mwololo

Comp 111: Introduction to Programming

59 Pre pared by Z. Mwololo

You might also like