c programming

123
C programming 1 C Language 1. Introduction The C PROGRAMMING LANGUAGE was pioneered by Dennis Ritchie at AT&T Bell Laboratories in the early 1970s. In the early 1980s, a need was seen to standardize the definition of the C language. The American National Standards Institute (ANSI) is the organization that handles such things, so in 1983 an ANSI C committee was formed to standardize C. In 1990, the first official ANSI standard definition of C was published. C is a “higher-level language”. C is a general-purpose structured programming language, it was originally designed with systems programming applications in mind and, as such, provides the user with an enormous amount of power and flexibility. 2.Some Fundamentals 1 Programming A computer program is just a collection of the instructions necessary to solve a specific problem. The approach or method that is used to solve the problem is known as an algorithm. Normally, to develop a program to solve a particular problem, you first express the solution to the problem in terms of an algorithm and then develop a program that implements that algorithm. With the algorithm in hand, you can then proceed to write the instructions necessary to implement the algorithm on a particular computer system. These instructions would be expressed in the statements of a particular computer language, such as Visual Basic, Java, C++, or C. 2 Higher-Level Languages When computers were first developed, the only way they could be programmed was in terms of binary numbers that corresponded directly to specific machine instructions and locations in the computer’s memory. The next technological software advance occurred in the development of assembly languages, which enabled the programmer to work with the machine on a slightly higher level. A special program, known as an assembler, translates the assembly language program from its symbolic format into the specific machine instructions of the computer system. Then, along came the so called higher-level languages, of which the FORTRAN (FORmula TRANslation) language was one of the first. One FORTRAN instruction or statement resulted in many different machine instructions being executed, unlike the one-to-one correspondence found between assembly language statements and machine instructions.

Upload: independent

Post on 01-Feb-2023

1 views

Category:

Documents


0 download

TRANSCRIPT

C programming 1C Language

1. Introduction

The C PROGRAMMING LANGUAGE was pioneered by Dennis Ritchie at AT&TBell Laboratories in the early 1970s. In the early 1980s, a need wasseen to standardize the definition of the C language. The AmericanNational Standards Institute (ANSI) is the organization that handlessuch things, so in 1983 an ANSI C committee was formed to standardizeC. In 1990, the first official ANSI standard definition of C waspublished. C is a “higher-level language”. C is a general-purposestructured programming language, it was originally designed withsystems programming applications in mind and, as such, provides theuser with an enormous amount of power and flexibility. 2.Some Fundamentals1 Programming A computer program is just a collection of theinstructions necessary to solve a specific problem. The approach ormethod that is used to solve the problem is known as an algorithm.Normally, to develop a program to solve a particular problem, youfirst express the solution to the problem in terms of an algorithm andthen develop a program that implements that algorithm. With thealgorithm in hand, you can then proceed to write the instructionsnecessary to implement the algorithm on a particular computer system.These instructions would be expressed in the statements of aparticular computer language, such as Visual Basic, Java, C++, or C.

2 Higher-Level Languages When computers were first developed, the onlyway they could be programmed was in terms of binary numbers thatcorresponded directly to specific machine instructions and locationsin the computer’s memory. The next technological software advanceoccurred in the development of assembly languages, which enabled theprogrammer to work with the machine on a slightly higher level. Aspecial program, known as an assembler, translates the assemblylanguage program from its symbolic format into the specific machineinstructions of the computer system.

Then, along came the so called higher-level languages, of which theFORTRAN (FORmula TRANslation) language was one of the first. OneFORTRAN instruction or statement resulted in many different machineinstructions being executed, unlike the one-to-one correspondencefound between assembly language statements and machine instructions.

C programming 2Standardization of the syntax of a higher-level language meant that aprogram could be written in the language to be machine independent.That is, a program could run on any machine that supported thelanguage with few or no changes.

To support a higher-level language, a special computer program must bedeveloped that translates the statements of the program developed inthe higher-level language into a form that the computer can understandin other words, into the particular instructions of the computer. Sucha program is known as a compiler.

3.Operating Systems

An operating system is a program that controls the entire operation ofa computer system. All input and output (that is, I/O) operations thatare performed on a computer system are channeled through the operatingsystem. The operating system must also manage the computer system’sresources and must handle the execution of programs. One of the mostpopular operating systems today is the Unix operating system, whichwas developed at Bell Laboratories. Unix was written primarily in theC language and made very few assumptions about the architecture of thecomputer, it has been successfully ported to many different computersystems with a relatively small amount of effort. Microsoft Windows XPis another example of a popular operating system. That system is foundrunning primarily on Pentium (or Pentium-compatible) processors.

4.Compiling Programs

A compiler analyzes a program developed in a particular computerlanguage and then translates it into a form that is suitable forexecution on your particular computer system. Figure 2.1 shows thesteps that are involved in entering, compiling, and executing acomputer program developed in the C programming language and thetypical Unix commands that would be entered from the command line. Theprogram that is to be compiled is first typed into a file on thecomputer system. C programs can typically be given any name providedthe last two characters are “.c”. A text editor is usually used toenter the C program into a file. For example, vi is a popular texteditor used on Unix systems. The program that is entered into the fileis known as the source program because it represents the original formof the program expressed in the C language. After the source program

C programming 3has been entered into a file, you can then proceed to have itcompiled.

The compilation process is initiated by typing a special command onthe system. When this command is entered, the name of the file thatcontains the source program must also be specified. For example, underUnix, the command to initiate program compilation is called cc. If youare using the popular GNU C compiler, the command you use is gcc.Typing the line gcc prog1.c has the effect of initiating thecompilation process with the source program contained in prog1.c.

In the first step of the compilation process, the compiler examineseach program statement contained in the source program and checks itto ensure that it conforms to the syntax and semantics of thelanguage. If any mistakes are discovered by the compiler, The errorsthen have to be corrected in the source program, and the compilationprocess must be restarted. Typical errors reported during this phaseof compilation might be due to an expression that has unbalancedparentheses(syntactic error), or due to the use of a variable that isnot “defined” (semantic error).

When all the syntactic and semantic errors have been removed from theprogram, the compiler then proceeds to take each statement of theprogram and translate it into a “lower” form. The assembler takeseach assembly language statement and converts it into a binary formatknown as object code, which is then written into another file on thesystem. This file typically has the same name as the source file underUnix, with the last letter an “o” (for object) instead of a “c”. UnderWindows, the suffix letters "obj" typically replace the “c” in thefilename.

After the program has been translated into object code, it is ready tobe linked. This process is once again performed automatically wheneverthe cc or gcc command is issued under Unix. The purpose of the linkingphase is to get the program into a final form for execution on thecomputer. If the program uses other programs that were previouslyprocessed by the compiler, then during this phase the programs arelinked together. Programs that are used from the system’s programlibrary are also searched and linked together with the object programduring this phase.

C programming 4

Figure 2.1 Typical steps for entering, compiling, and executing Cprograms from the command line.

The process of compiling and linking a program is often calledbuilding. The final linked file, which is in an executable object codeformat, is stored in another file on the system, ready to be run orexecuted. Under Unix, this file is called a.out by default. UnderWindows, the executable file usually has the same name as the sourcefile, with the extension replaced by an exe extension.

To subsequently execute the program, all you do is type in the name ofthe executable object file. So, the command a.out has the effect ofloading the program called a.out into the computer’s memory andinitiating its execution.

C programming 5When the program is executed, each of the statements of the program issequentially executed in turn. If the program requests any data fromthe user, known as input, the program temporarily suspends itsexecution so that the input can be entered. Results that are displayedby the program, known as output, appear in a window, sometimes calledthe console Or, the output might be directly written to a file on thesystem.

The entire process of compiling, linking, and executing the programmust be repeated until the desired results are obtained.

Integrated Development Environments

The individual steps involved in developing C programs were outlinedearlier, showing typical commands that would be entered for each step.This process of editing, compiling, running, and debugging programsis often managed by a single integrated application known as anIntegrated Development Environment, or IDE for short. An IDE is awindows based program that allows you to easily manage large softwareprograms, edit files in windows, and compile, link, run, and debugyour programs. On Mac OS X, CodeWarrior and Xcode are two IDEs thatare used by many programmers. Under Windows, Microsoft Visual Studiois a good example of a popular IDE. Kylix is a popular IDE fordeveloping applications under Linux. All the IDE applications greatlysimplify the entire process involved in program development so it isworth your while to learn how to use one. Most IDEs also supportprogram development in several different programming languages inaddition to C, such as C# and C++.

Language Interpreters

An interpreter analyzes and executes the statements of a program atthe same time. This method usually allows programs to be more easilydebugged. On the other hand, interpreted languages are typicallyslower than their compiled counterparts because the program statementsare not converted into their lowest level form in advance of theirexecution. BASIC and Java are two programming languages in whichprograms are often interpreted and not compiled. Other examplesinclude the Unix system’s shell and Python.

3. Compiling and Running Your First ProgramProgram 3.1 Writing Your First C Program

C programming 6#include <stdio.h>int main (void){

printf ("Programming is fun.\n");return 0;}In the C programming language, lower-case and upper-case letters are distinct. In addition,in C, it does not matter where on the line you begin typing you can begin typing your statement at any position on the line.

Compiling Your Program You first need to type it into a file. Any texteditor can be used for this purpose. Unix users often use an editor such as vi or emacs. Most C compilers recognize filenames that end in the two characters “.” and “c” as C programs. So, assume you type Program 3.1 into a file called prog1.c. Next, you need to compile the program.Using the GNU C compiler, this can be as simple as issuing thegcc command at the terminal followed by the filename, like this:

$ gcc prog1.c

If you’re using the standard Unix C compiler, the command is cc instead of gcc. Here, the text you typed is entered in bold. The dollar sign is your command prompt if you’re compiling your C program from the command line. Your actual command prompt might be some characters other than the dollar sign. If you make any mistakes keyingin your program, the compiler lists them after you enter the gcc command, typically identifying the line numbers from your program thatcontain the errors. When the compiler compiles and links your program,it creates an executable version of your program. Using the GNU or standard C compiler, this program is called a.out by default. Under Windows, it is often called a.exe instead.

Compiling Your Program You first need to type it into a file. Anytext editor can be used for this purpose. Unix users often use aneditor such as vi or emacs. Most C compilers recognize filenames thatend in the two characters “.” and “c” as C programs. So, assume youtype Program 3.1 into a file called prog1.c. Next, you need to compilethe program. Using the GNU C compiler, this can be as simple asissuing the gcc command at the terminal followed by the filename, likethis:

C programming 7$ gcc prog1.c

If you’re using the standard Unix C compiler, the command is ccinstead of gcc. Here, the text you typed is entered in bold.The dollarsign is your command prompt if you’re compiling your C program fromthe command line. Your actual command prompt might be some charactersother than the dollar sign. If you make any mistakes keying in yourprogram, the compiler lists them after you enter the gcc command,typically identifying the line numbers from your program that containthe errors. When the compiler compiles and links your program, itcreates an executable version of your program. Using the GNU orstandard C compiler, this program is called a.out by default. UnderWindows, it is often called a.exe instead.

Running Your Program

You can now run the executable by simply typing its name on thecommand line

$ a.out Programming is fun. You can also specify a different name for the executable file at thetime the program is compiled. This is done with the –o option, whichis followed by the name of the executable. For example, the commandline $ gcc prog1.c –o prog1 compiles the program prog1.c, placing the executable in the fileprog1, which can subsequently be executed just by specifying its name:

$ prog1 Programming is fun. Understanding Your First Program

The first line of the program #include <stdio.h> It tells the compilerinformation about the printf output routine that is used later in theprogram. The line of the program that reads int main (void) informsthe system that the name of the program is main, and that it returnsan integer value, which is abbreviated “int.” main is a special namethat indicates precisely where the program is to begin execution. Theopen and close parentheses immediately following main specify thatmain is the name of a function. The keyword void that is enclosed inthe parentheses specifies that the function main takes no arguments(that is, it is void of arguments).

C programming 8Now that you have identified main to the system, you are ready tospecify precisely what this routine is to perform. This is done byenclosing all program statements of the routine within a pair of curlybraces. All program statements included between the braces are takenas part of the main routine by the system. In Program 3.1, you haveonly two such statements. The first statement specifies that a routinenamed printf is to be invoked or called. The parameter or argument tobe passed to the printf routine is the string of characters"Programming is fun.\n"

The printf routine is a function in the C library that simply printsor displays its argument on your screen. The last two characters inthe string (\n) are known as the newline character. Any characters tobe printed after the newline character then appear on the next line ofthe display. All program statements in C must be terminated by asemicolon (;).This is the reason for the semicolon that appearsimmediately following the closing parenthesis of the printf call.

The last statement in main that reads return 0; says to finishexecution of main, and return to the system a status value of 0. Zerois used by convention to indicate that the program completedsuccessfully—that is, without running into any errors. Differentnumbers can be used to indicate different types of error conditionsthat occurred.

This exit status can be tested by other programs (such as the Unixshell) to see whether Now that you’ve finished analyzing your firstprogram, you can modify it to also display the phrase “And programmingin C is even more fun.”This can be done by the simple addition ofanother call to the printf routine, as shown in Program 3.2.#include <stdio.h>int main (void){printf ("Programming is fun.\n");printf ("And programming in C is even more fun.\n"); return 0;}Displaying the Values of Variables

C programming 9The printf routine is the most commonly used routine to displayprogram results. printf displays the values of variables and theresults of computations. Program 3.4 Displaying Variables

#include <stdio.h>int main (void){int sum;sum = 50 + 25;printf ("The sum of 50 and 25 is %i\n", sum);return 0;}In Program 3.4, the first C program statement declares the variablesum to be of type integer. C requires that all program variables bedeclared before they are used in a program. The declaration of avariable specifies to the C compiler how a particular variable will beused by the program. This information is needed by the compiler togenerate the correct instructions to store and retrieve values intoand out of the variable. A variable declared as type int can only beused to hold integral values. Whenever the printf routine finds the %icharacters inside a character string, it automatically displays thevalue of the next argument to the printf routine.

CommentsA comment statement is used in a program to document a program and toenhance itsreadability.Program 3.6 Using Comments in a Program/* This program adds two integer values and displays the results */#include <stdio.h>int main (void){

// Declare variables int value1, value2, sum;// Assign values and calculate their sum value1 = 50;value2 = 25;sum = value1 + value2;// Display the result printf ("The sum of %i and %i is %i\n", value1, value2, sum);

C programming 10return 0;

}There are two ways to insert comments into a C program. A comment canbe initiated by /*.This marks the beginning of the comment. Thesetypes of comments have to be terminated. To end the comment */areused without any embedded spaces. All characters included between the/*and the */are treated as part of the comment statement and areignored by the C compiler. This form of comment is often used whencomments span several lines in the program. The second way to add acomment to your program is by using two consecutive slashcharacters //.Any characters that follow these slashes up to the endof the line are ignored by the compiler.

The benefits of the comments during the debug phase, when programlogic errors are being isolated and debugged. A comment can also helppoint the way to the source of the logic mistake.

4 Variables, Data Types, and Arithmetic Expressions

1. Variables :-Variables enable you to assign symbolic names, known asvariable names, for storing program computations and results. Avariable name can be chosen by you in a meaningful way to reflect thetype of value that is to be stored in that variable. Properdeclaration for the variable is made before it is used in the program.Variables can be used to store floating point numbers, characters, andeven pointers to locations inside the computer's memory.

The rules for forming variable names are quite simple: they must beginwith a letter or underscore (_) and may be followed by any combinationof letters (upper- or lower-case), underscores, or the digits 0 - 9.The following is a list of valid variable names.

piece_flagJ5X7Number_of _Moves_sysflagOn the other hand, the following variable names are not valid:Sum$value $ is not a valid characterpiece flag Ebedded blank space not permitted int int is a reserved word

C programming 11The Upper and lower case letters are distinct in C. Therefore, thevariable names sum, Sum, and SUM each refer to a different variable.2.Data Types and Constants A variable declared to be of type int can be used to contain integralvalues . The C programming language provides four other basic datatypes: float, double, char, and Bool. A variable declared to be oftype float can be used for storing floating point numbers. The doubletype is the same as type float, only with roughly twice the precision.The char data type can be used to store a single character, such asthe letter a,the digit character 6. Finally, the Bool data type can beused to store just the values 0 or 1. Variables of this type are usedfor indicating an on/off, yes/no, or true/false situation. In C, anyliteral number, single character, or character string is known as aconstant. The character string "Programming in C is fun. \n" is anexample of a constant character string.

Type IntIn C, an integer constant consists of a sequence of one or moredigits. A minus sign preceding the sequence indicates that the valueis negative. The values 158, -10, and 0 are all valid examples ofinteger constants. No embedded spaces are permitted between thedigits, and values larger than 999 cannot be expressed using commas. There are two special formats in C that enable integer constants to beexpressed in a base other than decimal (base 10). If the first digit of the integer value is a zero, then the integer istaken as expressed in octal notation, that is, in base 8. In thatcase, the remaining digits of the value must be valid base-8 digitsand therefore must be from 0 through 7. An integer value can bedisplayed at the terminal in octal notation by using the formatcharacters %o in the format string of a printf statement. In such acase, it is noted that the value will be displayed in octal without aleading zero.If an integer constant is preceded by a 0 and the letter x (eitherlower-case or upper-case), then the value is taken as expressed inhexadecimal (base 16) notation. Immediately following the letter xare the digits of the hexadecimal value, which can be composed of thedigits 0 through 9 and the letters a through f (or A through F). Theletters represent the values 10 through 15, respectively. To displayan integer value in hexadecimal format at the terminal, use the formatcharacters %x. Type float

C programming 12A variable declared to be of type float can be used for storing valuescontaining decimal places. A floating point constant is distinguishedby the presence of a decimal point. It is permissible to omit digitsbefore the decimal point, or digits after the decimal point, butobviously not to omit both. The values 3., 125.8, and -.0001 are allvalid examples of floating point constants. To display a floatingpoint value at the terminal, the printf conversion characters %f areused. In order to display a value in scientific notation, the formatcharacters %e should be specified in the printf format string.Type doubleThe type double is very similar to type float. It is used whenever theaccuracy provided by a float variable is not sufficient. Variablesdeclared to be of type double can store roughly twice as manysignificant digits as can a variable of type float. The precise numberof digits that can be stored in either a float or double variabledepends on the particular computer system you are using. To display adouble float value at the terminal, the format characters %f or %e,which are the same format characters used to display a float value,can be used.Type charA char variable can be used to contain a single character. A characterconstant is formed by enclosing the character within a pair of singlequote marks. So 'a', ';', and '0' are all valid examples of characterconstants. with a character string, which is any number of charactersenclosed in double quotes. The format characters %c can be used in aprintf call to display the value of a char variable at the terminal.Qualifiers long, short, and unsigned If the qualifier long is placed directly before the int declaration,then the declared integer variable will be of extended accuracy onmany computer systems. An example of a long int declaration might be long int factorial;for example, the maximum positive value that can be stored inside avariable of type int is 32,767. Declaring a variable to be of typelong int permits values up to 231 - 1 or 2,147,483,647 to be stored inthe variable. A constant value of type long is formed by optionallyappending the letter L (upper- or lower-case) onto the end of aninteger constant. No spaces are permitted between the number and theL. So, the declarationlong int memory_address = 131071L;To display the value of a long int variable at the terminal, theletter I is used as a modifier before the integer format characters d,

C programming 13p, or x. This means that the format characters %ld can be used todisplay the value of a long int in decimal format, the characters %loto display the value in octal format, and the characters %lx todisplay the value in hexadecimal format.The qualifier short, when placed in front of the int declaration,tells the C system that the particular variable being declared willbe used to store small integer values. On many machines, a short intwill take up half the amount of storage as a regular int variable.The final qualifier that may be placed in front of an int variable isused when an integer variable will be used only to store positivenumbers. The declarationunsigned int counter;declares to the C system that the variable counter will be used onlyto contain positive values. for example, a normal int variable canassume values from - 32,768 through 32,767. The same variabledeclared to be of type unsigned int can assume values from 0 through65,535. When declaring variables to be of type long int, short int, orunsigned int, it is permitted to omit the keyword int. So the unsignedvariable counter could have been equivalently declared asunsigned counter;Program 4.1 Using the Basic Data Types#include <stdio.h>int main (void){

int integerVar = 100;float floatingVar = 331.79;double doubleVar = 8.44e+11;char charVar = 'W';Bool boolVar = 0;printf ("integerVar = %i\n", integerVar);printf ("floatingVar = %f\n", floatingVar);printf ("doubleVar = %e\n", doubleVar);printf ("doubleVar = %g\n", doubleVar);printf ("charVar = %c\n", charVar);printf ("boolVar = %i\n", boolVar);return 0;

}

3. Arithmetic Expressions

C programming 14In C, the plus sign (+) is used to add two values; the minus sign (-)to subtract two values; the asterisk (*) to multiply two values; andthe slash (/) to divide two values. These operators are known asbinary arithmetic operators, since they operate on two values orterms.Program 4.2 Using the Arithmetic Operators// Illustrate the use of various arithmetic operators#include <stdio.h>int main (void){

int a = 100;int b = 2;int c = 25;int d = 4;int result;result = a - b; // subtractionprintf ("a - b = %i\n", result);result = b * c; // multiplicationprintf ("b * c = %i\n", result);result = a / c; // divisionprintf ("a / c = %i\n", result);result = a + b * c; // precedenceprintf ("a + b * c = %i\n", result);printf ("a * b + c * d = %i\n", a * b + c * d);return 0;

}The last operation performed in the program introduce the view thatone operator can have a higher priority or precedence over anotheroperator. In fact, each operator in C has a precedence associated withit. This precedence is used to determine how an expression that hasmore than one operator is evaluated: The operator with the higherprecedence is evaluated first. Expressions containing operators of thesame precedence are either evaluated from left to right or from rightto left, depending on the operator. This is known as the associativeproperty of an operator. Evaluation of an expression generally proceeds from left to right.However, the operations of multiplication and division are givenhigher precedence over the operations of addition and subtraction.

C programming 15The unary minus operator has higher precedence than all otherarithmetic operators,except for the unary plus operator (+), which hasthe same precedence.The Modulus OperatorThe modulus operator, which is symbolized by the percent sign (%). Tryto determine how this operator. works by analyzing the output from thefollowing program.Program 4.4 Illustrating the Modulus Operator// The modulus operator#include <stdio.h>int main (void){

int a = 25, b = 5, c = 10, d = 7;printf ("a %% b = %i\n", a % b);printf ("a %% c = %i\n", a % c);printf ("a %% d = %i\n", a % d);printf ("a / d * d + a %% d = %i\n", a / d * d + a % d);return 0;

}The first statement inside main declares and initializes the variablesa,b,c, and d in a single statement. In the first printf call, you willnotice that we used two percent signs in the format string; yet, ifyou examine the program's output, you will notice that only a singlepercent sign was printed. The reason for this is due to the specialsignificance of the % sign to the printf routine.Integer and Floating Point ConversionsIn order to effectively develop C programs, it will be necessary foryou to understand the rules that are used for the implicit conversionof floating point and integer values in C.Program 4.5 Converting Between Integers and Floats// Basic conversions in C#include <stdio.h>int main (void){

float f1 = 123.125, f2;int i1, i2 = -150;char c = 'a';i1 = f1; // floating to integer conversion

C programming 16printf ("%f assigned to an int produces %i\n", f1, i1);f1 = i2; // integer to floating conversionprintf ("%i assigned to a float produces %f\n", i2, f1);f1 = i2 / 100; // integer divided by integerprintf ("%i divided by 100 produces %f\n", i2, f1);f2 = i2 / 100.0; // integer divided by a floatprintf ("%i divided by 100.0 produces %f\n", i2, f2);f2 = (float) i2 / 100; // type cast operatorprintf ("(float) %i divided by 100 produces %f\n", i2, f2);return 0;

}Whenever a floating point value is assigned to an integer variable inC, the decimal portion of the number gets truncated.The Type Cast Operator

The last division operation from Program 4.5 that reads

f2 = (float) i2 / 100; // type cast operator

introduces the type cast operator. The type cast operator has theeffect of converting the value of the variable i2to type float forpurposes of evaluation of the expression. The type cast operator has ahigher precedence than all the arithmetic operators except the unaryminus and unary plus.

Combining Operations with Assignment: The Assignment OperatorsThe C language permits you to join the arithmetic operators with theassignment operator using the following general format :op=

In this format, op is any of the arithmetic operators, including+,–,×,/,and %. In addition, op can be any of the bit operators forshifting and masking. Consider this statement: count += 10;

The effect of the so-called “plus equals” operator +=is to add theexpression on the right side of the operator to the expression on theleft side of the operator and to store the result back into thevariable on the left-hand side of the operator. So, the previousstatement is equivalent to this statement:

count = count + 10;

5.PROGRAM LOOPINGIf we were to arrange 15 dots into the shape of a triangle, we wouldend up with an arrangement that might look something like this:

C programming 17

The first row of the triangle contains one dot, the second row twodots, and so on. In general, the number of dots it would take to forma triangle containing n rows would be the sum of the integers from 1through n. This sum is known as a triangular number. If we start at 1,then the fourth triangular number would be the sum of the consecutiveintegers 1 through 4 (1 + 2 + 3 + 4), or 10. One of the fundamental properties of a computer is its ability torepetitively execute a set of statements. The C programming languagecontains three different program statements for program looping. Theyare known as the for statement, the while statement, and the dostatement.The for statement The general format of the for statement is as follows for ( init_expression; loop_condition; loop_expression)program statement;The three expressions enclosed within parentheses init_expression,loop_condition, and loop_expression set up the environment for theprogram loop. The program statement that immediately follows can be any valid Cprogram statement and constitutes the body of the loop. This statementwill be executed as many times as specified by the parameters set upin the for statement. The first component of the for, labeled init_expression, is used toset the initial values before the loop begins.The second component of the for statement specifies the condition orconditions that are necessary in order for the loop to continue. Inother words, looping continues as long as this condition is satisfied.Several relational operators provided in the C programming language.These operators are used to test specific conditions. The answer tothe test will be "yes" or, more commonly, TRUE if the condition issatisfied and "no" or FALSE if the condition is not satisfied.The relational operators have lower precedence than all arithmeticoperators. TABLE 5.1. RELATIONAL OPERATOR

C programming 18

In summary, then, execution of the for statement proceeds as follows:1. The initial expression is evaluated first. This expression usuallysets a variable that will be used inside the loop, generally referredto as an index variable, to some initial value such as 0 or 1.2. The looping condition is evaluated. If the condition is notsatisfied (the expression is FALSE), then the loop is immediatelyterminated. Execution continues with the program statement thatimmediately follows the loop. 3. The program statement that constitutes the body of the loop isexecuted.4. The looping expression is evaluated. This expression is generallyused to change the value of the index variable, frequently by adding 1to it or subtracting 1 from it.5. Return to Step 2.Program 5.2 Calculating the 200th Triangular Number/* Program to calculate the 200th triangular number Introduction ofthe for statement */#include <stdio.h>int main (void){

int n, triangulrNumber;triangularNumber = 0;for ( n = 1; n <= 200; n = n + 1 )

triangularNumber = triangularNumber + n;printf ("The 200th triangular number is %i\n", triangularNumber);return 0;

}Since above Program actually generates all of the first 200triangular numbers on its way to its final goal, it might be nice togenerate a table of these numbers. To save space, however, we willassume that we just want to print a table of the first 10 triangularnumbers.

C programming 19Program 5.3 Generating a Table of Triangular Numbers// Program to generate a table of triangular numbers #include <stdio.h>int main (void){

int n, triangularNumber;printf ("TABLE OF TRIANGULAR NUMBERS\n\n");printf (" n Sum from 1 to n\n");printf ("--- ---------------\n");triangularNumber = 0;for ( n = 1; n <= 10; ++n ) {

triangularNumber += n;printf (" %i %i\n", n, triangularNumber);

}return 0;

}A new operator in the C programming language-the increment operator.The function of the double plus sign-or the increment operator-is toadd 1 to its operand. Therefore, the expression ++n is equivalent tothe expression n = n + I. Program InputProgram 5.4 Asking the User for Input#include <stdio.h>int main (void){

int n, number, triangularNumber;printf ("What triangular number do you want? ");scanf ("%i", &number);triangularNumber = 0;for ( n = 1; n <= number; ++n )

triangularNumber += n;printf ("Triangular number %i is %i\n", number,triangularNumber);return 0;

}The first printf statement in the above program is used to prompt theuser to type in a number. After the message is printed, the scanfroutine is called. The first argument to the scanf routine is the

C programming 20format string and is very similar to the format string used in aprintf call. In this case, the format string doesn't tell the systemwhat types of values are to be displayed but rather what types ofvalues are to be read in from the terminal. Like the printf, the %dcharacters are used to specify an integer value. The second argumentto the scanf routine specifies where the value that is typed in by theuser is to be stored. The & character before the variable number isnecessary in this case. Nested for LoopsProgram gives the user the flexibility to have the program calculateany triangular number that is desired. But suppose the user had a listof five triangular numbers to be calculated? Well, in such a case theuser could simply execute the program five times, each time typing inthe next triangular number from the list to be calculated. This can best be effected by inserting a loop into the program tosimply repeat the entire series of calculations five times .Program 5.5 Using Nested forLoops#include <stdio.h>int main (void){

int n, number, triangularNumber, counter;for ( counter = 1; counter <= 5; ++counter ) {

printf ("What triangular number do you want? "); scanf ("%i", &number);triangularNumber = 0;for ( n = 1; n <= number; ++n )

triangularNumber += n;printf ("Triangular number %i is %i\n\n", number,triangularNumber);

}return 0;

}The program consists of two levels of for statements. The outermostfor statementfor ( counter = 1; counter <= 5; ++counter )

specifies that the program loop is to be executed precisely fivetimes. This can be seen because the value of counter will beinitially set to 1 and will be incremented by 1 until it is no longerless than or equal to 5 (in other words, until it reaches 6). Variable

C programming 21counter must be declared in the program. The program loop actuallyconsists of all of the remaining program statements, as indicated bythe braces. for Loop Variantswhen writing a for loop, you have more than one variable you wouldlike to initialize before the loop begins, or perhaps more than oneexpression you would like evaluated each time through the loop. We caninclude multiple expressions in any of the fields of the for loopprovided that we separate such expressions by commas. For example, inthe for statement that beginsfor ( i = 0, j = 100; i < 10; ++i, j = j - 10 )

the value of i is set to zero and the value of j is set to zero beforethe loop begins. The two expressions i = 0 and j = 0 are separatedfrom each other by a comma.The while StatementThe while statement further extends the C language's repertoire oflooping capabilities. The syntax of this frequently used construct issimplywhile ( expression)program statement;The expression specified inside the parentheses is evaluated. If theresult of the expression evaluation is TRUE, then program statement,which immediately follows, is executed. After execution of thisstatement (or statements if enclosed in braces), expression is onceagain evaluated. If the result of the evaluation is TRUE, then programstatement is once again executed. This process continues untilexpression finally evaluates FALSE, at which point the loop isterminated. Execution of the program then continues with the statementthat follows program statement.As an example of its use, the following program sets up a while loop,which merely counts from 1 to 5.Program 5.6 Introducing the whileStatement// Program to introduce the while statement #include <stdio.h>int main (void){

int count = 1;while ( count <= 5 ) {

C programming 22printf ("%i\n", count);++count;

}return 0;

}The program initially sets the value of count to 1. Execution of thewhile loops then begins. Since the value of count is less than orequal to 5, the statement that immediately follows is executed. Thebraces serve to define both the printf statement and the statementthat increments count as the body of the while loop. From the outputof the program we can readily observe that this loop is executedprecisely 5 times, or until the value of count reaches 6.You may haverealized from this program that we could have readily accomplished thesame task by using a for statement. In fact, a for statement canalways be translated into an equivalent while statement, and viceversa.For example, the general for statementfor ( init_expression; loop_condition; loop_expression)program statement;can be equivalently expressed in the form of a while statement asinit_expression;while ( loop_condition){

program statement;loop_expression;

}Once you become familiar with the use of the while statement, you willgain a better feel as to when it seems more logical to use a while andwhen to use a for. In general, a loop that is executed a predeterminednumber of times is a prime candidate for implementation as a forstatement. Also, if the initial expression, looping expression, andlooping condition all involve the same variable, then the forstatement is probably the right choice. The following program willfind the gcd of two nonnegative integer values typed in by the user.Program 5.7 Finding the Greatest Common Divisor/* Program to find the greatest common divisor of two nonnegativeinteger values */#include <stdio.h>int main (void)

C programming 23{

int u, v, temp;printf ("Please type in two nonnegative integers.\n");scanf ("%i%i", &u, &v);while ( v != 0 ) {

temp = u % v;u = v;v = temp;

}printf ("Their greatest common divisor is %i\n", u);return 0;

} The do Statement The two looping constructs that we have discussed thus far both makea test of the condition before the loop is executed. Therefore, thebody of the loop may never be executed at all if the condition is notsatisfied. When developing programs it sometimes becomes desirable tohave the test made at the end of the loop rather than at thebeginning. Naturally, the C language provides a special languageconstruct to handle such a situation. This looping statement is knownas the do statement. The syntax of this statement is as shown:doprogram statement;while ( expression );Program 5.8 Reversing the Digits of a Number// Program to reverse the digits of a number #include <stdio.h>int main (void){

int number, right_digit;printf ("Enter your number.\n");scanf ("%i", &number);while ( number != 0 ) {

right_digit = number % 10;printf ("%i", right_digit);number = number / 10;

}

C programming 24printf ("\n");return 0;

}The break StatementSometimes when executing a loop, it becomes desirable to leave theloop as soon as a certain condition occurs (for instance, you detectan error condition, or you reach the end of your data prematurely).Thebreakstatement can be used for this purpose.Execution of the breakstatement causes the program to immediately exitfrom the loop it is executing, whether it’s a for, while, or do loop.Subsequent statements in the loop are skipped, and execution of theloop is terminated. Execution continues with whatever statementfollows the loop.If a break is executed from within a set of nested loops, only theinnermost loop in which the break is executed is terminated. Theformat of the breakstatement is simply the keyword break followed by asemi-colon:break;

The continueStatementThe continuestatement is similar to the breakstatement except itdoesn’t cause the loop to terminate. Rather, as its name implies, thisstatement causes the loop in which it is executed to be continued. Atthe point that the continuestatement is executed, any statements inthe loop that appear after the continuestatement are automaticallyskipped. Execution of the loop otherwise continues as normal. Thecontinuestatement is most often used to bypass a group of statementsinside a loop based upon some condition, but to otherwise continueexecution of the loop. The format of the continuestatement is simplycontinue;

6. MAKING DECISIONSThe C programming language also provides several other decision-makingconstructs,which are covered in this chapter:

The ifstatement The switchstatement The conditional operator

The If Statement The C programming language also provides a general decision makingcompatibility in the form of a language construct known as the ifstatement. The general format of this statement isIf(expression )

C programming 25{ programming statement }Imagine if you will that we could translate a statement such as "If itis not raining then I will go swimming" into the C language. Using theabove format for the If statement, this might be "written" in C asfollows:if ( it is not raining )I will go swimmingThe If statement is used to stipulate execution of a program statementbased on specified conditions. I will go swimming if it is notraining. Similarly, in the program statement if ( count > COUNT_LIMIT )printf ("Count limit exceeded\n");only if the value of count is greater than the value of COUNT_LIMITwill the prlntf statement be executed otherwise, it will be ignored bythe system. Program 6.1 Calculating the Absolute Value of an Integer// Program to calculate the absolute value of an integer int main (void){

int number;printf ("Type in your number: ");scanf ("%i", &number);if ( number < 0 )number = -number;printf ("The absolute value is %i\n", number);return 0;

}After a message is displayed to the user and the integer value that isentered stored into number, the program tests the value of number tosee if it is less than zero. If it is, then the following programstatement, which negates the value of number, is executed. If thevalue of number is not less than zero, then this program statement isautomatically skipped. The absolute value of number is then displayedby the program, and program execution ends. The If.else Construct

C programming 26Let us now write a program that determines whether an integer valuetyped in by the user is even or odd, and then displays an appropriatemessage at the terminal.Program 6.3 Determining if a Number Is Even or Odd// Program to determine if a number is even or odd #include <stdio.h>int main (void){

int number_to_test, remainder;printf ("Enter your number to be tested.: ");scanf ("%i", &number_to_test);remainder = number_to_test % 2;if ( remainder == 0 )

printf ("The number is even.\n");if ( remainder != 0 )

printf ("The number is odd.\n");return 0;

}After the number is typed in by the user, the remainder after divisionby 2 is calculated. The first if statement tests the value of thisremainder to see if it is equal to 0. If it is, then the message "Thenumber is even." is displayed at the terminal.The second if statement tests the value of remainder to see if it isnot equal to zero. If it is not, then a message is displayed to informthe user that the number is odd.The fact of the matter is that whenever the first if statementsucceeds, the second one must fail, and vice versa. In C, this isknown as the if-else construct and the general format is as followsIf(expression)program statement 1;elseprogram statement2;The If-else is actually just an extension of the general format of theIf statement. If the result of the evaluation of the expression isTRUE, then program statement 1, which immediately follows, isexecuted; otherwise, program statement 2 is executed. In either case,either program statement 1 or program statement 2 will be executed,but not both.Compound Relational Tests

C programming 27The C language provides the mechanisms necessary to perform thesetypes of compound relational fests. A compound relational test issimply one or more simple relational tests joined by either thelogical AND or the logical OR operator. These operators arerepresented by the character pairs && and II (two vertical barcharacters), respectively. As an example, the C statementif ( grade >= 70 && grade <= 79 )++grades_70_to_79;

will increment the value of grades 70 to 79 only if the value of gradeis greater than or equal to 70 and less than or equal to 79. In a likemanner, the statementif ( index < 0 || index > 99 )printf ("Error - index out of range\n");

will cause execution of the prlntf statement if value is less than 0or greater than 99. The compound operators can be used to formextremely complex expressions in C. Two words of advice are in order.First, when forming compound relational expressions, use parenthesesto aid readability of the expression and to avoid getting into troublebecause of a mistaken assumption about the precedence of the variousoperators in the expression. (The && operator has lower precedencethan any arithmetic or relational operator but higher precedence thanthe II operator.) Program 6.5 Determining if a Year Is a Leap Year// Program to determines if a year is a leap year #include <stdio.h>int main (void){

int year, rem_4, rem_100, rem_400;printf ("Enter the year to be tested: ");scanf ("%i", &year);rem_4 = year % 4;rem_100 = year % 100;rem_400 = year % 400;if ( (rem_4 == 0 && rem_100 != 0) || rem_400 == 0 )

printf ("It's a leap year.\n");elseprintf ("Nope, it's not a leap year.\n");return 0;

}

C programming 28 Nested If Statements In discussions of the general format of the ifstatement, we indicated that if the result of evaluating theexpression inside the parentheses were TRUE, then the statement thatimmediately followed would be executed. It is perfectly valid thatthis program statement be another if statement, as in the statementif ( game_is_over == 0 )if ( player_to_move == YOU )printf ("You'r Move\n");If the value of game_is-over is zero, then the following statementwill be executed, which is in turn another if statement. This ifstatement will compare the value of player_to_Move against YOU. If thetwo values are equal, then the message "Your Move" will be displayedat the terminal. Therefore, the printf statement will be executedonly if game.Js over equals 0 and player_to_Move equals YOU. In fact,this statement above could have been equivalently formulated usingcompound relationals as followsif ( gameIsOver == 0 && playerToMove == YOU )printf ("Your Move\n");

A more practical example of "nested" if statements would be if weadded an else clause to the above example as shownif ( gameIsOver == 0 )

if ( playerToMove == YOU )printf ("Your Move\n");

elseprintf ("My Move\n");

Execution of this statement proceeds as described above. However, ifgame_is_over equals 0, and the value of player_to_Move is not equal toYOU, then the else clause will be executed. This will display themessage "My Move" at the terminal. If game_is_Over does not equal 0,then the entire if statement that follows, including its associatedelse clause, will be skipped.Note how the else clause is associated with the if statement thattests the value of player_to_Move, and not with the if statement thattests the value of game_is_over. The general rule is that an elseclause is always associated with the last if statement that does notcontain an else We can go one step further and can add an else clauseto the outermost if statement in the above example. This else clausewould be executed if the value of game_is_over is not 0if ( gameIsOver == 0 )

if ( playerToMove == YOU )

C programming 29printf ("Your Move\n");

elseprintf ("My Move\n");

elseprintf ("The game is over\n");

The else If ConstructWe mentioned that the statement that followed an else could be anyvalid C program statement, so why not another if? Thus, in the generalcase, we could writeif ( expression 1 )program statement 1;elseif ( expression 2 )program statement 2;elseprogram statement 3;Which effectively extends the if statement from a two-valued logicdecision to a three-valued logic decision. We can continue to add ifstatements to the else clauses in the manner shown above toeffectively extend the decision to an n-valued logic decision.The above construct is so frequently used that it is generallyreferred to as an else if construct, and is usually formatteddifferently from that shown above asif ( expression 1 )

program statement 1;else if ( expression 2 )

program statement 2;else

program statement 3;This latter method of formatting improves the readability of thestatement and makes it clearer that a three-way decision is beingmade. The next program illustrates the use of the else if construct byimplementing the sign function discussed above.Program 6.6 Implementing the Sign Function// Program to implement the sign function

C programming 30#include <stdio.h>int main (void){

int number, sign;printf ("Please type in a number: ");scanf ("%i", &number);if ( number < 0 )

sign = -1;else if ( number == 0 )

sign = 0;else // Must be positive

sign = 1;printf ("Sign = %i\n", sign);return 0;

}If the number that is entered is less than zero, then sign is assignedthe value -1; otherwise, if the number is equal to zero, then sign isassigned the value 0; otherwise the number must be greater than zero,so sign is assigned the value 1. In order to read a single characterfrom the terminal, the format characters %C are used in the scanfcall.Program 6.7 Categorizing a Single Character Entered at the Terminal// Program to categorize a single character that is entered at theterminal #include <stdio.h>int main (void){

char c;printf ("Enter a single character:\n");scanf ("%c", &c);if ( (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') )

printf ("It's an alphabetic character.\n");else if ( c >= '0' && c <= '9' )

printf ("It's a digit.\n");else

printf ("It's a special character.\n");return 0;

}The first test that is made after the character is read determines ifthe char variable c is an alphabetic character or not. This is done by

C programming 31testing if the character is either a lower-case letter or an upper-case letter. The former test is made by the expression( c >= 'a' && c <= 'z' )

which will be TRUE if c is within the range of characters 'a' through'z', that is, if c is a lower-case letter. The latter test is made bythe expression( c >= 'A' && c <= 'Z' )which will be TRUE if c is within the range of characters 'A' through'Z', that is, if c is an upper-case letter. If the variable c is analphabetic character, then the first if test will succeed and themessage "It's an alphabetic character." will be displayed. If the testfails, then the else if clause will be executed. This clausedetermines if the character is a digit. Note that this test comparesthe character c against the characters '0' and '9' and not theintegers 0 and 9. If c is a digit character, then the phrase "It's adigit." will be displayed. Otherwise, if c is not alphabetic and isnot a digit, then the final else clause will be executed, to displaythe phrase. "It's a special character." at the terminal. Execution ofthe program will then be complete.The switch StatementThe type of if else statement chain that we encountered in the lastprogram example where the value of a variable is successively comparedagainst different values is so commonly used when developing programsthat a special program statement exists in the C language forperforming precisely this function. The name of the statement is theswitch statement, and its general format is as shown:switch ( expression){case value: program statement;

program statement;break;

case value2: program statement;program statement;break;

case value n: program statement; program statement; break;

C programming 32default: program statement;

program statement;break;

The expression enclosed within parentheses is successively comparedagainst the values value}, value2, ... , valuen, which must be simpleconstants or constant expressions. If a case is found whose value isequal to the value of expression, then the program statements thatfollow the case are executed. You will note that if more than one such program statement isincluded, that they do not have to be enclosed within braces. Thekeyword break-otherwise known as the break statement-signals the endof a particular case and causes execution of the switch statement tobe terminated. You must remember to include the break statement at theend of every case. Forgetting to do so for a particular case willcause program execution to continue into the next case whenever thatcase gets executed.The special optional case called default is executed if the value ofexpression does not match any of the case values. In fact, the generalform of the switch statement can be equivalently expressed as an ifstatement as follows:if ( expression == value) ){program statement;program statement;}else if ( expression == value2){program statement;program statement;else if ( expression = = value n ){program statement;program statement;}else{

C programming 33program statement;program statement;} we can translate the big if statement into an equivalent switchstatement. We will call this new program.Program 6.9 Revising the Program to Evaluate Simple Expressions/* Program to evaluate simple expressions of the form value operatorvalue */#include <stdio.h>int main (void){

float value1, value2;char operator;printf ("Type in your expression.\n");scanf ("%f %c %f", &value1, &operator, &value2);switch (operator){

case '+': printf ("%.2f\n", value1 + value2);break;

case '-':printf ("%.2f\n", value1 - value2);break;

case '*':printf ("%.2f\n", value1 * value2);break;

case '/':if ( value2 == 0 )printf ("Division by zero.\n");

elseprintf ("%.2f\n", value1 / value2);

break;default:printf ("Unknown operator.\n");

break;}return 0;

}After the expression has been read in, the value of operator issuccessively compared against the values as specified by each case.When a match is found, the statements contained inside the case willbe executed. The break statement will then send execution out of theswitch statement, where execution of the program will be complete. If

C programming 34none of the cases match the value of operator, then the default case,which displays "Unknown operator.", will be executed.The break statement in the default case is actually unnecessary in theprogram above, since no statements follow this case inside the switch.Nevertheless, it is a good programming habit to remember to includethe break at the end of every case.When writing a switch statement, no two case values may be the same.However, we can associate more than one case value with a particularset of program statements. This is done simply by listing the multiplecase values before the common statements that are to be executed. Asan example, in the switch statementswitch (operator){...case '*':case 'x': printf ("%.2f\n", value1 * value2);

break;...}the printf statement, which multiplies value1 by value2, will beexecuted if operator is equal to an asterisk or to the lower-caseletter x.Boolean VariablesMany new programmers soon find themselves with the task of having towrite a program to generate a table of prime numbers. The first primeinteger is defined to be 2.The next prime is 3, because it is notevenly divisible by any integers other than 1 and 3, and 4 is notprime because it is evenly divisible by 2.There are several approaches that you can take to generate a table ofprime numbers. If you have the task of generating all prime numbers upto 50, for example, the most straight forward algorithm to generatesuch a table is simply to test each integer p for divisibility by allintegers from 2 through p–1.If any such integer evenly divided p, thenp is not prime; otherwise, it is a prime number.Program 6.10 Generating a Table of Prime Numbers// Program to generate a table of prime numbers #include <stdio.h>int main (void){

int p, d;

C programming 35_Bool isPrime;for ( p = 2; p <= 50; ++p ) {

isPrime = 1;for ( d = 2; d < p; ++d )

if ( p % d == 0 )isPrime = 0;

if ( isPrime != 0 )printf ("%i ", p);

}printf ("\n");return 0;

}A flag will typically assume only one of two different values. Furthermore, the value of a flag will usually be tested at least once in theprogram to see if it is "on" (TRUE) or "off" (FALSE) and someparticular action taken based on the results of the test. The Conditional Expression Operator the conditional expression operator is a ternary operator; that is, ittakes three operands. The two symbols that are used to denote thisoperator are the question mark ? and the colon . The first operand isplaced before the?, the second between the? and the third after the :.condition? expression1 : expression2condition is an expression, usually a relational expression, that isevaluated by the C system first whenever the conditional expressionoperator is encountered. If the result of the evaluation of conditionis TRUE, then expression is evaluated and the result of the evaluationbecomes the result of the operation. If condition evaluates FALSE,then expression2 is evaluated and its value becomes the result of theoperation.The conditional expression operator is most often used to assign oneof two values to a variable depending on some condition. For example,suppose we have an integer variable x and another integer variable s.If we wished to assign -1 to s if x were less than 0, and the value ofx2 to S otherwise, then the following statement could be written:s = ( x < 0 ) ? -1 : x * x;

7 Working with Arrays

The C language provides a capability that enables the user to define aset of ordered data items known as an array.

C programming 36Defining an ArrayIn C we can define a variable called grades, which represents not asingle value of a grade but an entire set of grades. Each element ofthe set can then be referenced by means of a number called an indexnumber or subscript. Where, in mathematics, a subscripted variable Xi refers to the ith

element x in a set, in C the equivalent notation is x[i]. So the expression grades[5](read as "grades sub 5") refers toelement number 5 in the array called grades. In C, array elements begin with number 0, so grades[0] actually refersto the first element of the array. The elements of arrays declared to be of type int, float, or char maybe manipulated in the same fashion as can ordinary variables: we canassign values to them, display their values, add to them, subtractfrom them, and so on. So if the following statements were to appear ina program

Program 7.1 Working with an Array#include <stdio.h>int main (void){

int values[10];int index;values[0] = 197;values[2] = -100;values[5] = 350;values[3] = values[0] + values[5]; values[9] = values[5] / 10; --values[2];for ( index = 0; index < 10; ++index )

C programming 37printf ("values[%i] = %i\n", index, values[index]);

return 0;}The variable index assumes the values 0 through 9, since the lastvalid subscript of an array is always one less than the number ofelements. Since we never assigned values to five of the elements inthe array-elements 1,4 and 6 through 8-the values that are displayedfor them are meaningless. Even though the program's output shows thesevalues as zero, the value of any uninitialized variable or arrayelement is simply the value that happens to be sitting around insidethe computer's memory at the time that the program is executed.Program 7.3 Generating Fibonacci Numbers// Program to generate the first 15 Fibonacci numbers #include <stdio.h>int main (void){

int Fibonacci[15], i;Fibonacci[0] = 0; // by definition Fibonacci[1] = 1; // ditto for ( i = 2; i < 15; ++i )Fibonacci[i] = Fibonacci[i-2] + Fibonacci[i-1];for ( i = 0; i < 15; ++i )

printf ("%i\n", Fibonacci[i]);return 0;

}Initializing Array Elementswe assign initial values to the elements of an array. This is done bysimply listing the initial values of the array, starting from thefirst element. Values in the list are separated by commas and theentire list is enclosed in a pair of braces. The statementint counters[5] = { 0, 0, 0, 0, 0 };

will declare an array called counters to contain five integer valuesand will initialize each of these elements to zero. In a similarfashion, the statementint integers[5] = { 0, 1, 2, 3, 4 };

will set the value of integers[0] to 0, integers[1] to 1, integers[2]to 2, and so on. Arrays of characters are initialized in a similarmanner; thus the statementchar letters[5] = { 'a', 'b', 'c', 'd', 'e' };

C programming 38will define the character array letters and will initialize the fiveelements to the characters 'a', 'b', 'c', 'd', and 'e', respectively.It is not necessary to completely initialize an entire array. If lessinitial values are specified, then only as many elements will beinitialized. The remaining values in the array will be set to zero. Sothe declarationfloat sample_data[500] = { 100.0, 300.0, 500.5 };

will initialize the first three values of sample_data to 100.0, 300.0,and 500.5, and will set the remaining 497 elements to zero. Thefollowing program illustrates the two types of array initializationtechniques.Program 7.5 Initializing Arrays#include <stdio.h>int main (void){

int array_values[10] = { 0, 1, 4, 9, 16 };int i;for ( i = 5; i < 10; ++i )

array_values[i] = i * i;for ( i = 0; i < 10; ++i )

printf ("array_values[%i] = %i\n", i, array_values[i]);return 0;

}In the declaration of the array array_values, the first five elementsof the . array are initialized to the square of their element number .The first for loop shows how this same type of initialization can beperformed inside a loop. This loop sets each of the elements 5-9 tothe square of its element number. The second for loop simply runsthrough all 10 elements to display their values at the terminal.Character ArraysThe purpose of the following program is to simply illustrate how acharacter array can be used. Program 7.6 Introducing Character Arrays#include <stdio.h>int main (void){

char word[] = { 'H', 'e', 'l', 'l', 'o', '!' };int i;for ( i = 0; i < 6; ++i )

printf ("%c", word[i]);

C programming 39printf ("\n");return 0;

}The C language allows you to define an array without specifying thenumber of elements in the array. If this is done, then the size of thearray will be determined automatically based on the number ofinitialization elements. Since in the above program there are sixinitial values listed for the array word, the C language implicitly"dimensions" the array to six elements. Base Conversion Using Arrays// Program to convert a positive integer to another base #include <stdio.h>int main (void){

const char baseDigits[16] = { '0', '1', '2', '3', '4', '5', '6', '7','8', '9', 'A', 'B', 'C', 'D', 'E', 'F'

}; int convertedNumber[64];long int numberToConvert;int nextDigit, base, index = 0;// get the number and the base printf ("Number to be converted? ");scanf ("%ld", &numberToConvert);printf ("Base? ");scanf ("%i", &base);// convert to the indicated base do {

convertedNumber[index] = numberToConvert % base; ++index; numberToConvert = numberToConvert / base;

}while ( numberToConvert != 0 );// display the results in reverse order printf ("Converted number = ");for (--index; index >= 0; --index ) {

nextDigit = convertedNumber[index];printf ("%c", baseDigits[nextDigit]);

}printf ("\n");return 0;

}Multi-Dimensional Arrays

C programming 40The C language allows arrays of any dimension to be defined. We willtake a look at two-dimensional arrays. One of the most naturalapplications for a two-dimensional array arises in the case of amatrix. Consider the 4 X 5 matrix shown below

In mathematics it is quite common to refer to an element of the abovematrix by use of a double subscript. So if we called the matrix aboveM, then the notation Mi,j would refer to the element in the ith row , jth

column, where i ranges from 1 through 4, and j ranges from 1 through5. So the notation M3,2 would refer to the value 20, which is found inthe 3rd row, 2nd column of the above matrix. In a similar fashion, M4,5

would refer to the element contained in the 4th row, 5th column : thevalue 6. In C there is an analogous notation to be used when referring toelements of a two-dimensional array. C likes to start numbering thingsat 0, the first row of the matrix is actually row 0, and the firstcolumn of the matrix is column 0.The above matrix would then have rowand column designations as shown below.

Whereas in mathematics the notation Mi,j is used, in C the equivalentnotation is Remember, the first index number refers to the rownumber, while the second index number references the column. So theexpressionsum = M[0][2] + M[2][4];would add the value contained in row 0, column 2 which is 3 to thevalue contained in row 2, column 4 which is 14 and would assign theresult of 11 to the variable sum. Two-dimensional arrays are declaredthe same way one-dimensional arrays are; thusint M[4][5];declares the array M to be a two-dimensional array consisting of 4rows and 5 columns, for a total of 20 elements. Each position in thearray is defined to contain an integer value. Two-dimensional arrays

C programming 41may be initialized in a manner analogous to their one-dimensionalcounterparts. When listing elements for initialization, the values arelisted by row. Brace pairs are used to separate the list ofinitializes for one row from the next. So to define and initializethe array M to the elements listed in the above table, a statementsuch as the following could be used:int M[4][5] = {

{ 10, 5, -3, 17, 82 },{ 9, 0, 0, 8, -7 },{ 32, 20, 1, 0, 14 },{ 0, 0, 8, 7, 6 }

};Pay particular attention to the syntax of the above statement. Commasare required after each brace that closes off a row, except in thecase of the last row. The use of the inner pairs of braces is actuallyoptional. If not supplied, then initialization proceeds by row. Thusthe above statement could also have been written as –int M[4][5] = { 10, 5, -3, 17, 82, 9, 0, 0, 8, -7, 32, 20, 1, 0, 14,0, 0, 8, 7, 6 };As with one dimensional arrays, it is not required that the entirearray be initialized. A statement such as int M[4][5] = {

{ 10, 5, -3 },{ 9, 0, 0 },{ 32, 20, 1 },{ 0, 0, 8 }

};would initialize the first three elements of each row of the matrix tothe indicated values. The remaining values will be set to zero. Inthis case the inner pairs of braces are required to force the correctinitialization. Without them, the first two rows and the first twoelements of the third row would have been initialized instead .Variable-Length ArraysThis section discusses a feature in the language that enables you towork with arrays inyour programs without having to give them a constant size.1. As of this writing, full support for variable-length arrays was notoffered by all compilers.You might want to check your compiler’sdocumentation before you use this feature.Program 7.8 Generating Fibonacci Numbers Using Variable-Length Arrays// Generate Fibonacci numbers using variable length arrays

C programming 42#include <stdio.h>int main (void){

int i, numFibs;printf ("How many Fibonacci numbers do you want (between 1 and

75)? ");scanf ("%i", &numFibs);if (numFibs < 1 || numFibs > 75){

printf ("Bad number, sorry!\n");return 1;

}unsigned long long int Fibonacci[numFibs]; Fibonacci[0] = 0; // by definition Fibonacci[1] = 1; for ( i = 2; i < numFibs; ++i )

Fibonacci[i] = Fibonacci[i-2] + Fibonacci[i-1];for ( i = 0; i < numFibs; ++i )printf ("%llu ", Fibonacci[i]);

printf ("\n");return 0;

}First, the variables I and numFibs are declared. Latter variable isused to store the requested number of Fibonacci numbers that the userwants to generate. Notice the range of the entered value is checked bythe program, which is good programming practice. If the value is outof range, the program displays a message and returns a value of 1.Executing the return statement at that point in the program causes theprogram to ter-minate immediately, and no further statements areexecuted. After the number has been entered by the user, you see thestatementunsigned long long int Fibonacci[numFibs];The Fibonacci array is declared to contain numFibs elements. This iscalled a variable length array because the size of the array isspecified by a variable and not by a constant expression. Also, aspreviously noted, a variable can be declared anywhere in a program, aslong as the declaration occurs before the variable is first used.A technique known as dynamic memory allocation is also often used toallocate space for arrays while a program is executing. This involvesusing functions such as malloc and calloc that are in the standard Clibrary.

8 Working with Functions

C programming 43The C programming language has the fundamental element function. Theprintf and scanf routines are examples of functions. Indeed, each andevery program also used a function called main. The program functionprovides the mechanism for producing programs that are easy to write,read, understand, debug, modify, and maintain.Defining a FunctionFirst, you must understand what a function is, and then you canproceed to find out how it can be most effectively used in thedevelopment of programs. #include <stdio.h>int main (void){

printf ("Programming is fun.\n");return 0;

}Here is a function called printMessage that does the same thing:void printMessage (void){

printf ("Programming is fun.\n");}The differences between printMessage and the function main from aboveProgram is in the first and last line. The first line of a functiondefinition tells the compiler (in order from left to right) fourthings about the function:1. Who can call it 2. The type of value it returns3. Its name4. The arguments it takesThe first line of the printMessage function definition tells thecompiler that the function returns no value (the first use of thekeyword void), its name is printMessage, and that it takes noarguments (the second use of the keyword void). Obviously, choosingmeaningful function names greatly affects the program’s readability.In the above Program main is a specially recognized name in the Csystem that always indicates where the program is to begin execution.You must always have a main. You can add a main function to thepreceding code to end up with a complete program, as shown in Program8.1.Program 8.1 Writing a Function in C

C programming 44#include <stdio.h>void printMessage (void){

printf ("Programming is fun.\n");}int main (void){

printMessage ();return 0;

}Program 8.1 consists of two functions: printMessage and main. Programexecution always begins with main. Inside that function, the statementprintMessage(); appears. This statement indicates that the functionprintMessage is to be executed. The open and close parentheses areused to tell the compiler that printMessage is a function and that noarguments or values are to be passed to this function. When a functioncall is executed, program execution is transferred directly to theindicated function. Inside the printMessage function, the printfstatement is executed to display the message “Programming is fun.” atthe terminal. After the message has been displayed, the printMessageroutine is finished and the program returns to the main routine, whereprogram execution continues at the point where the function call wasexecuted.Arguments and Local VariablesWhen the printf function is called, you always supply one or morevalues to the function, the first value being the format string andthe remaining values being the specific program results to bedisplayed. These values, called arguments, greatly increase theusefulness and flexibility of a function. Unlike your printMessageroutine, which displays the same message each time it is called, theprintffunction displays whatever you tell it to display.You can define a function that accepts arguments. you developed anassortment of programs for calculating triangular numbers. Here, youdefine a function to generate a triangular number, calledappropriately enough, calculateTriangularNumber. As an argument to thefunction, you specify which triangular number to calculate. Thefunction then calculates the desired number and displays the resultsat the terminal. Program 8.4 shows the function to accomplish thistask and a Main routine to try it out.

C programming 45Program 8.4 Calculating the nth Triangular Number// Function to calculate the nth triangular number #include <stdio.h>void calculateTriangularNumber (int n){

int i, triangularNumber = 0;for ( i = 1; i <= n; ++i )triangularNumber += i;printf ("Triangular number %i is %i\n", n, triangularNumber);

}int main (void){

calculateTriangularNumber (10);calculateTriangularNumber (20);calculateTriangularNumber (50);return 0;

}Function Prototype DeclarationThe first line of the function: void calculateTriangularNumber (int n)is called the function prototype declaration. It tells the compilerthat calculateTriangularNumber is a function that returns no value(the keyword void) and that takes a single argument, called n, whichis an int. The name that is chosen for an argument, called its formalparameter name. After the formal parameter name has been defined, itcan be used to refer to the argument any where inside the body of thefunction.Automatic Local VariablesVariables defined inside a function are known as automatic localvariables because they are automatically “created” each time thefunction is called, and because their values are local to thefunction. The value of a local variable can only be accessed by thefunction in which the variable is defined. Its value cannot beaccessed by any other function. If an initial value is given to avariable inside a function, that initial value is assigned to thevariable each time the function is called.When defining a local variable inside a function, it is more precisein C to use the keyword auto before the definition of the variable. Anexample of this is as follows:auto int i, triangularNumber = 0;

C programming 46Program 8.5 Revising the Program to Find the Greatest Common Divisor/* Function to find the greatest common divisor of two nonnegativeinteger values */#include <stdio.h>void gcd (int u, int v){

int temp;printf ("The gcd of %i and %i is ", u, v);while ( v != 0 ) {

temp = u % v;u = v;v = temp;

}printf ("%i\n", u);

}int main (void){

gcd (150, 35);gcd (1026, 405);gcd (83, 240);return 0;

}Returning Function ResultsThe C language provides you with a convenient mechanism whereby theresults of a function can be returned to the calling routine. Thegeneral syntax of this construct is straightforward enough:return expression;This statement indicates that the function is to return the value ofexpression to thecalling routine. Functions Calling Functions Calling…Program 8.8 Calculating the Square Root of a Number// Function to calculate the absolute value of a number #include <stdio.h>float absoluteValue (float x){

if ( x < 0 )x = -x;

C programming 47return (x);

}// Function to compute the square root of a number float squareRoot (float x){

const float epsilon = .00001;float guess = 1.0;while ( absoluteValue (guess * guess - x) >= epsilon )

guess = ( x / guess + guess ) / 2.0;return guess;

}int main (void){

printf ("squareRoot (2.0) = %f\n", squareRoot (2.0));printf ("squareRoot (144.0) = %f\n", squareRoot (144.0));printf ("squareRoot (17.5) = %f\n", squareRoot (17.5));return 0;

}Declaring Return Types and Argument TypesThe C compiler assumes that a function returns a value of type int asthe default case. More specifically, when a call is made to afunction, the compiler assumes that the function returns a value oftype int unless either of the following has occurred:1. The function has been defined in the program before the functioncall is encountered.2. The value returned by the function has been declared before thefunction call is encountered.Not only is the function declaration used to declare the function’sreturn type, but itis also used to tell the compiler how many arguments the functiontakes and what theirtypes are.Here are some reminders and suggestions about functions:1. Remember that, by default, the compiler assumes that a functionreturns an int.2. When defining a function that returns an int, define it as such.3. When defining a function that doesn’t return a value, define it asvoid.

C programming 484. The compiler converts your arguments to agree with the ones thefunction expects only if you have previously defined or declared thefunction.5. To play it safe, declare all functions in your program, even ifthey are defined before they are called. Functions and ArraysAs with ordinary variables and values, it is also possible to pass thevalue of an array element and even an entire array as an argument to afunction. To pass a single array element to a function , the arrayelement is specified as an argument to the function in the normalfashion. Nothing special has to be done to handle single arrayelements passed as arguments. In the same manner as with a simplevariable, the value of the array element is copied into the value ofthe corresponding formal parameter when the function is called.Program 8.9 Finding the Minimum Value in an Array// Function to find the minimum value in an array #include <stdio.h>int minimum (int values[10]){

int minValue, i;minValue = values[0];for ( i = 1; i < 10; ++i )if ( values[i] < minValue )

minValue = values[i];return minValue;

}int main (void){

int scores[10], i, minScore;int minimum (int values[10]);printf ("Enter 10 scores\n");for ( i = 0; i < 10; ++i )

scanf ("%i", &scores[i]);minScore = minimum (scores);printf ("\nMinimum score is %i\n", minScore);return 0;

}Program 8.13A Multidimensional Variable-Length Arrays#include <stdio.h>

C programming 49int main (void){

void scalarMultiply (int nRows, int nCols, int matrix[nRows][nCols], int scalar);void displayMatrix (int nRows, int nCols, int matrix[nRows][nCols]);int sampleMatrix[3][5] = { { 7, 16, 55, 13, 12 },

{ 12, 10, 52, 0, 7 },{ -2, 1, 2, 4, 9 }

};printf ("Original matrix:\n");displayMatrix (3, 5, sampleMatrix);scalarMultiply (3, 5, sampleMatrix, 2);printf ("\nMultiplied by 2:\n");displayMatrix (3, 5, sampleMatrix);scalarMultiply (3, 5, sampleMatrix, -1);printf ("\nThen multiplied by -1:\n");displayMatrix (3, 5, sampleMatrix);return 0;

}// Function to multiply a matrix by a scalar void scalarMultiply (int nRows, int nCols, int matrix[nRows][nCols],int scalar){

int row, column;for ( row = 0; row < nRows; ++row )for ( column = 0; column < nCols; ++column )

matrix[row][column] *= scalar;}void displayMatrix (int nRows, int nCols, int matrix[nRows][nCols]){

int row, column;for ( row = 0; row < nRows; ++row) {for ( column = 0; column < nCols; ++column )

printf ("%5i", matrix[row][column]);printf ("\n");

}}Global Variables

C programming 50The global variables are defined first in the program. Since they arenot defined within any particular function, the C system classifiesthese variables as global variables, which means, that they can now bereferenced by any function in the program.The primary use of global variables is in programs in which manyfunctions must access the value of the same variable. Rather thanhaving to pass the value of the variable to each individual functionas an argument, the function can explicitly reference the variableinstead. Now there is a drawback with this approach. Because thefunction explicitly references a particular global variable, thegenerality of the function is somewhat reduced. So every time thatfunction is to be used, we must make sure that the global variableexists, by its particular name.The main point to be made about global variables is that while theiruse may reduce the number of arguments that need to be passed to afunction. Automatic and Static Variables ·This is the key to the concept of a static variable it does not comeand go as the function is called and returns. This implies that thevalue that a static variable has on leaving a function will be thesame value that variable will have the next time that the function iscalled.Static variables also differ with respect to their initialization. Astatic local variable is initialized once only at the start of overallprogram execution and not each time that the function is called.Furthermore the initial value specified for a static variable must bea simple constant or constant expression. In the function auto-staticdefined as follows:Program 8.15 Illustrating Static and Automatic Variables// Program to illustrate static and automatic variables #include <stdio.h>void auto_static (void){

int autoVar = 1;static int staticVar = 1;printf ("automatic = %i, static = %i\n", autoVar, staticVar);++autoVar;++staticVar;

}int main (void){

C programming 51int i;void auto_static (void);for ( i = 0; i < 5; ++i )

auto_static ();return 0;

}Recursive Functions Recursion is a process by which a function calls itself repeatedly,until some specified condition has been satisfied. Recursive functionscan be effectively used to briefly and efficiently solve problems.They are commonly used in applications in which the solution to aproblem can be expressed in terms of successively applying the samesolution to subsets of the problem. One example might be in theevaluation of expressions containing nested sets of parenthesizedexpressions. Other common applications involve the searching andsorting of data structures called trees and lists.Program 8.16 Calculating Factorials Recursively#include <stdio.h>int main (void){

unsigned int j;unsigned long int factorial (unsigned int n);for ( j = 0; j < 11; ++j )

printf ("%2u! = %lu\n", j, factorial (j));return 0;

}// Recursive function to calculate the factorial of a positive integerunsigned long int factorial (unsigned int n){

unsigned long int result;if ( n == 0 )

result = 1;else

result = n * factorial (n - 1);return result;

}UNIT-V

9.STRUCTURESThe structure, which is a data structure whose individual elements candiffer in type. Thus, a single structure might contain integer

C programming 52elements, floating-point elements and character elements. Pointers,arrays and other structures can also be included as elements within astructure. The individual structure elements are referred to asmembers.Defining structureIn general terms, the composition of a structure may be defined as struct tagname{member 1;member 2;……member m;};In this declaration, struct is a required keyword, tag is name thatidentifies structures of this type, and member 1, member 2,. . member mare individual member declarations.

Individual structure type variables can be declared as follows:Storage-class struct tag variable 1, variable 2,. .variable n are structure variable of type tag.Processing a structure : - The members of a structure are usuallyprocessed individually, as a separate entities. Therefore, we must beable to access the individual structure members. A structure member canbe accessed by writing variable.member.

Where variable refers to the name of a structure type variable, andmember refers to the name of a member within the structure. (.)Separates the variable name from the member name. Suppose we wished tostore today's date-which is 9/18/82. We can define a structure calleddate in the C language that consists of three components thatrepresent the month, day, and year. The syntax for such a definition israther straightforward as shown:struct date{

int month;int day;int year;

};The date structure defined above contains three integer members calledmonth, day, and year. The definition of date in a sense defines a newtype in the language in that variables may subsequently be declared tobe of type struct date, as in the declaration

C programming 53struct date today;We can also declare a variable purchase_date to be of the same type bya separate declaration such as struct date purchase_date;A member of a structure is accessed by specifying the variable namefollowed by a period and then the member name.Program 9.1 Illustrating a Structure// Program to illustrate a structure #include <stdio.h>int main (void){

struct date{

int month;int day;int year;

};struct date today;today.month = 9;today.day = 25;today.year = 2004;printf ("Today's date is %i/%i/%.2i.\n", today.month, today.day,today.year % 100);return 0;

}Using Structures in ExpressionsWhen it comes to the evaluation of expressions, structure membersfollow the same rules as ordinary variables do in the C language. Sodivision of an integer structure member by another integer isperformed as an integer division, as in century = today.year / 100 +1;Functions and StructuresC language has the ability to pass a structure to a function and toreturn one as well.Program 9.5 Updating the Time by One Second// Program to update the time by one second #include <stdio.h>struct time

C programming 54{

int hour;int minutes;int seconds;

};int main (void){

struct time timeUpdate (struct time now);struct time currentTime, nextTime;printf ("Enter the time (hh:mm:ss): ");scanf ("%i:%i:%i", &currentTime.hour,&currentTime.minutes, &currentTime.seconds);nextTime = timeUpdate (currentTime);

printf ("Updated time is %.2i:%.2i:%.2i\n", nextTime.hour,nextTime.minutes, nextTime.seconds );

return 0;}// Function to update the time by one second struct time timeUpdate (struct time now){

++now.seconds;if ( now.seconds == 60 ) { // next minute

now.seconds = 0;++now.minutes;if ( now.minutes == 60 )

{ // next hour now.minutes = 0;

++now.hour; if ( now.hour == 24 ) // midnight

now.hour = 0; }

}return now;

}Initializing Structures ·Initialization of structures is similar to initialization of arraysthe elements are simply listed inside a pair of braces, with eachelement separated by a comma.

C programming 55To initialize the date structure variable today to July 2, 2005, thestatementstruct date today = { 7, 2, 2005 }; can be used.Arrays of Structures You have seen how useful the structure is in enabling you to logicallygroup related elements together. C does not limit you to storingsimple data types inside an array; it is perfectly valid to define anarray of structures. For example,struct time experiments[10];defines an array called experiments, which consists of 10 elements.Each element inside the array is defined to be of type struct time. Initialization of arrays containing structures is similar toinitialization of multidimensionalarrays. So the statementstruct time runTime [5] = { {12, 0, 0}, {12, 30, 0}, {13, 15, 0} };Program 9.6 Illustrating Arrays of Structures// Program to illustrate arrays of structures #include <stdio.h>struct time{

int hour;int minutes;int seconds;

};int main (void){

struct time timeUpdate (struct time now);struct time testTimes[5] = { { 11, 59, 59 }, { 12, 0, 0 }, { 1,29, 59 }, { 23, 59, 59 }, { 19, 12, 27 }};int i;for ( i = 0; i < 5; ++i ) {

printf ("Time is %.2i:%.2i:%.2i", testTimes[i].hour,testTimes[i].minutes, testTimes[i].seconds);testTimes[i] = timeUpdate (testTimes[i]);printf (" ...one second later it's %.2i:%.2i:%.2i\n",testTimes[i].hour, testTimes[i].minutes,testTimes[i].seconds);

}

C programming 56return 0;

}Structures Within Structures C provides the user with an enormous amount of flexibility in definingstructures. For instance, it is possible to define a structure thatitself contains another structure as one or more of its members, aswell as define structures that contain arrays. For example, we mightneed to set up a list of events that are to occur at a particular dateand time.struct dateAndTime{

struct date sdate;struct time stime;

};Stluctures Containing ArraysIt is possible to define structures that contain arrays as members.One of the most common applications of this type is setting up anarray of characters inside a structure. For example, suppose you wantto define a structure called month that contains as its members thenumber of days in the month as well as a three character abbreviationfor the month name. struct month{

int numberOfDays;char name[3];

};Program 9.7 Illustrating Structures and Arrays// Program to illustrate structures and arrays #include <stdio.h>int main (void){

int i;struct month{int numberOfDays;char name[3];};const struct month months[12] =

C programming 57{ { 31, {'J', 'a', 'n'} }, { 28, {'F', 'e','b'} },{ 31, {'M', 'a', 'r'} }, { 30, {'A', 'p','r'} },{ 31, {'M', 'a', 'y'} }, { 30, {'J', 'u','n'} },{ 31, {'J', 'u', 'l'} }, { 31, {'A', 'u','g'} },{ 30, {'S', 'e', 'p'} }, { 31, {'O', 'c','t'} },{ 30, {'N', 'o', 'v'} }, { 31, {'D', 'e','c'} } };

printf ("Month Number of Days\n");printf ("----- --------------\n");for ( i = 0; i < 12; ++i )

printf (" %c%c%c %i\n",months[i].name[0], months[i].name[1],months[i].name[2], months[i].numberOfDays);return 0;

}Structure VariantsIt is valid to declare a variable to be of a particular structure typeat the same time that the structure is defined. This is done simply byincluding the variable name (or names) before the terminatingsemicolon of the structure definition.struct date{

int month;int day;int year;

} todaysDate, purchaseDate;defines the structure date and also declares the variables todaysDateand purchaseDate to be of this type.You can also assign initial valuesto the variables in the normal fashion. Thus,struct date{int month;int day;int year;

C programming 58} todaysDate = { 1, 11, 2005 };defines the structure date and the variable todaysDate with initialvalues as indicated. 10.CHARACTER STRINGSTo assign a single character to such a variable, the character wasenclosed within a pair of single quote marks. plusSign = '+';Thus, the assignment hold more than a single character, and this isprecisely where the array of characters comes into play.char word [] = { 'H', 'e', 'l', 'l', 'o', '!' };In order to print out the contents of the array word, we ran througheach element in the array and displayed it using the %c formatcharacters. Concatenate to be called as follows:concat (result, str1, n1, str2, n2);where str1and str2 represent the two character arrays that are to beconcatenated andn1 and n2 represent the number of characters in the respective arrays.Program 10.1 Concatenating Character Arrays// Function to concatenate two character arrays #include <stdio.h>void concat (char result[], const char str1[], int n1, const charstr2[], int n2){

int i, j;// copy str1 to result for ( i = 0; i < n1; ++i )result[i] = str1[i];// copy str2 to result for ( j = 0; j < n2; ++j )result[n1 + j] = str2[j];

}int main (void){

void concat (char result[], const char str1[], int n1, const char str2[], int n2);const char s1[5] = { 'T', 'e', 's', 't', ' '};const char s2[6] = { 'w', 'o', 'r', 'k', 's', '.' };char s3[11];int i;concat (s3, s1, 5, s2, 6);

C programming 59for ( i = 0; i < 11; ++i )printf ("%c", s3[i]);printf ("\n");return 0;

}Variable Length Character Strings In the C language, the special character that is used to signal theend of a string is known as the null character, and is written as '\0'. So the statementconst char word [] = { 'H', 'e', 'l', 'l', 'o', '!', '\0' };defines a character array called word that contains seven characters,the last of which is the null character. To begin with anillustration of how these variable length character strings are used,let us write a function that counts the number of characters in acharacter string. We will call function string length and have it takeas its argument a character array that is terminated by the nullcharacter. The function will determine the number of characters in thearray and will return this value back to the calling routine. We willdefine the number of characters in the array as the number ofcharacters up to, but not including, the terminating null character. Program 10.2 Counting the Characters in a String// Function to count the number of characters in a string #include <stdio.h>int stringLength (const char string[]){

int count = 0;while ( string[count] != '\0' )

++count;return count;

}int main (void){

int stringLength (const char string[]);const char word1[] = { 'a', 's', 't', 'e', 'r', '\0' };const char word2[] = { 'a', 't', '\0' };const char word3[] = { 'a', 'w', 'e', '\0' };printf ("%i %i %i\n", stringLength (word1),stringLength (word2), stringLength (word3));return 0;

}

C programming 60Initializing and Displaying Character StringsThe first feature involves the initialization of character arrays. Cpermits a character array to be initialized by simply specifying aconstant character string rather than a list of individual characters.So, for example, the statement char word[] = { "Hello!" };can be used to set up an array of characters called word with theinitial characters 'H', 'e', 'l', 'l', '0', '\0', respectively. Thisstatement is equivalent to the statementchar word[] = { 'H', 'e', 'l', 'l', 'o', '!', '\0' };The special format characters %s inside a printf format string can beused to display an array of characters that is terminated by the nullcharacter. So with the definition of word above, the prlntf callprintf ("%s\n", word);can be used to display the entire contents of the word array at theterminal. The prlntf function assumes when it encounters the %s formatcharacters that the corresponding argument is a character string thatis terminated by a null character.Program 10.3 Concatenating Character Strings#include <stdio.h>int main (void){

void concat (char result[], const char str1[], const charstr2[]);const char s1[] = { "Test " };const char s2[] = { "works." };char s3[20];concat (s3, s1, s2);printf ("%s\n", s3);return 0;

}// Function to concatenate two character strings void concat (char result[], const char str1[], const char str2[]){

int i, j;// copy str1 to result for ( i = 0; str1[i] != '\0'; ++i )result[i] = str1[i];// copy str2 to result for ( j = 0; str2[j] != '\0'; ++j )

C programming 61result[i + j] = str2[j];// Terminate the concatenated string with a null characterresult [i + j] = '\0';

}Testing Two Character Strings for EqualityWe cannot directly test two strings to see if they are equal in C witha statement such asif ( string! == string2 )since the equality operator can only be applied to simple variabletypes such as float's, int's or char's and not to more sophisticatedtypes such as structures or ,arrays.Program 10.4 Testing Strings for Equality// Function to determine if two strings are equal #include <stdio.h>#include <stdbool.h>bool equalStrings (const char s1[], const char s2[]){

int i = 0;bool areEqual;while ( s1[i] == s2 [i] && s1[i] != '\0' && s2[i] != '\0' )

++i;if ( s1[i] == '\0' && s2[i] == '\0' )

areEqual = true; else

areEqual = false; return areEqual;

}int main (void){

bool equalStrings (const char s1[], const char s2[]);const char stra[] = "string compare test";const char strb[] = "string";printf ("%i\n", equalStrings (stra, strb));printf ("%i\n", equalStrings (stra, stra));printf ("%i\n", equalStrings (strb, "string"));return 0;

}Inputting Character Strings

C programming 62The scanf function can be used with the %s format characters to readin a string of characters up to a blank space or up to the end of theline, whichever occurs first. So the statementschar string[81];scanf ("%s", string);will have the effect of reading in a character string from theterminal and storing it inside the character array string.Program 10.5 Reading Strings with scanf// Program to illustrate the %s scanf format characters #include <stdio.h>int main (void){

char s1[81], s2[81], s3[81];printf ("Enter text:\n");scanf ("%s%s%s", s1, s2, s3);printf ("\ns1 = %s\ns2 = %s\ns3 = %s\n", s1, s2, s3);return 0;

}Single Character InputA function called getchar is most likely available for reading asingle character from the terminal. Repeated calls to the getcharfunction will return successive single characters from the input. Whenthe end of the line has been reached, the function will return thenewline character '\n'. However, the getchar function is a more directapproach, since its sole purpose is for reading in single characters,and therefore does not require any arguments. The function returns asingle character that may be assigned to a variable or used as desiredby the program.C is another function called gets. The sole purpose of this functionis to read in a single line of text from the terminal. #include <stdio.h>int main (void){

int i;char name[81], city[81];printf ("Enter your name:\n");for(i=0;(name[i]=getchar())!=’\n’;i++);printf ("Enter your city:\n”);city=gets()

C programming 63printf(“\n Name and City is :”);puts(name);printf(“\n”);puts(city);

}The Null StringA character string that contains no characters other than the nullcharacter has a special name in the C language; it is called the nullstring. Sometimes it becomes desirable to set the value of acharacter string to the null string. Escape Characters other characters be combined with the backslash character to perform"special" functions. These various "backs lash characters," commonlyreferred to as escape characters are summarized in the followingtable.

Character Strings. Structures. and Arrays There are many ways to combine the basic elements of the C programminglanguage to form very powerful programming constructs. This nextprogram example further illustrates the notion of arrays ofstructures, combined with the variable length character string.Binary Search AlgorithmStep 1: Set low to 0,highto n– 1.Step 2: If low > high, x does not exist in M and the algorithmterminates.Step 3: Set mid to (low + high) / 2.Step 4: If M[mid] < x, set low to mid+ 1 and go to step 2.Step 5: If M[mid] > x, set high to mid– 1 and go to step 2.

C programming 64Step 6: M[mid] equals x and the algorithm terminates.Character Conversions and Arithmetic Operations Whenever a character constant or variable is used in an expression inC, it is automatically converted to, and subsequently treated as, aninteger value by the system. This applies when characters are passedas arguments to functions as well: they are automatically converted tointegers by the system.Program 10.11 Converting a String to its Integer Equivalent// Function to convert a string to an integer #include <stdio.h>int strToInt (const char string[]){

int i, intValue, result = 0;for ( i = 0; string[i] >= '0' && string[i] <= '9'; ++i ){

intValue = string[i] - '0';result = result * 10 + intValue;

}return result;

}int main (void){

int strToInt (const char string[]);printf ("%i\n", strToInt("245"));printf ("%i\n", strToInt("100") + 25);printf ("%i\n", strToInt("13x5"));return 0;

}11.POINTERS

The most sophisticated features of the C programming language:pointers. Pointers enable us to effectively represent complex datastructures, to change values passed as arguments to functions, to workwith memory that has been allocated "dynamically" , and to moreconcisely and efficiently deal with arrays. Suppose we define avariable called count as follows:int count = 10;We can define another variable called int_pointer, which will enableus to indirectly access the value of count by the declaration. int *int_pointer;

C programming 65The asterisk defines to the C system that the variable int_pointer isof type pointer. More precisely, the combination int * specifies thatthe variable is of type "pointer to int," meaning that it will be usedin the program to indirectly access the value of one or more integervariables.Therefore, with the definitions of count and int_pointer asabove, we can write a statement in C such asint_pointer = &count;to set up the indirect reference between int_pointer and count. Theaddress operator has the effect of assigning to the variableint_pointer not the value of count but a pointer to the variablecount. The link that has been made between int_pointer and count isconceptualized in Fig.

Program 11.1 Illustrating Pointers// Program to illustrate pointers#include <stdio.h>int main (void){

int count = 10, x;int *int_pointer;int_pointer = &count;x = *int_pointer;printf ("count = %i, x = %i\n", count, x);return 0;

}the variable int_pointer is declared to be of type "pointer to int." Using Pointers in ExpressionsIn Program 11.3, two integer pointers, p1 and p2, are defined. Noticehow the value referenced by a pointer can be used in an arithmeticexpression. Program 11.3 Using Pointers in Expressions// More on pointers #include <stdio.h>

C programming 66int main (void){

int i1, i2;int *p1, *p2;i1 = 5;p1 = &i1;i2 = *p1 / 2 + 10;p2 = p1;printf ("i1 = %i, i2 = %i, *p1 = %i, *p2 = %i\n", i1, i2, *p1,*p2);return 0;

}Working with Pointers and StructuresYou have seen how a pointer can be defined to point to a basic datatype, such as an int or a char. But pointers can also be defined topoint to structures.struct date{

int month;int day;int year;

};Just as you defined variables to be of type struct date, as in structdate todaysDate;So can you define a variable to be a pointer to a struct datevariable:struct date *datePtr;You can set it to point to todaysDatewith the assignment statementdatePtr = &todaysDate;After such an assignment has been made, you then can indirectly accessany of the members of the datestructure pointed to by datePtrin thefollowing way: (*datePtr).day = 21;Pointers to structures are so often used in C that a special operatorexists in the language. The structure pointer operator ->, which isthe dash followed by the greater than sign, permits expressions thatwould otherwise be written as (*x).y to be more clearly expressed asx->yProgram 11.4 Using Pointers to Structures// Program to illustrate structure pointers #include <stdio.h>

C programming 67int main (void){struct date{

int month;int day;int year;

};struct date today, *datePtr;datePtr = &today;datePtr->month = 9;datePtr->day = 25;datePtr->year = 2004;printf ("Today's date is %i/%i/%.2i.\n",datePtr->month, datePtr->day, datePtr->year % 100);return 0;}Structures Containing PointersNaturally, a pointer also can be a member of a structure. In thestructure definitionstruct intPtrs{

int *p1;int *p2;

};a structure called intPtrsis defined to contain two integer pointers,the first one called p1and the second one p2.You can define a variableof type struct intPtrsin the usual way:struct intPtrs pointers;The variable pointerscan now be used in the normal fashion,remembering that pointers itself is not a pointer, but a structurevariable that has two pointers as its members.Program 11.5 Using Structures Containing Pointers// Function to use structures containing pointers #include <stdio.h>int main (void){

struct intPtrs{

C programming 68int *p1;int *p2;

};struct intPtrs pointers;int i1 = 100, i2;pointers.p1 = &i1;pointers.p2 = &i2;*pointers.p2 = -97; printf ("i1 = %i, *pointers.p1 = %i\n", i1, *pointers.p1); printf ("i2 = %i, *pointers.p2 = %i\n", i2, *pointers.p2);return 0;

}Linked ListsThe concepts of pointers to structures and structures containingpointers are very powerful ones in C, for they enable you to createsophisticated data structures, such as linked lists, doubly linkedlists, and trees. Suppose you define a structure as follows:struct entry{

int value;struct entry *next;

};This defines a structure called entry, contains two members. Thefirst member of the structure is a simple integer called value. Thesecond member of the structure is a member called next, which is apointer to an entry structure. Think about this for a moment.Contained inside an entry structure is a pointer to another entrystructure. Suppose you define two variables to be of type struct entryas follows: struct entry n1, n2;You set the next pointer of structure n1 to point to structure n2 byexecuting the following statement: n1.next = &n2;Program 11.6 Using Linked Lists// Function to use linked Lists #include <stdio.h>int main (void){

struct entry{

int value;

C programming 69struct entry *next;

};struct entry n1, n2, n3;int i;n1.value = 100;n2.value = 200;n3.value = 300;n1.next = &n2;n2.next = &n3;i = n1.next->value;printf ("%i ", i);printf ("%i\n", n2.next->value);return 0;

}The Keyword const and PointersA variable or an array can be declared as const to alert the compileras well as the reader that the contents of a variable or an array willnot be changed by the program. With pointers, there are two things toconsider: whether the pointer will be changed, and whether the valuethat the pointer points to will be changed. Think about that for asecond. Assume the following declarations:char c = 'X';char *charPtr = &c;The pointer variable charPtris set pointing to the variable c. If thepointer variable is always set pointing to c, it can be declared as aconst pointer as follows:char * const charPtr = &c; Pointers and FunctionsWe can pass a pointer as an argument to a function in the normalfashion, and we can also have a function return a pointer as itsresult. The formal parameter pointer can then be used the same way a normalpointer variable can be used. One thing worth remembering when dealingwith pointers that are sent to functions as arguments: the value ofthe pointer is copied into the formal parameter when the function iscalled. Therefore, any change made to the formal parameter by thefunction will not affect the pointer that was passed to the function.While the pointer cannot be changed by the function. The data elementsthat the pointer references can be changed.

C programming 70Program 11.8 Using Pointers and Functions// Program to illustrate using pointers and functions #include <stdio.h>void test (int *int_pointer){

*int_pointer = 100;}int main (void){

void test (int *int_pointer);int i = 50, *p = &i;printf ("Before the call to test i = %i\n", i);test (p);printf ("After the call to test i = %i\n", i);return 0;

}since we are limited to returning only a single value from a function.The use of pointers helps us to overcome this minor inconveniencebecause they enable us to change what is known as a call by value intoa call by reference. Pointers and Arrays One of the most common uses of pointers in C is as pointers to arrays.The main reasons for using pointers to arrays are ones of notationalconvenience and of program efficiency. Pointers to arrays generallyresult in code that uses less memory space and executes faster. C compiler treats the occurrence of an array name without a subscriptas a pointer to the array. Program 11.11 Working with Pointers to Arrays// Function to sum the elements of an integer array #include <stdio.h>int arraySum (int array[], const int n){

int sum = 0, *ptr;int * const arrayEnd = array + n;for ( ptr = array; ptr < arrayEnd; ++ptr )sum += *ptr;return sum;

}int main (void)

C programming 71{

int arraySum (int array[], const int n);int values[10] = { 3, 7, -9, 3, 6, -1, 7, 9, 1, -5 };printf ("The sum is %i\n", arraySum (values, 10));return 0;

}Pointers to Character StringsOne of the most common applications of using a pointer to an array isas a pointer to a character string. To show how easily pointers tocharacter strings can be used, let's write a function called copy-string to copy one string into another. Program 11.13 Pointer Version of copyString#include <stdio.h>void copyString (char *to, char *from){for ( ; *from != '\0'; ++from, ++to )*to = *from;*to = '\0';}int main (void){

void copyString (char *to, char *from);char string1[] = "A string to be copied."; char string2[50];copyString (string2, string1);printf ("%s\n", string2);copyString (string2, "So is this."); printf ("%s\n", string2);return 0;

}Constant Character Strings and PointersThe only time that C lets you get away with performing this type ofassignment to a character array is when initializing it, as inchar text[80] = "This is okay.";If text is a character pointer, initializing text with the statementchar *text = "This is okay.";The Increment and Decrement Operators Revisitedif textPtr is a character pointer, the expression*(++textPtr)

C programming 72first increments textPtr and then fetches the character it points to,whereas the expression*(textPtr++)fetches the character pointed to by textPtr before its value isincremented. Operations on Pointers we can add or subtract integer values from pointers. Furthermore, wecan compare two pointers to see if they are equal or not, or if onepointer is less than or greater than another pointer. The only otheroperation that is permitted on pointers is the subtraction of twopointers. The result of subtracting two pointers in C is the number ofelements contained between the two pointers. Pointers to Functions To declare a variable fn_pointer to be of type "pointer to a functionwhich returns an int the declaration int (*fn_pointer)(); can be used. The parentheses around *fn_pointer are required, becauseotherwise the C compiler would treat the above statement as thedeclaration of a function called fn_pointer that returns a pointer toan int.Pointers and Memory Addresses Whenever we apply the address operator to a variable in C, the valuethat is generated is the actual address of that variable inside thecomputer's memory. So the expressionint_pointer = &count;will assign to the variable int_pointer the address in the computer'smemory that has been assigned to the variable count. If count werelocated at address 500, then the above statement would assign thevalue 500 to int_pointer. So if int_pointer were declared to be oftype "pointer to int," then the value stored in the memory addressgiven by *int_pointer would be interpreted as an integer by thesystem.

12. OPERATIONS ON BITSA bit can assume either of two values: 1 or 0. So a byte stored ataddress 1000 in a computer's memory, for example, might beconceptualized as a string of eight binary digits as shown:01100100The rightmost bit of a byte, is known as the "least significant" or"low order" bit, while the leftmost bit is known as the "most

C programming 73significant" or "high-order" bit. If we treat the string of bits as aninteger, then the rightmost bit of the above byte represents 2° or 1,the bit immediately to its left represents 21or 2, the next bit 22 or 4,and so on. The representation of negative numbers is handled slightlydifferently. Most computers choose to represent such numbers using aso-called "twos complement" notation. Using this notation, theleftmost bit represents the "sign" bit. If this bit is 1, then thenumber is negative; otherwise the bit is zero and the number ispositive. 4 expressed in binary is 00000100, and complementing thebits produces 11111011Bit operatorsThe operators that C provides for manipulating bits are presented inTable

All of the operators listed in Table, with the exception of the ones complement operator' -', are binary operators and as such take two operands. Bit operations can be performed on any type of integer value

in C-be it short, long, or unsigned-and on characters, but cannot be performed on a value of type float or double.

The Bitwise AND OperatorWhen two values are AND in C, the binary representations of thevalues are "compared" bit by bit. Each corresponding bit that is a 1in the first value and a 1 in the second value produces a 1 in thecorresponding bit position of the result; anything else produces a 0.If b1 and b2 represent corresponding bits of the two operands, thenthe following table, called a truth table, shows the result.

For example, the expression w3=w1&3; will assign to w3 the value of w3bitwise ANDed with the constant 3. Program 12.1 The Bitwise AND Operator// Program to demonstrate the bitwise AND operator #include <stdio.h>

C programming 74int main (void){

unsigned int word1 = 077u, word2 = 0150u, word3 = 0210u;printf ("%o ", word1 & word2);printf ("%o ", word1 & word1);printf ("%o ", word1 & word2 & word3);printf ("%o\n", word1 & 1);return 0;

}The Bitwise Inclusive OR OperatorWhen two values are bitwise inclusive ORed in C, the binaryrepresentation of the two values are once again "compared" bit by bit.This time, each bit that is a 1 in the first value or a 1 in thesecond value will produce a 1 in the corresponding bit of the result.The truth table for the inclusive OR operator is shown below.

The Bitwise Exclusive OR OperatorThe bitwise exclusive OR operator, which is often called the XORoperator, works as follows: for corresponding bits of the twooperands, if either bit is a 1-but not both-then the corresponding bitof the result is a 1;otherwise it is a 0. The truth table for thisoperator is as shown

The Ones Complement OperatorThe ones complement operator is a unary operator, and its effect is tosimply "flip" the bits of its operand. So each bit of the operand thatis a 1 is changed to a 0, and each bit that is a 0 is changed to a 1.The truth table is provided below.

Program 12.2 Illustrate Bitwise Operators

C programming 75/* Program to illustrate bitwise operators */#include <stdio.h>int main (void){

unsigned int w1 = 0525u, w2 = 0707u, w3 = 0122u;printf ("%o %o %o\n", w1 & w2, w1 | w2, w1 ^ w2);printf ("%o %o %o\n", ~w1, ~w2, ~w3);printf ("%o %o %o\n", w1 ^ w1, w1 & ~w2, w1 | w2 | w3);printf ("%o %o\n", w1 | w2 & w3, w1 | w2 & ~w3);printf ("%o %o\n", ~(~w1 & ~w2), ~(~w1 | ~w2));w1 ^= w2;w2 ^= w1;w1 ^= w2;printf ("w1 = %o, w2 = %o\n", w1, w2);return 0;

}The Left Shift OperatorWhen a left shift operation is performed on a value, the bitscontained in the value are literally shifted to the left. Associatedwith this operation is the number of places (bits) that the value isto be shifted. Bits that are shifted out through the high order bit ofthe data item are lost, and as are always shifted into the low orderbit position of the value. So if w1 is equal to 03, then theexpressionw1 = w1 « 1; which can also be expressed as w1 «= 1;will result in 03 being shifted one place to the left, which willresult in 06 being assigned to w1:

The operand on the left of the < < operator is the value to beshifted, while the operand on the right is the number of bit positionsthe value is to be shifted by. If we were to shift w1 one more placeto the left, we would end up with octal 014 as the value of w1:

Left shifting actually has the effect of multiplying the value that isshifted by two. The Right Shift Operator

C programming 76As implied from its name, the right shift operator » shifts the bitsof a value to the right. Bits shifted out of the low order bit of thevalue are lost. Right shifting an unsigned value will always result in0s being shifted in on the left, that is, through the high-order bits.What is shifted in on the left for signed values depends on the signof the value that is being shifted and also on how this operation isimplemented on your particular computer system. If the sign bit is 0,then 0s will be shifted in no matter what machine we are talkingabout. However, if the sign bit is 1, then on some machines 1s will beshifted in, and on others 0s will be shifted in. This former type ofoperation is known as an arithmetic right shift, while the latter isknown as a logical right shift.So for example, if w1 is an unsigned int, which is represented in 16bits, and w1 is set equal to octal 0155667, then shifting w1 one placeto the right with the statementw1 »=1will set w1 equal to octal 0066733

Program 12.3 Implementing a Shift Function// Function to shift an unsigned int left if the count is positive,and right if negative #include <stdio.h>unsigned int shift (unsigned int value, int n){

if ( n > 0 ) // left shift value <<= n;

else // right shift value >>= -n;

return value;}int main (void){

unsigned int w1 = 0177777u, w2 = 0444u;unsigned int shift (unsigned int value, int n);printf ("%o\t%o\n", shift (w1, 5), w1 << 5);printf ("%o\t%o\n", shift (w1, -6), w1 >> 6);printf ("%o\t%o\n", shift (w2, 0), w2 >> 0);printf ("%o\n", shift (shift (w1, -3), 3));return 0;

C programming 77} Bit FieldsThere are two methods in C that can be used to pack informationtogether to make better use of memory. One way is to simply representthe data inside a normal int, for example, and then access the desiredbits of the int using the bit operators. Another way is to define astructure of packed information using a C construct known as a bitfield.Suppose we needed to pack 5 data values into a single word. Assumethat three of these data values are flags, which we will call f1, f2,and f3; the fourth value is an integer called type, which ranges from1 through 12; and the final value is an integer called index, whichranges from 0 to 500. In order to store the values of the flags f1, f2, and f3, we wouldonly require three bits of storage, one bit for the TRUE/FALSE valueof each flag. To store the value of the integer type, which rangesfrom 1 to 12, would require 4 bits of storage. Finally, to store thevalue of the integer index, which can assume a value from 0 to 500, wewould need 9 bits. Therefore, the total amount of storage needed tostore the five data values f 1, f2, f3, type, and index, would be 16bits. We could define an integer variable that could be used tocontain all five of these values, as in unsigned int packed_data;One such assignment is described in Figure, which assumes that thesize of packed_data is 16 bits. We can now apply the correct sequenceof bit operations to packed-data to set and retrieve values to andfrom the various fields of the integer. For example, we can set thetype field of packed data to 7 by shifting the value 7 the appropriatenumber of places to the left and then ORing it into packed-data.packed_data |= 7<<9; can set the type field to the value of n, wheren is between 0 and 15 by the statementpacked_data |= n « 9;

The C language does provide a more convenient way of dealing with bitfields. This method employs the use of a special syntax in thestructure definition that allows us to define a field of bits andassign a name to that field. In order to define the bit field

C programming 78assignments mentioned above, we can define a structure called packed-struct, for example, as follows:struct packed_struct{unsigned int :3;unsigned int f1:1;unsigned int f2:1;unsigned int f3:1;unsigned int type:4;unsigned int index:8;};The C system automatically packs the above bit field definitionstogether. The nice thIng about this approach is that the fields of avariable defined to be of type packed-struct can now be referenced inthe same convenient way normal structure members are referenced. So ifwe were to define a variable called packed_data as follows: structpacked_struct packed_data;then we could easily set the type field of packed_data to 7 with thesimple statement packed_data.type=7;Extraction of the value from a bit field is also automaticallyhandled, so the statement will extract the type field frompacked_data. Bit fields can be used in normal expressions, and areautomatically converted to integers. So the expressioni=packed_data.index/5;Bit fields are packed into words as they appear in the structuredefinition. If a particular field does not fit into a word, then theremainder of the word is skipped and the field is placed into the nextword.

13.THE PREPROCESSORPreprocessor statements are identified by the presence of a pound sign#. which must be the first character on the line. The #deflne Statement The #define statement is used for assigning symbolic names to programconstants. The preprocessor statement #define TRUE 1 defines thename TRUE and makes it equivalent to the value 1. The name TRUE cansubsequently be used anywhere in the program where the constant 1could be used. Whenever this name appears, its defined value of 1 willbe automatically substituted into the program by the preprocessor.

C programming 79Program 13.1 Introducing the #defineStatement#include <stdio.h>#define YES 1#define NO 0// Function to determine if an integer is even int isEven (int number){

int answer;if ( number % 2 == 0 )

answer = YES;else

answer = NO;return answer;

}int main (void){

int isEven (int number);if ( isEven (17) == YES )

printf ("yes ");else

printf ("no ");if ( isEven (20) == YES )

printf ("yes\n");else

printf ("no\n");return 0;

}Program ExtendabilityUsing a defined name for a constant value helps to make programs morereadily extendable. For example, define an array that we must specifythe number of elements in the array either explicitly or implicitly.If the array data_values were defined in a program as follows:

float data_values[1000];A better way of dealing with array bounds that makes programs easierto extend is to define a name for the upper array bound. So, if wedefine a name such as MAXIMUM_DATA_VALUES with an appropriate #deflnestatement:

#define MAXIMUM_DATA_VALUES 1000

C programming 80Program TransportabilityAnother nice use of the define is that it helps to make programs moretransportable from one computer system to another. At times it may benecessary to use constant values in a program that are related to theparticular computer that the program is running on. More Advanced Types of DefinitionsA definition for a name can include more than a simple constant value.It can include an expression. The following defines the name TWO_PI asthe product of 2.0 and 3.141592654#define TWO_PI 2.0*3.141592654A preprocessor definition does not have to be a valid C expression inits own right-just so long as wherever it is used the resultingexpression is valid. For instance, the definition#define LEFT_SHIFT_8 << 8Now consider the following define and the subsequent if statement:#define IS_LEAP_YEAR(y) y % 4 == 0 && y % 100 != 0 || y % 400 == 0consider a macro called SQUARE that simply squares its argument. Thedefinition#define SQUARE(x) x * xThe following defines a macro called MAX, which gives the maximum oftwo values:#define MAX(a,b) ( ((a) > (b)) ? (a) : (b) )The ##OperatorThis operator is used in macro definitions to join two tokenstogether. It is preceded (orfollowed) by the name of a parameter to the macro. The preprocessortakes the actualargument to the macro that is supplied when the macro is invoked andcreates a singletoken out of that argument and whatever token follows the ##.Suppose, for example, you have a list of variables x1 through x100.Youcan write amacro called printx that simply takes as its argument an integer value1 through 100and that displays the corresponding x variable as shown:#define printx(n) printf ("%i\n", x ## n)

C programming 81The portion of the define that reads x ## nsays to take the tokens that occur before and after the ## and make asingle token out of them. So the call printx (20); is expanded intoprintf ("%i\n", x20);The #includeStatementyou to collect all your definitions into a separate file and theninclude them in your program, using the #include statement. Thesefiles normally end with the characters .hand are referred to as headeror include files.Suppose you are writing a series of programs for performing variousmetric conversions. You might want to set up some defines for all ofthe constants that you need to perform your conversions:The double quotation marks around the include filename instruct thepreprocessor to look for the specified file in one or more filedirectories. If the file isn’t located, the preprocessor automaticallysearches other system directories as described next. Enclosing thefilename within the characters <and >instead, as in #include <stdio.h>causes the preprocessor to look for the include file in the specialsystem include file directory or directories. System Include FilesThe <stdio.h>header file contains information about the I/O routinescontained in the standard I/O library. Two other useful system includefiles are <limits.h>and <float.h>.The <float.h>header file givesinformation about floating-point data types. Other system includefiles contain prototype declarations for various functions storedinside the system library.Conditional Compilation The C preprocessor offers a feature known as conditional compilation.Conditional compilation is sometimes used to have one program that canrun on different computer systems. It is also used at times to"switch" on or off various statements in the program, such asdebugging statements that print out the values of various variables ortrace the flow of program execution.The #ifdef,#endif,#else,and #ifndef StatementsIf we had a large program that had many such dependencies on theparticular hardware of the computer system , then we might end up withmany defines whose values would have to be changed when the programwas moved to another computer system.

C programming 82We can help reduce the problem of having to change these defines whenthe program is moved and can incorporate the values of these definesfor each different machine directly into the program by using theconditional compilation capabilities of the preprocessor. As a simpleexample, the statements#ifdef UNIX# define DATADIR "/uxn1/data"#else# define DATADIR "\usr\data"#endifhave the effect of defining DATADIRto "/uxn1/data"if the symbolUNIXhas been previ-ously defined and to "\usr\data"otherwise.The #ifand #elifPreprocessor StatementsThe #ifpreprocessor statement offers a more general way of controllingconditional compilation. The #ifstatement can be used to test whethera constant expression evaluates to nonzero. If the result of theexpression is nonzero, subsequent lines up to a #else,#elif,or#endifare processed; otherwise, they are skipped. The special operatordefined (name) can also be used in #ifstatements. The set ofpreprocessor statements#if defined (DEBUG)...#endifand#ifdef DEBUG...#endifThe #undefStatementOn some occasions, you might need to cause a defined name to becomeundefined. Thisis done with the #undefstatement. To remove the definition of aparticular name, you write#undef name

14 More on Data TypesEnumerated Data Types An enumerated data type definition is initiated by the keyword enum.Immediately following this keyword is the name of the enumerated data

C programming 83type, followed by a list of the permissible values that can beassigned to the type. For example, the C statement enum flag { true, false }defines a data type flag. This data type can be assigned the valuestrue and false inside the program, and no other values.Enumerated values that subsequently appear in the list will beassigned sequential values beginning with the specified integer valueplus one. For example, in the definitionenum direction { up, down, left = 10, right }; an enumerated data type direction is defined with the values up, down,left, and right. The compiler assigns the value 0 to up, since itappears first in the list; 1 to down, since it appears next; 10 toleft, since it is explicitly assigned this value; and 11 to right,since it appears immediately after left in the list.Program 14.1 Using Enumerated Data Types// Program to print the number of days in a month #include <stdio.h>int main (void){

enum month { january = 1, february, march, april, may, june,july, august, september, october, november, december };enum month aMonth;int days;printf (“Enter month number: “);scanf (“%i”, &aMonth);switch (aMonth ) {

case january:case march:case may:case july:case august:case october:case december:days = 31;

C programming 84break;case april:case june:case september:case november:days = 30;break;case february:days = 28;break;default:printf (“bad month number\n”);days = 0;break;

}if ( days != 0 )

printf (“Number of days is %i\n”, days);if ( amonth == february )

printf (“...or 29 if it’s a leap year\n”);return 0;

} The typedef Statement C provides a capability that enables the programmer to assign analternate name to a data type. This is done with a statement known asa typedef. The statement #define COUNTER intdefines the name COUNTER to be equivalent to the C data type int.Variables can subsequently be declared to be of type COUNTER, as inthe statement COUNTER j,nThe C compiler actually treats the declaration of the variables j andn above as normal integer variables. The main advantage of the use ofthe typedef in this case is in the added readability that it lends tothe definition of the variables. For example, the following typedef statement. In order to define a newtype name, you should follow this procedure:

C programming 851. Write the statement as if a variable of the desired type were beingdefined.2. Where the name of the defined variable would normally appear,substitutethe new type name.3. In front of everything, place the keyword typedef.Data Type ConversionsA float and an int was carried out as a floating point operation, theinteger data item being automatically converted to floating point. Wehave also seen how the type cast operator can be used to explicitlydictate a conversion. So in the expressionaverage = (float) total / n;the value of the variable total is converted to type float before theoperation is performed, thereby guaranteeing that the division will becarried out as a floating point operation.The compiler also has two rules that it uses for converting argumentsthat are passed to functions: (l) any argument of type float isautomatically converted to type double; and (2) any argument of typechar or short is automatically converted to type int. The value of afloat or a double can be displayed using the format characters %f or%e. TABLE 14-1. CONVERSION OF OPERANDS IN AN EXPRESSION1. If either operand is of type float, then it will be converted totype double. If either operand is of type char or of type short(signed or unsigned), then it will be converted to type int (signed orunsigned).2. If either operand is of type double, then the other operand will beconverted to type double. This will be the type of the result of theevaluation.3. If either operand is of type long, then the other operand will beconverted to type long, which will be the type of the result of theevaluation.4. If either operand is of type unsigned, then the other operand willbe converted to type unsigned, which will be the type of the result.5. If none of the above conversions is performed, then both operandsmust be of type int, which will be the type of the result.15. INPUT AND OUTPUTCharacter I/O: getchar and putchar

C programming 86The getchar function used to read data from the terminal a singlecharacter at a time. syntax is getchar(); The putchar function takes only one character argument and it isdisplayed on screen.. So the callputchar(c);where c is of type char, would have the effect of displaying thecharactercontained in c at the terminal. The callputchar (‘ \n’ ) ;would have the effect of displaying the newline character at theterminal, which, as we know, would cause the cursor to move to thebeginning of the next line.Formatted I/O: prlntf and scanfThe first argument to both the printf and scanf functions is theformat string. This string specifies how the remaining arguments tothe function are to be displayed in the case of the printf function,and how the data that is read in is to be interpreted in the case ofthe scanf function.The printf functionThe % character and the specific so-called conversion character tomore precisely control the formatting of the output. For example, wecould be used to specify a field width. The format characters %2dspecified the display of an integer value right-justified in a fieldwidth of two columns. Table 16-1 summarizes all possible characters and values that can beplaced directly after the % sign and before the conversion characterinside a format string. The use of any of these conversion charactermodifiers is optional. However, if more than one modifier is used,then they must be specified in the order as indicated by Table 16-1. Table 16.1 printfFlagsFlag Meaning - Left-justify value+ Precede value with +or -(space) Precede positive value with spacecharacter0 Zero fill numbers# Precede octal value with 0,hexadecimal value with 0x(or 0X);

display decimal point for floats; leave trailing zeroes for g orG format

C programming 87Table 16.2 printfWidth and Precision ModifiersSpecifier Meaningnumber Minimum size of field* Take next argument to printf as size of field. number Minimum number of digits to display for integers number

of decimal places for e or f formats; maximum number ofsignificant digits to display for g maximum number ofcharacters for s format

.* Take next argument to printf as precision (andinterpret as indicated in preceding row)Table 16.3 printfType ModifiersType MeaningHh Display integer argument as a characterh* Display short integerl* Display long integerll* Display long long integerL Display long doublej* Display intmax_tor uintmax_tvalue t* Display ptrdiff_tvaluez* Display size_tvalueTable 16.4 printfConversion CharactersChar Use to DisplayI or d Integeru Unsigned integero Octal integerx Hexadecimal integer, using a–fX Hexadecimal integer, using A–Ff or F Floating-point number, to six decimal places by defaulte or E Floating-point number in exponential format (e places

lowercase e before the exponent, E places uppercase E beforeexponent)

g Floating-point number in for e formatG Floating-point number in For E formata or A Floating-point number in the hexadecimal format 0xd.ddddp±dc Single characters Null-terminated character stringp Pointer% Percent signTable 16.5 scanfConversion Modifiers

C programming 88Modifier Meaning* Field is to be skipped and not assignedsize Maximum size of the input fieldhh Value is to be stored in a signedor unsigned charh Value is to be stored in a short intl Value is to be stored in a long int,double,or wchar_t j,z,or t

Value is to be stored in a size_t(%j),ptrdiff_t(%z),intmax_t,oruintmax_t(%t)

ll Value is to be stored in a long long intL Value is to be stored in a long double type Conversion characterTable 16.6 scanfConversion CharactersCharacter Actiond The value to be read is expressed in decimal notation; the

corresponding argu-ment is a pointer to an intunless the h,l,orllmodifier is used, in which case the argument is a pointer to ashort,long,or long long int,respec-tively.

I Like %d,except numbers expressed in octal (leading 0) orhexadecimal (lead-ing 0xor 0X) also can be read.

u The value to be read is an integer, and the correspondingargument is a point-er to an unsigned int.

o The value to be read is expressed in octal notation and can beoptionally pre-ceded by a 0.The corresponding argument is apointer to an int,unless h,l,or llprecedes the letter o,in whichcase the argument is a pointer to a short,long,or longlong,respectively.

X The value to be read is expressed in hexadecimal notation andcan be option-ally preceded by a leading 0xor 0X;thecorresponding argument is a pointer to an unsigned int, unless ah,l,or llmodifies the x.

a,e,f,or g The value to be read is expressed in floating-pointnotation; the value can be optionally preceded by a sign and canoptionally be expressed in exponential notation.

c The value to be read is a single character; s The value to be read is a sequence of characters; [...] Characters enclosed within brackets indicate that acharacter string is to be read, as in %s;n Nothing gets read. p The value to be read is a pointer expressed in the sameformat as is displayed by printf with the

C programming 89 % p conversion characters. The corresponding argument is a

pointer to a pointer to void.% The next nonwhitespace The scanf FunctionThe scanf function takes optional modifiers between the % and theconversion character. These optional modifiers are summarized in Table16-3. The possible conversion characters that may be specified aresummarized in Table 16-4.When the scanf function searches the inputstream for a value to be read, it will always bypass any leading so-called white space characters, where white space refers to either ablank space, tab ('\t'), newline ('\n'), or form feed character('\f').FILE I/O Redirection of I/O to a FileThe need frequently arises to either read in information from a filethat is stored on the system, or to write data out to a file on thesystem. Both of these operations can be easily performed under UNIXwithout anything special being done at all to the program. If wewished to write all of our program results into a file called data,for example, then all that we would have to do under UNIX would be toredirect the output from the program into the file data by executingthe program with the following command:a.out > dataThe above command instructs the system to execute the program a.outbut to take all of the information that is normally written to theterminal by the program and redirect it into a file called datainstead. Any values displayed by printf would not be displayed at theterminal but instead would be written into the file called data.Program 16.2 Copying Characters from Standard Input to Standard Output// Program to echo characters until an end of file #include <stdio.h>int main (void){int c;while ( (c = getchar ()) != EOF )putchar (c);return 0;}Special Functions for Working with Files

C programming 90perform all I/O operations using just the getchar, putchar, scanf andprintf functions and the notion of I/O redirection. you might need toread data from two or more different files or to write output resultsinto several different files. To handle these situations, specialfunctions have been designed expressly for working with files. The fopenFunctionBefore you can begin to do any I/O operations on a file, the file mustfirst be opened. To open a file, you must specify the name of thefile. The system then checks to make certain that this file actuallyexists and, in certain instances, creates the file for you if it doesnot. When a file is opened, you must also specify to the system thetype of I/O operations that you intend to perform with the file. Ifthe file is to be used to read in data, you normally open the file inread mode. If you want to write data into the file, you open the filein write mode. Finally, if you want to append information to the endof a file that already contains some data, you open the file in appendmode. In the latter two cases, write and append mode, if thespecified file does not exist on the system, the system creates thefile for you. In the case of read mode, if the file does not exist, anerror occurs.The function called fopen in the standard library serves the functionof opening a file on the system and of returning a unique file pointerwith which to subsequently identify the file. The function takes twoarguments: The first is a character string specifying the name of thefile to be opened; the second is also a character string thatindicates the mode in which the file is to be opened. If the filecannot be opened for some reason, the function returns the value NULL. #include <stdio.h>FILE *inputFile;inputFile = fopen ("data", "r");have the effect of opening a file called data in read mode. The getc and putc FunctionsThe function getc enables you to read in a single character from afile. getc takes an argument: a FILE pointer that identifies the filefrom which the character is to be read.c = getc (inputFile);has the effect of reading a single character from the file data. Theputc function is equivalent to the putchar function, only it takes twoarguments instead of one. The first argument to putc is the character

C programming 91that is to be written into the file. The second argument is the FILEpointer. So the call putc ('\n', outputFile);writes a newline character into the file identified by the FILEpointeroutputFile.The fclose functionOne operation that we can perform on a file that must be mentioned isthat of closing the file. Once a file has been closed, it can nolonger be read from or written to unless it is reopened. The argumentto the fclose function is the FILE pointer of the file to be closed.So, the callfclose (inputFile);closes the file associated with the FILEpointer inputFile.Program 16.3 Copying Files// Program to copy one file to another #include <stdio.h>int main (void){

char inName[64], outName[64];FILE *in, *out;int c;// get file names from userprintf ("Enter name of file to be copied: ");scanf ("%63s", inName);printf ("Enter name of output file: ");scanf ("%63s", outName);// open input and output filesif ( (in = fopen (inName, "r")) == NULL ) {

printf ("Can't open %s for reading.\n", inName);return 1;}if ( (out = fopen (outName, "w")) == NULL ) {

printf ("Can't open %s for writing.\n", outName);return 2;}// copy in to outwhile ( (c = getc (in)) != EOF )

putc (c, out);// Close open filesfclose (in);

C programming 92fclose (out);printf ("File has been copied.\n");return 0;

}The feof Function In order to test for an end of file condition on afile, the function feof is provided in the standard I/O library. Thesingle argument to the function is a FILE pointer. The functionreturns an integer value that is non-zero if all of the data from thespecified file has been read, and is zero otherwise. So, the statementif ( feof (inFile) ) {printf ("Ran out of data.\n");return 1;}will have the effect of displaying the message "Ran out of data." atthe terminal if an end of file condition exists on the file identifiedby in_file.The fprintf and fscanf FunctionsThe functions fprintf and fscanf are provided to perform the analogousoperations of the printf and scanf functions on a file. Thesefunctions take an additional argument, which is the FILE pointer thatidentifies the file to which the data is to be written or from whichthe data is to be read. So to write the character string "Programmingin C is fun.\n" into the file identified by outfile, we can write thestatementfprintf (outFile, "Programming in C is fun.\n");Similarly, to read in the next floating point value from the fileidentified by infile into the variable fv, the statement fscanf (inFile, "%f", &fv);could be used. As with scanf, fscanf returns the number of argumentsthat are successfully assigned or the value EOF if the end of the fileis reached. The fgetsand fputsFunctionsFor reading and writing entire lines of data from and to a file, thefputs and fgets functions can be used. The fgets function is called asfollows:fgets(buffer, n, filePtr);buffer is a pointer to a character array where the line that is readin will be stored; n is an integer value that represents the maximumnumber of characters that are to be stored into buffer, andfile_pointer identifies the file from which the line is to be read.

C programming 93The fgets function reads characters from the specified file until anewline character has been read or until n- 1 characters have beenread, whichever occurs first. The function automatically places a nullcharacter after the last character in the buffer and returns the valueof buffer if the read is successful and the value NULL if an erroroccurs on the read or if an attempt is made to read past the end ofthe file.The fputs function writes a line of characters to a specified file.The function is called as shown:fputs (buffer, filePtr); Characters stored in the array pointed to by buffer are written tothe file identified by file_pointer until the null character isreached. The terminating null character is not written out to thefile. For reading and writing lines of data from the terminal thefunctions gets and puts are available. These functions are similar tothe fgets and fputs functions except that a FILE pointer is not takenas an argument. They also differ in the way they handle the newlinecharacter: gets will not store the newline character in the buffer,and puts automatically appends a newline character to the characterstring that is written.stdin,stdout,and stderrWhenever a C program is executed, three "files" are automaticallyopened by the system for use by the program. These files areidentified by the constant FILE pointers stdin, stdout, and stderr,which are defined in the standard I/O include file. The FILE pointerstdin identifies the standard input of the program and is normallyassociated with your terminal. All standard I/O functions that performinput and do not take a FILE pointer as an argument get their inputfrom stdin. For example, the scanf function reads its input fromstdin, and a call to this function is equivalent to a call to thefscanf function with stdin as the first argument. So the call fscanf(stdin, "%i", &i);The exit FunctionAt times it may be desirable to force the termination of a program,such as when an error condition is detected by a program. We know thatprogram execution is automatically terminated whenever the laststatement in main is executed. But in order to explicitly terminate aprogram, the exit function can be called. The function callexit (n);18.MISCELLANEOUS FEATURES AND ADVANCED TOPICS

C programming 94The break Statement Sometimes when executing a loop it becomesdesirable to leave the loop as soon as a certain condition occurs. Thebreak statement can be used inside a loop to achieve this result. Inthe statements for(i=0;i<n;i++){

eof_flag=fscanf(in_file,”%d”,&x[i]);if(eof_flag==EOF)

break;sum+=x[i];

}The if statement inside the loop tests the value of eof_flag andexecutes a break statement if in fact the end of the file has beenreached. This causes the program to immediately exit the for loop.Subsequent statements in the loop are skipped, and execution of theloop is terminated.The break statement can be used from within for, while, do, or switchstatements. If a break is executed from within a set of nested loops,only the innermost loop in which the break statement occurs isterminated. The continue StatementThis statement causes the loop in which it is executed to be continuedat the point that the continue statement is executed, any statementsin the loop that appear after the continue statement are automaticallyskipped. Execution of the loop otherwise continues as normal.The continue statement is most often used to bypass a group ofstatements inside a loop. The format of the continue statement issimplycontinue;The goto StatementExecution of a goto statement causes a direct branch to be made to aspecified point in the program. This branch is made immediately andunconditionally upon execution of the goto. In order to identify wherein the program the branch is to be made, a label is needed. A label isa name that is formed with the same rules as variable names, and mustbe immediately followed by a colon. The label is placed directlybefore the statement to which the branch is to be made, and mustappear in the same function as the goto.

C programming 95The null StatementC permits a single semicolon to be placed wherever a normal programstatement can appear. The effect of such a statement, known as thenull statement, is that nothing is done. It is very often used by Cprogrammers in while, for, and do statements. For example, the purposeof the following statement is to store all of the characters read infrom the standard input into the character array pointed to by textuntil a newline character is encountered:while ( (*text++ = getchar ()) != '\n' );unionsUnion is used mainly in more advanced programming applications whereit is necessary to store different types of data into the same storagearea. Exampleunion mixed{

char c;float f;int i;

};The declaration for a union is identical to that of a structure,except the keyword union is used where the keyword struct is otherwisespecified. The real difference between structures and unions has to dowith the way memory is allocated. Declaring a variable to be of typemixed as in union mixed x;does not define x to contain three distinct members called c, f, andi, but rather defines x to contain a single member that is calledeither c, f, or i. In this way, the variable x can be used to storeeither a char or a float or an int. We could store a character intothe variable x with the following statement: x.c = 'K';The character stored in x could subsequently be retrieved in the samemanner. So to display its value at the terminal, for example, thefollowing could be used:printf ("Character = %c\n", x.c);A union member follows the same rules of arithmetic as the type of themember that is used in the expression. So in x.i/2the expression is evaluated according to the rules of integerarithmetic.The Comma Operator

C programming 96we could include more than one expression in any of the fields byseparating each expression with a comma. For example, the forstatement that beginsfor ( i = 0, j = 100; i != 10; ++i, j -= 10 )initializes the value of i to 0 and j to 100 before the loop beginsand increments the value of i and subtracts 10 from the value of jeach time after the body of the loop is executed. The comma operatorcan be used to separate multiple expressions anywhere that a valid Cexpression can be used. comma used to separate arguments in a functioncall or variable names in a list of declarations.Register VariablesIf a function heavily uses a particular variable, then you can requestthat the value of that variable be stored in one of the machine'sregisters whenever the function is executed. This is done by prefixingthe declaration of the variable by the keyword register, as inregister int index;register char *textPtr;Both automatic local variables and formal parameters can be declaredas register variables. The types of variables that can be assigned toregisters vary among machines. The basic data types can usually beassigned to registers. As well as pointers to any data type. As youwould expect, arrays and structures cannot be declared as registervariables. Each machine has different limitations on the number ofregister variables that are permitted. Command Line Arguments Many times a program will be developed that requires the user to entera small amount of information at the terminal. This capability isprovided by what is known as command line arguments.We have pointed out that the only distinguishing quality of thefunction main is that it has a special name to the system that is usedto specify where program execution is to begin. When main is called bythe runtime system, two arguments are actually passed to the function.The first argument, which is called argc by convention (for argumentcount), is an integer value that specifies the number of argumentsentered on the command line. The second argument to main is an arrayof character pointers, which is called argv by convention (forargument vector). There will be argc number of character pointerscontained in this array, where argc always has a minimum value of 1.The first entry in this array will always be a pointer to the name ofthe program that is executing. Subsequent entries in the array pointto the values that were specified on the same line as the command that

C programming 97initiated execution of the program. In order to access the commandline arguments, the main function must be appropriately declared astaking two arguments. The conventional declaration that is usedappears as follows:int main (int argc, char *argv[]){...}// Program to copy one file to another #include <stdio.h>int main (int argc, char *argv[]){

FILE *in, *out;int c;if ( argc != 3 ) {

fprintf (stderr, "Need two files names\n");return 1;

}if ( (in = fopen (argv[1], "r")) == NULL ) {

fprintf (stderr, "Can't read %s.\n", argv[1]);return 2;

}if ( (out = fopen (argv[2], "w")) == NULL ) {

fprintf (stderr, "Can't write %s.\n", argv[2]);return 3;

}while ( (c = getc (in)) != EOF )

putc (c, out);printf ("File has been copied.\n");fclose (in);fclose (out);return 0;

}Practical programsMS-WORD

C programming 98(1)(a)Design a visiting card for managing Director of a company with

the following specification.(i) Size of visiting card is 3.5" x 2"(ii) Name of a company with big font using water mark.(iii)Phone number, Fax number and e-mail address with appropriate

symbols.(iv) Office and residence address separated by line

1. Select start menu->programs->Microsoft office->Microsoft office word2007. Select Microsoft office button ->new ->blank document ->create to Open a blank document.

2. Select page setup from page Layout tab .3. In page setup dialog box, select the paper size tab.4. Reduce the paper width to 3.5”.5. Reduce the paper height to 2”.6. In the margins tab rebuke all the margins to 0.1”.7. In the document type the name of the manager in the left corner.8. In the right corner type the phone number with appropriate symbol.9. You can get the symbol from the symbols group on the insert tab.10. In the similar way add the fax number and the email address one

below the other with appropriate symbols.11. In the centre of the document type the name of the company with

centre alignment.12. Select the name of the company increase the font size.13. At the bottom type the office address.14. Draw a line after the office address.15. After the line type the residence address.16. At the end set a nice background.17. You can set the page colour from the page background group p on

the page Layout tab.1b) Create your class time table using Table option.1. Select start menu->programs->Microsoft office->Microsoft office

word2007. Select Microsoft office button ->new ->blank document ->create to Open a blank document.

2. Type TIME TABLE and select it , choose big font and under line from Home tab, font group.

3. Select insert table option from tables group on inset tab.4. Choose number of columns is 9 and number of rows is 7 in insert

dialog box to insert table.5. Insert column names DAY/PERIOD, I, II, BREAK, III, IV, LUNCH, V, VI.

C programming 996. Select BREAK column and right click mouse button it opens pop-up menu

in that choose merge cells option.7. Right click mouse button on break column it opens pop-up menu. Using

this change text direction vertical and choose centre alignment. 8. Repeat step5 and step6 for LUNCH column to merge cells and vertical

orientation and centre alignment.9. Enter Time Table Data in table. (2)(a) Create a letter head of a company with following using Template.i. Name of the company on the top of a page with big font and good

styleii. Phone No. Fax No… and e-mail address with appropriate symbols.iii. Slogans if any should be specified in bold at the bottom.1. Select start menu->programs->Microsoft office->Microsoft office

word2007. Select Microsoft office button ->new ->blank document ->create to Open a blank document.

2. Select the word art command from the drawing toolbar.3. Select a good word art.4. Type the name of the company and increase the font size.5. Adjust the name at the top of the document.6. Below the name, in the left side type the address of the company.7. Right to it type the phone number; fax number, and the email address

with appropriate symbols.8. You can get the symbols from the symbol command in the insert menu.9. After typing the details strike a line.10. Insert the footnote by selecting it from the insert menu.11. In the footnote type the main products manufactured in the

company.12. This ends up the document.(b)For given text add picture, add heading using word art and format the picture.1. Select start menu->programs->Microsoft office->Microsoft office

word2007. Select Microsoft office button-> Open and choose existing document from open dialog box.

2. Select pictures option on insert tab from illustrations group. Choose required picture from picture dialog box.

3. Select Word Art from text group on insert tab. Select required WordArtformat and enter heading of picture in edit word art dialog box.

4. To format picture, Select picture on click on it and change required pictures styles, picture shape, border, brightness, contrast format tab on picture tools.

3 Write a macro to format a document as below :-(i) Line spacing 2

C programming 100(ii) Justification formatting style(iii)Courier new font of 12 pt size(iv) Left and right margins to be 1.5"

1. Select start menu->programs->Microsoft office->Microsoft office word2007. Select Microsoft office button-> Open and choose existing document from open dialog box. Select text on document by cntrl+A.

2. Select Macros->record new macro command from macros group on view tab.3. Give the name for the macro and click ok.4. Choose paragraph dialog box on Home tab. Select double line spacing on

paragraph dialog box. 5. Click on the justify icon on the paragraph group on home tab. 6. Set the font to Courier New font and set the size to 12 points from

font group on Home tab.7. Select page setup dialog box on page layout tab. Set left and right

margins to 1.5.8. Select stop recording option from macros group on view tab.9. The macro is ready.(4)For given text, Apply the following :

(i) Page number and name of the college one each and every page(ii) Change font size and colour(iii)Add bullets and numbers(iv) Add border to pages1.Select start menu->programs->Microsoft office->Microsoft office word2007. 2.Select Microsoft office button-> Open and choose existing document from open dialog box.3. Select header option from Header & Footer group on Insert tab. 4. Insert College Name on Header and insert college name on header.5.Select text by ctrl + A .6. Change font size and colour from font group on Home tab.7. Select text by ctrl + A.8. Select bullets from paragraph group on Home tab.9.On the page layout tab select page borders option. 10.From page borders dialog box choose nice border.

(5) Use the mail merge option to write letters to your friends for inviting them to attend Annual Day Celebrations of your college.

1. Select start menu->programs->Microsoft office->Microsoft office word2007. Select Microsoft office button ->new ->blank document ->create to Open a blank document.

C programming 1012. Select step by step mail merge wizard from start mail merge group on

mailings tab.3. Choose letters option in step1 of the mail merge wizard and select

next button.4. In step2 of mail merge wizard select use the current document and

select next option.5. In step3 of mail merge wizard choose type a new list option and select

create option.6. It opens new address list dialog box. In that dialog box customize

columns (enter new columns, rename columns, delete unnecessary columnsif required).

7. Enter new data or edit data in new address list dialog box and save data and then select next option.

8. In Step4 write letter and select next.9. In step5 preview your letters and select next option.10. In step6 select print option to individual letters or edit

individual letters.(6)Create a suitable examination data base and find Total, Avg marks of each student and respective class secured by the students rules :-

Distinction if average > = 75First class if average > = 60 but < 75Second class if average > = 50 but < 60Third class if average 35 but < 50Fail if marks in any subject is < 35

1. Select start menu->programs->Microsoft office->Microsoft office Excel2007. Select Microsoft office button ->new ->blank work book ->create to Open a blank work book.

2. Type the field names in the first row.3. Type the required data.4. In the field for total type the formula by adding all the five

subjects [=SUM (C3:G3)].5. In the field for average type the formula using the average command

[=AVERAGE (C3:G3)]6. In the field for grade type the formula for grading on the given basis

using the ‘if’ and ‘and’ commands [=IF (AND (C3>=35, D3>=35, E3>=35, F3>=35, G3>=35, H3>=35), IF (I3>=75, "DISTINCTION", IF (I3>=60,"FIRST CLASS", IF (I3>=50, "SECOND CLASS", "THIRD CLASS"))), "FAIL")].

7. Copy formulas of total, average and grade to remaining rows. (7) Solve the following using functions :

(i) concatcrate two Texts(ii) Length of the text(iii)Text in uppercase and lowercase

C programming 1021. Select start menu->programs->Microsoft office->Microsoft office

Excel2007. Select Microsoft office button ->new ->blank work book ->create. To Open a blank work book.

2. Enter heading STRING FUNCTIONS.3. Enter two strings in b3 and b4.4. Enter formula to concatenate text in E5 is =concatenate(B3,B4).5. Enter formula to find length of text in F5 is =len(b3).6. Enter formula to convert lower case is =lower(b3).7. Enter formula to convert upper case is =upper(b4).(8)Prepare the following worksheet :

Year Product-1 Product-2 Product-3 Product-4 Prepare2003 1000 800 900 1000 for graph, line2004 800 80 500 9002005 1200 190 400 800 graph, pie

chart2006 400 200 300 10002007 1800 400 400 1200 and 3D chart

1. Select start menu->programs->Microsoft office->Microsoft office Excel2007. Select Microsoft office button ->new ->blank work book ->create. To Open a blank work book.

2. In a new work sheet type the data given. Select data by mouse click and drag.

3. Click on the line chart option and select required format of line chart from charts group on insert tab. It displays line chart on desired format.

4. Select data year and product1 series.5. Click on the pie chart option and select required format of pie chart

from charts group on insert tab. It displays pie chart for product1 series on desired format.

6. Repeat 5 for product2 ,product3 and product4 series.7. Select data by mouse click and drag.8. Click on the 3D chart option and select required format of 3D chart

from charts group on insert tab. It displays 3D chart on desired format.

(9)Create worksheet with the following columns :Employee code, Name, Age, Department, Salary and give title as Employee Information and Apply following format.(i) Title in Arial font with size 16(ii) Remaining text in Times new Roman font with 12(iii) Employee code in bold and Italic(iv) Employee Name fill with color(v) Apply borders to columns(vi) Salary with two decimal places

C programming 1031. Select start menu->programs->Microsoft office->Microsoft office

Excel2007. Select Microsoft office button ->new ->blank work book ->create to Open a blank work book.

2. Type Employee Information as title in first row.3. Select title by click and drag and then select font type is Arial and

font size is 12 from font group in home tab.4. Enter column names employee code, name, age, department, salary and

enter data.5. Select Employee code and choose options B and I from font group on

Home tab.6. Select Employee name and choose required fill color from font group on

home tab.7. Select salary cells and right click mouse select format cells from

popup menu.8. Select number category and also select decimal places is 2 on number

tab in Format cells dialog box.(10) Create emp worksheet with the following columns.

Emp No, Name, Basic salary, HRA (20% of Basic), DA(30% of Basic), Gross (Basic + HRA + DA), PF (15% basic), NET (Gross-PF).Find max & min / Net salaries Find employees where names starts with letter 'S'Find employees where salary 10,000

1. Select start menu->programs->Microsoft office->Microsoft office Excel2007. Select Microsoft office button ->new ->blank work book ->create to Open a blank work book.

2. Type column names Emp No, Name, Basic Salary, HRA,DA, Gross, PF, NET in A2,B2,C2,D2,E2,F2,G2,H2 cells respectively.

3. Enter 10 rows for employee data empno, name, basic salary.4. Type formulas in =C3*0.2,=C3*0.3,=SUM(C3:E3),=C3*.15,=F3-G3 in cells

D3,E3,F3,G3,H3 cells respectively.5. Copy formulas to remaining rows.6. Type in A15 cell Maximum Salary= and enter formula in cell B15

=max(H3:H12).7. Type in A16 cell Minimum Salary= and enter formula in cell

B16=min(H3:H12).8. Select 10 rows data and choose option filter on data tab. Then click

on arrow appeared on name column heading. It opens pop up menu in thatselect text filters->Begins with option. It opens custom auto filter.In that type names begins with is ‘s’.

9. This filter data and shows data names begins with letter ‘s’ only .10. Select 10 rows data and choose option filter on data tab. Then

click on arrow appeared on Net Salary column heading. It opens pop up

C programming 104menu in that select Number filters->greater than option. It opens custom auto filter. In that type net salary is greater than 10000.

11. This filter data and shows data net salary is greater than 10000.MS-ACCESS:

(11) Create a database using MS-Access with at lest 5 records Table 1

Register No, Name, DoB, Gender, ClassTable 2

Register No, M1, M2, M3, M4, M5 & Total.Maintain relationship between two tables with register number as primary key and answer following queries : show the list of students with register no, name, gender & total marks. Find student name starts with 'a' Find students where total > 500 Find student details where register no. = 301.

1. Select start menu->programs->Microsoft office->Microsoft office Access2007 -> Blank database. Enter File name of the database as student and select create. It create student database.

2. In student database open design view of table1 and enter Field namesRegistration_No, SName, DOB, Gender, Class and data type number, text, date/time, text, text respectively. Right click on Registration_No field select primary key option on pop-up menu. SaveTable1.

3. Open Table1 and enter 5 rows data.4. Select Create -> table option to create Table2 and save it. Open

Table2 in design view.5. Enter Field names Registration_No, M1, M2, M3, M4, M5 and Total and

enter all data types are number data type only. Right click on Registration_No field select primary key option on pop-up menu. SaveTable2.

6. Open Table2 and enter 5 rows data.7. On the Database Tools tab, in the Show/Hide group, click

Relationships.8. If you have not yet defined any relationships, the Show Table dialog

box automatically appears. The Show Table dialog box displays all ofthe tables and queries in the database.

9. Select table1 and table2 then click Add and then click Close. 10. Drag Registration_No field (typically the primary key) from

Table1 to the Table2 Registration_No in the Table2.11. On the Create tab, in the Other group, click Query Design. 12. In the Show Table dialog box, on the Tables tab, double-click

Table2. 13. Close the Show Table dialog box. 14. Select update option from query type group on design tab.

C programming 10515. In the Table2, Add Total field to the query design grid. 16. In the query design grid, in the update to row of the Total

column, type Table2.M1 + Table2.M2 + Table2.M3+Table2.M4+Table2.M5.

17. On the Design tab, in the Results group, click Run. The query runs, and update 5 rows.

18. Press CTRL+S to save the query. 19. On the Create tab, in the Other group, click Query Design. 20. In the Show Table dialog box, on the Tables tab, double-click

Table1. 21. Close the Show Table dialog box. 22. In the query design grid, in the criteria row of the Name column,

type Like ‘a*’.23. On the Design tab, in the Results group, click Run. It displays

names list starts with letter ‘a’.24. On the Create tab, in the Other group, click Query Design. 25. In the Show Table dialog box, on the Tables tab, double-click

Table2. 26. Close the Show Table dialog box. 27. Select in field row columns registration_No, name, DOB, gender

from table1 and total from table2 in the query design grid, in the criteria row of the total column enter >500

28. On the Design tab, in the Results group, click Run. It displays student data total marks >500.

(12)(a) Create a table member with following fields : Member no, member name, address, city, pin code, phone no, create form and enter data into the table through form.

(b) Create student table and form using table and form wizards with your own columns.1. Select start menu->programs->Microsoft office->Microsoft office Access2007 -> Blank database. Enter File name of the database as student and select create. It create student database.2. In student database open design view of table1 and enter Field names Member_no, member_ name, address, city, pincode, phoneno and data type number, text, text, text, number , number respectively. Right click on Member_no field select primary key option on pop-up menu. Save Table1.3. Select More Forms->Forms wizard from Forms group on create group.4. It starts Form wizard. In step1 select table1 and also select required fields and then press next.5. In step2 select Form layout as columnar from given options(columnar, tabular, datasheet, justified).6. In step3 select required style from existing styles. In step4 enterform title and select option open the form to view or enter information and press finish.

C programming 1067. Enter 5 records into table through form.8. Select Create -> table option to create Table2 and save it. Open Table2 in design view.9. Enter Field names Sno, Sname, DOB, Gender, Address and enter datatypes number, text, date/time, text, text respectively. Right click on Registration_No field select primary key option on pop-up menu. Save Table2.10. Select More Forms->Forms wizard from Forms group on create group. 11. It starts Form wizard. In step1 select table1 and also select required fields and then press next.12. In step2 select Form layout as columnar from given options(columnar, tabular, datasheet, justified).13. In step3 select required style from existing styles. In step4 enter form title and select option open the form to view or enter information and press finish.14. Enter 5 records into table through form.

13. Create database using MS-Access with at least 5 recordsTable 1 Employee code, emp-name, Age, Gender, DoB

Table 2 Emp code, Basic payMaintain relationship between two tables with Emp-code and generate following reports.1. Select start menu->programs->Microsoft office->Microsoft office Access2007 -> Blank database. Enter File name of the database as student and select create. It create student database.2. In student database open design view of table1 and enter Field names Emp_code, Emp_name, Age, Gender, DOB and data type number, text, number, text, date/time respectively. Right click on Emp_Code field select primary key option on pop-up menu. Save Table1.3. Open Table1 and enter 5 rows data.4. Select Create -> table option to create Table2 and save it. Open Table2 in design view.5. Enter Field names Emp_Code, Basic_pay, Da, Hra, Gross and enter all data types are number data type only. Right click on Emp_code select primary key option on pop-up menu. Save Table2.6. Open Table2 and enter 5 rows data.7. On the Database Tools tab, in the Show/Hide group, click Relationships.8. If you have not yet defined any relationships, the Show Table dialog box automatically appears. The Show Table dialog box displays all of the tables and queries in the database.Select table1 and table2 then click Add and then click Close. 9. Drag Emp_code field (typically the primary key) from Table1 to the Table2 Emp_code in the Table2.

C programming 10710. On the Create tab, in the Other group, click Query Design. 11. In the Show Table dialog box, on the Tables tab, double-click Table2. 12. Close the Show Table dialog box. 13. Select update option from query type group on design tab.14. In the Table2 Add DA, HRA, GROSS_SALARY fields to the query design grid. 12. In the query design grid, Enter in the update to row of the DA is Table2.Basic_pay * 0.2, HRA is Table2.Basic_pay *0.3 and in Gross is Table2.Basic_pay + Table2.DA +Table2.HRA.13. On the Design tab, in the Results group, click Run. The query runs, and update 5 rows.14. Press CTRL+S to save the query. 15.Select Report wizard from Reports on create tab. It opens Report Wizard dialog box. In that select Table1. From Table1 fields list select Emp_code, emp_name, age, gender.16. Select Table2 in Report wizard and select GROSS_SALARY then click next. 17. In Report wizard add Emp_code is a grouping level and click next. 18.In Report wizard select emp_name as sorting field in ascending order and click next. 19. In Report wizard select layout and page orientation and click next.20. In Report wizard, select style(flow) of the Report and click next. In opened dialog box enter title of the report and click finish. It displays preview of the report.21.Select Report wizard from Reports on create tab. It opens Report Wizard dialog box. In that select Table1. From Table1 fields list select Emp_code, emp_name.16. Select Table2 in Report wizard and select Basic_pay, DA, HRA, GROSS_SALARY then click next. 17. In Report wizard add Emp_code is a grouping level and click next. 18.In Report wizard select emp_name as sorting field in ascending order and click next. 19. In Report wizard select layout and page orientation and click next.20. In Report wizard, select style(flow) of the Report and click next. In opened dialog box enter title of the report and click finish. It displays preview of the report.MS-Power Point :(14)make power point presentation on your strengths, weaknesses, hobbies, factors, that

wrote your time.1. Select start menu->programs->Microsoft office->Microsoft office PowerPoint 2007. Opens PowerPoint with Title slide.

C programming 1082. In Title slide enter STUDNET NAME as title and enter name in Sub Title. Select Title and apply nice style from word art styles on drawing tools format tab. Select Sub Title and apply nice style from word art styles on drawing tools format tab. 3. Add new slide (Title and Content slide) from slides group on Home tab. In this slide add STRENGTHS as title and its content insert in contents box.4. Select Title and apply nice style from word art styles on drawing tools format tab. Select Content and apply nice style from word art styles on drawing tools format tab. 5. Add new slide (Title and Content slide) from slides group on Home tab. In this slide add WEAKNESSES as title and its content insert in contents box. Repeat step 4.6. Add new slide (Title and Content slide) from slides group on Home tab. In this slide add HOBBIES as title and its content insert in contents box. Repeat step 4.7. Add new slide (Title and Content slide) from slides group on Home tab. In this slide add FACTORS as title and its content insert in contents box. Repeat step 4.8.Select From beginning option from Start Silde Show group on Slide Show.

(15) Create presentation consisting slides with the following inform,Name of College, Addressof College, List of all Courses, Library & Lab facilities and apply transition effects.

1. Select start menu->programs->Microsoft office->Microsoft office PowerPoint 2007. Opens PowerPoint with Title slide.2. In Title slide enter NAME OF THE COLLEGE as title and enter name inSub Title. Select Title and apply nice style from word art styles on drawing tools format tab. Select Sub Title and apply nice style from word art styles on drawing tools format tab. 3. Add new slide (Title and Content slide) from slides group on Home tab. In this slide add ADDRESS as title and its content insert in contents box.4. Select Title and apply nice style from word art styles on drawing tools format tab. Select Content and apply nice style from word art styles on drawing tools format tab. 5. Add new slide (Title and Content slide) from slides group on Home tab. In this slide add LIST OF ALL COURSES as title and its content insert in contents box. Repeat step 4.6. Add new slide (Title and Content slide) from slides group on Home tab. In this slide add LAB FACILITIES as title and its content insertin contents box. Repeat step 4.7. Add new slide (Title and Content slide) from slides group on Home tab. In this slide add LIBRARY as title and its content insert in contents box. Repeat step 4.

C programming 1098. Select slide and nice transition from Transition to this slide group on animations tab. Similarly apply transition to all slides. 8.Select From beginning option from Start Silde Show group on Slide Show.

(16) Make power point presentation of all the details of the books that you had studied in B.Sc. first year.

1. Select start menu->programs->Microsoft office->Microsoft office PowerPoint 2007. Opens PowerPoint with Title slide.2. In Title slide enter BSC FIRST YEAR as title and enter Brach name in Sub Title. Select Title and apply nice style from word art styles on drawing tools format tab. Select Sub Title and apply nice style from word art styles on drawing tools format tab. 3. Add new slide (Title and Content slide) from slides group on Home tab. In this slide add TELUGU as title and insert Books studied fortelugu in contents box. 4. Select Title and apply nice style from word art styles on drawing tools format tab. Select Content and apply nice style from word art styles on drawing tools format tab. 5. Add new slide (Title and Content slide) from slides group on Home tab. In this slide add ENGLISH as title and insert Books studied forEnglish in contents box. Repeat step 4.6. Add new slide (Title and Content slide) from slides group on Home tab. In this slide add MATHE MATICS as title and insert Books studiedfor Mathematics in contents box. Repeat step 4.7. Add new slide (Title and Content slide) from slides group on Home tab. In this slide add PHYSICS as title and insert Books studied for Physics in contents box. Repeat step 4.7. Add new slide (Title and Content slide) from slides group on Home tab. In this slide add COMPUTER SCIENCE as title and insert Books studied for Computer science in contents box. Repeat step 4.8.Select From beginning option from Start Silde Show group on Slide Show.

(17)(a) Create presentation by importing chart from Excel1. Select start menu->programs->Microsoft office->Microsoft office

PowerPoint 2007. Opens PowerPoint with Title slide.2. Right click on slide and change slide layout to title and contents.Enter CHART NAME as title and Contents select insert chart option. It opens insert chart dialog box with all chart type.3.Select columnar chart type and also select 3D cylinder format of chart from available chart formats and click ok.4.It insets excel chart and allows to edit Excel data . If any modification required edit excel data. Modification on data immediately modify chart also.(b) Create presentation consisting of an organization chart.

C programming 1101. Select start menu->programs->Microsoft office->Microsoft office PowerPoint 2007. Opens PowerPoint with Title slide.2. Right click on slide and change slide layout to title and contents.3. Enter Organization Chart name as title .4. In Contents box select s insert smart art graphs option. It opens choose a Smart Art Graphs dialog box with all Smart Art graphics. Select organization chart option from hierarchy category and click ok. 5.It insert organization chart on contents text box. In Type your text here dialog box. Enter text Degree college as heading or top level. 6. In next level text box enter text Office. 7. In next level text boxes enter Computer Science department, Mathematics department ,Physics department. 8.Choose Add shape after option from create graphics group on smart art tools design tab. It create a text box in same level after Physicsdepartment. In that text box add text Chemistry department.9. Choose Add shape after option from create graphics group on smart art tools design tab. It create a text box in same level after Chemistry department. In that text box add text Electronics department.10. Choose Add shape after option from create graphics group on smart art tools design tab. It create a text box in same level after Electronics department. In that text box add text English department.11. Choose Add shape after option from create graphics group on smart art tools design tab. It create a text box in same level after English department. In that text box add text Botany department.12. Choose Add shape after option from create graphics group on smart art tools design tab. It create a text box in same level after Botanydepartment. In that text box add text Zoology department.13. Choose Add shape after option from create graphics group on smart art tools design tab. It create a text box in same level after Zoology department. In that text box add text Library.14.Choose nice layout from layouts group on smart art tools ->designtab.15. Choose nice Smart Art Style (2 D or 3D ) from Smart Art Styles group on smart art tools ->design tab.16. Choose nice Color from Change Colors group on smart art tools ->design tab.

(18) i)Program for sum of factors of a number/* Program for sum of factors of a number */#include<stdio.h>void main(){

int n,i,s;

C programming 111clrscr();

printf("\n-------------INPUT--------------------\n");printf("enrter the value to find the factors");scanf("%d",&n);

printf("\n---------------OUTPUT----------------\n");printf("\n factors of %d: \n",n);s=0;for(i=1;i<n;i++){

if(n%i==0){

printf("\t%d",i);s+=i;

}}printf("\n sum of factors= %d",s);getch();}

ii) Program for sum of digits of a number/* A program to find the sum of digits of a given number */#include<stdio.h>void main(){

int num,r,sum=0; /* num is a given number, r is remainder, sis sum*/

clrscr();printf("\n-------------INPUT--------------------\n");printf("Enter a number to find sum of digits : ");scanf("%d",&num);while(num!=0){

r=num%10;sum+=r;num/=10;

}printf("\n---------------OUTPUT----------------\n");printf("Sum of digits of %d of number is %d",num,sum);

}(19) Program to check whether given number is

(i) prime or not(ii) perfect or not

i)/*Program to check whether the given no is prime or not*/#include<stdio.h>void main()

C programming 112{

int n,i;clrscr();printf("\n-------------INPUT-------------\n");printf("\nEnter a number to check prime or not : ");scanf("%d",&n);for(i=2;i<n;i++)

if(n%i==0)break;

printf("\n-------------OUTPUT-------------\n");if(n==i)

printf("\n%d is prime number",n);else

printf("\n%d is not prime number",n);}ii)

/*Program to check whether the given no is perfect or not*/#include<stdio.h>#include<conio.h>void main(){

int i,n,s=0;clrscr();printf("\n-------------INPUT-------------\n");printf("enter the number: ");scanf("%d",&n);printf("\n-------------OUTPUT-------------\n");for(i=1;i<=n/2;i++)if(n%i==0)

s+=i;if(s==n)

printf("Given number is perfect");else

printf("Given number is not perfect");getch();

}(20) Program using recursion for factorial of a given number/*program to find the factorial of a given number using recursion*/#include<stdio.h>void main(){

long int f;int n;

C programming 113long int factorial(int n);clrscr();printf("\n--------------INPUT--------------");printf("\nEnter a number to find factorial:");scanf("%d",&n);f=factorial(n);printf("\n-------------OUTPUT--------------");printf("\nFactorial of %d number is %ld",n,f);

}long int factorial(int n){

if(n==1)return(1);elsereturn(n*factorial(n-1));

}(21) Program Using functions(i) with out parameters(ii)with parameters

/*program using functions with out parameters*/#include <stdio.h>main(){

maximum ( );}void maximum (){

int a,b;printf("\n--------------INPUT--------------\n");printf ("in enter a,b values");

scanf("%d%d%",&a,&b);printf("\n-------------OUTPUT--------------\n");

if (x>y) printf("%d is maximum", x); else printf ("%d is maximum", y);}/*program using functions with parameters*/

C programming 114#include <stdio.h>main(){

int a,b;void maximum (int r,int y);clrscr();printf("\n--------------INPUT--------------\n");printf ("in enter a,b values");

scanf("%d%d%",&a,&b); maximum (a,b);}void maximum (int x,int y){

printf("\n-------------OUTPUT--------------\n"); if (x>y) printf("%d is maximum", x); else printf ("%d is maximum", y);}(22) Program for sorting an array#include<stdio.h>void main(){

int n[10],temp;int i,j;clrscr();printf("\n--------------INPUT--------------\n");printf(" enter 10 numbers \n");for(i=0;i<10;i++)

scanf("%d",&n[i]);printf(" input numbers are \n");for(i=0;i<10;i++)

printf("%d\n",n[i]);for(i=0;i<9;i++){

for(j=i+1;j<10;j++)if(n[i]>n[j]){

temp=n[i];

C programming 115n[i]=n[j];n[j]=temp;

}} printf("\n-------------OUTPUT--------------\n");printf(" numbers in ascending order \n");for(i=0;i<10;i++)

printf("%d\n",n[i]);getch();}(23) Program for matrix addition & substraction#include<stdio.h>void main(){

int a[3][3],b[3][3],c[3][3],d[3][3],i,j;clrscr();printf("\n--------------INPUT--------------\n");printf("\n enter values to matrix:A");for(i=0;i<3;i++)for(j=0;j<3;j++){

printf("\n a[%d][%d]=",i,j);scanf("%d",&a[i][j]);

}printf("\n enter values to matrix:B");for(i=0;i<3;i++)for(j=0;j<3;j++){

printf("\n b[%d][%d]=",i,j);scanf("%d",&b[i][j]);

} printf("\n-------------OUTPUT--------------\n");for(i=0;i<3;i++)for(j=0;j<3;j++)

c[i][j]=a[i][j]+b[i][j];printf("\n Sum of two Matrix A &B:\n");for(i=0;i<3;i++){

for(j=0;j<3;j++)

C programming 116printf("%5d", c[i][j]);printf("\n");

}for(i=0;i<3;i++)for(j=0;j<3;j++)d[i][j]=a[i][j]-b[i][j]; printf("\n Difference of two Matrix A &B:\n");for(i=0;i<3;i++){

for(j=0;j<3;j++)printf("%5d",d[i][j]);printf("\n");

}}

ii)Program for reversing digits of a Number#include<stdio.h>void main(){

int s=0,n,r;clrscr();printf("\n----------INPUT-------------\n");printf"\nEnter a number to reverse digits");scanf("%d",&n);while(n!=0){

r=n%10;s=s*10+r;n=n/10;

} printf("\n---------OUTPUT---------\n");printf("\nReverse digits of given number=%d",s);

} (24) Program for matrix multiplication/*Program to perform matrix multiplication after verifying matrixmultiplication conditions.*/#include<stdio.h>#include<conio.h>void main()

C programming 117{

int a[10][10],b[10][10],c[10][10],rows,cols;void read(int a[][10],int rows,int cols);void write(int a[][10],int rows,int cols);void multiply(int a[][10],int b[][10],int c[][10],int

rows,int cols);clrscr();printf("\nEner size of a matrix:(rows&cols)");scanf("%d%d",&rows,&cols);printf("\n----------INPUT-------------\n");printf("\nEnter values for A matrix:\n");read(a,rows,cols);printf("\nEnter values for B matrix:\n");read(b,rows,cols);if(cols==rows){

multiply(a,b,c,rows,cols);printf("\n---------OUTPUT---------\n");printf("\nResultant matrix :\n");write(c,rows,cols);

}elseprintf("\n Multiplication is not possible");

} void read(int a[][10],int rows,int cols) {

int i,j;for(i=0;i<rows;i++)for(j=0;j<cols;j++){

printf("a[%d][%d]=",i,j);scanf("%d",&a[i][j]);

} } void write(int a[][10],int rows,int cols) { int i,j;

for(i=0;i<rows;i++)

C programming 118{

for(j=0;j<cols;j++){

printf("%5d",a[i][j]);}printf("\n");

} } void multiply(int a[][10],int b[][10],int c[][10],int rows,int cols) {

int i,j,k;for(i=0;i<rows;i++){

for(j=0;j<cols;j++){

c[i][j]=0; for(k=0;k<cols;k++) {

c[i][j]+=a[i][k]*b[k][j]; }

}}

}(25) Program to demonstrate structures#include<stdio.h>#include<conio.h>struct stu{

int no;char name[10];float avg;

};void main(){

struct stu s;

C programming 119printf( "\n enter student no,name,avg marks");scanf("%d%s%f",&s.no, &s.name, &s.avg);printf(" no=%d",s.no);printf(" name=%s",s.name);printf(" marks=%2f",s.avg);getch();

}(26) Program sorting strings using pointers/*26.Sorting sorting strings using both functions and pointers*/#include<stdio.h>#include<string.h>void main(){

int i,n=0;char *x[10];void orderstrings(int n,char *x[]);n=0;printf("---------------INPUT--------------------\n");printf("Enter strings to sort type \'END\' when finished\

n");do{

x[n]=(char*)malloc(12*sizeof(char));printf("String %d :",n+1);scanf("%s",x[n]);

}while(strcmpi(x[n++],"END"));orderstrings(--n,x);printf("\n-----------OUTPUT------------");printf("\nReordered list of Strings:\n");for(i=0;i<n;i++)printf("\nString %d: %s",i+1,x[i]);

}void orderstrings(int n,char *x[]){

char *temp;int i,item;for(item=0;item<n-1;++item)/*find the lowest of all remaining strings*/for(i=item+1;i<n;++i)if(strcmpi(x[item],x[i])>0)

C programming 120{

temp=x[item];x[item]=x[i];x[i]=temp;

}return;

}(27) Program to create file to store & relrieve strings using fputs( ) and fgets ( ).#include<stdio.h>#include<process.h>main(){

FILE *fp;char str[80],str1[80];fp=fopen("data.txt","w");if(fp==NULL){

printf("\n ERROR-in file opening");exit(0);

}printf("\n enter line of text: ");gets(str);fputs(str,fp);fclose(fp);fp=fopen("data.txt","r");if(fp==NULL){

printf("\n ERROR-input file opening");exit(1);

}fgets(str1,50,fp);printf("\n textfrom file: ");puts(str1);fclose(fp);

}(28) Program to count no of words, lines in a text./*Counting characters,words and lines in a text*/#include<stdio.h>

C programming 121void main(){

int char_count=0,words=0,lines=0,c,w;char text[80];/*char_count counts no.of characters,words count no.of

words,lines count no.of lines*/clrscr();printf("\n------------INPUT---------------\n");printf("\nEnter text :\n");do{

c=0; w=0;while((text[c]=getchar())!='\n'){

c++;if(text[c]==' ')

w++;}words+=w;char_count+=c;lines++;

}while(c>0);printf("--------------OUPTPUT-------x---");printf("\nNo.of lines = %d",--lines);printf("\nNo.of words = %d",words);printf("\nNo.of characters = %d",char_count);

}(29) Program to create table of Triangular numbers./*Program to Generate a Table of Triangular Number*/void main(){

int n,triangular_number;printf("TABLE OF TRIANGULAR NUMBERS\n\n");printf("n Sum from 1 to n \n");printf("--- --------------------------\n");triangular_number=0;for(n=1 ;n<10; ++n){

C programming 122triangular_number=triangular_number+n;printf(" %d %d\n",n,triangular_number);

}}

(30) Program to demonstrate(i) Unions(ii) Enumerate data types

#include<stdio.h>#include<string.h>union stu{

int no;char name[10];float avg;

};void main(){

union stu s;clrscr();s.no=10;printf("\n student no = %d", s.no);strcpy(s.name, "pvr");printf("\n student name= %s", s.name);s.avg=90;printf("\n average = %f", s.avg);getch();

}/*Program for Enumerate data types*/

#include<stdio.h>void main(){

enum days{

SUNDAY, MONDAY,TUESDAY, WEDNESDAY,THURSDAY, FRIDAY, SATURDAY};enum days today, holiday;today=MONDAY;clrscr();

if(today>SUNDAY)

C programming 123printf("Today is a working day");

elseprintf("Today is a holiday");

}