UNIT 2 WRITING A PROGRAMME IN 'C' - eGyanKosh

42
UNIT 2 WRITING A PROGRAMME IN 'C' Structure Page Nos. 2.0 Introduction 42 2.1 Objectives 43 2.2 Structure of C Program 44 2.3 Execution of C Program 44 2.4 Basic Data Types and Operators 47 2.4.1 Examples Programs 56 2.5 Control Structures 58 2.5.1 If Statement 58 2.5.2 Wilile Loop 60 2.5.3 Do-While Loop 61 2.5.4 For Loop 61 2.5.5 Break and Continue 63 2.5.6 Switch Statement 65 2.6 Complex Data Types 67 2.6.1 Structures 67 2.6.2 Arrays 68 2.6.3 Strings 71 2.6.4 Pointers 73 2.6.5 User Defined Type Declaration 74 2.7 Functions 77 2.7.1 Declaration and Definition of Functions 78 2.7.2 Characteristics of Function 79 .2.7.3 Call by Value and Call by Reference 80 2.9 Summary 84 2.1 o References/Further Readings 84 2.0 INTRODUCTION 42 This Unit will introduce you to the practical aspects ofC Programming which includes defining the basic structure of C program and how to execute a C .Program. However, to make this Unit more useful, we have added some basic concepts of C Programming in this Unit, which provides a basic recapitulation of the concepts that you have already learnt and some more concepts that are added .here for the purpose of future reference. As far as C is concerned, it is a language for professional programmer's and is a structured language by nature. C was designed and developed by Kernighan and Ritchie who wrote the original language definition in their book, "The C Programming Language", in 1978 as their research.

Transcript of UNIT 2 WRITING A PROGRAMME IN 'C' - eGyanKosh

UNIT 2 WRITING A PROGRAMME IN 'C'

Structure Page Nos.

2.0 Introduction 422.1 Objectives 432.2 Structure of C Program 442.3 Execution of C Program 442.4 Basic Data Types and Operators 47

2.4.1 Examples Programs 562.5 Control Structures 58

2.5.1 If Statement 582.5.2 Wilile Loop 602.5.3 Do-While Loop 612.5.4 For Loop 612.5.5 Break and Continue 632.5.6 Switch Statement 65

2.6 Complex Data Types 672.6.1 Structures 672.6.2 Arrays 682.6.3 Strings 712.6.4 Pointers 732.6.5 User Defined Type Declaration 74

2.7 Functions 772.7.1 Declaration and Definition of Functions 782.7.2 Characteristics of Function 79

.2.7.3 Call by Value and Call by Reference 802.9 Summary 842.1o References/Further Readings 84

2.0 INTRODUCTION

42

This Unit will introduce you to the practical aspects ofC Programming whichincludes defining the basic structure of C program and how to execute a C.Program. However, to make this Unit more useful, we have added some basicconcepts of C Programming in this Unit, which provides a basic recapitulation ofthe concepts that you have already learnt and some more concepts that are added

.here for the purpose of future reference. As far as C is concerned, it is a languagefor professional programmer's and is a structured language by nature. C was designedand developed by Kernighan and Ritchie who wrote the original languagedefinition in their book, "The C Programming Language", in 1978 as theirresearch.

The C Programming Language was developed by Bell Laboratories in the early

seventies. It had two predec~ssor languages BCPL and B. C is a High Level

Language that was designed with the main objective of writing portable system

programs. (A portable program is the one that can be ported from one hardware

platform to other. One of the most common system program is the Operating

System). The C was used to write the UNIX operating system so that it can be

ported to different hardware with minimum of rework. The formal ANSI standard

for C was produced in 1989. ANSI C supports the procedural 'programming

paradigm. In 1986 a descendent ofC was developed by Bjame Stroustnrp thatsupported the Object Oriented programming paradigm.

In order to successfully complete this unit, you will not need any prior knowledge of

the C programming language. We will begin with the most basic concepts ofC and

take you up gradually. Programming in C is a tremendous asset in those areas where

you may want to use Assembly Language but would rather keep it a "simple to write"and "easy to maintain" program.

Throughout this Unit, every attempt will be made to indicate to you what constructs

are available in every C compiler because they are part of the ANSI-C standard, the

accepted standard ofC. The examples given in this Unit are ANSI C compliant and

can be run on any compiler, as most ofthe compilers are ANSI C compliant.

However, please note that this Unit cannot cover all aspects of programming in C,

simply because there is too much to cover, but it will instruct you in all you

need for the majority of your programming in C, and it will introduce essentiallyall of the C language ..

2.1 OBJECTIVES

After studying this unit, you should be able to:

• identify the structure of the C program;

• compile, execute and debug the C program;

• identify and use the various data typ~s and operators in your programs;

• use appropriate control structures, to fit in to the logic ofy?ur program;

• use basic data types to buid the complex data types; and

• implement your logic with the help of functions.

Writing a Programme in 'C'

43

In the previous section, you have seen the structure of a C program. But whatsteps do you need to follow to execute a C program. Executing. a programwritten in C programming language involves a series of steps. These are:

Lab Manual - 1 2.2 STRUCTURE OF C PROGRAM

A C program may contain one or more sections as shown below:

DocumentationLink SectionDefinition SectionGlobal declaration SectionMain 0 function section{ Declaration part

Execution part }Subprograms

I

user defined functionsFunction!Function 2

IFunction N

The Document section consists of a set of comment lines giving the name of theprogram, the author and other details which programmer would like to use later. TheLink section provides instructions to the compiler to link functions from the systemlibrary. The Definition section defines all symbolic constants ..There are somevariables that are used in more than on e function. Such variables are Global variablesand are declared in the Global declaration section that is outside of all the functions.

Every C program must have one mainO function section, this is the section, fromwhere the execution of the program starts. This section contains two parts i.e.declaration and executable. The declaration part declare all the variables used in theexecutable part. These two parts must appear between the opening and closing curlybraces i.e.{--}. Program execution starts at the opening braces and terminates at theclosing braces. All statements in declaration and executable part must terminate withsemicolon (;).

The Subprogram section contains all the user defined functions which are called inthe mainO function.

In the subsequent section we will study the details of the sections described here.

2.3 EXECUTION OF C PROGRAM

44

1. Creating the program2. Compiling the program3. Linking the program with the functions that are needed from the library4. Executing the program

You need to install a C compiler to compile and execute a C program. Youshould make sure that your compiler is ANSI C compliant, and also has theability to generate an executable file. The steps of execution ofthe program,which are listed above are independent of (he operating system. However,please note that the commands that may be required to be executed by youmay be different. Further, it should be noted that the conventions for namingfiles may differ on different systems.

All ofthe example programs in this u;it will compile and execute correctlywith any good ANSI compliant C compiler. Fortunately, most of the Ccompilers available have a means of compiling a standard C program which iswritten for the DOS environment and includes none of the Windowsextensions. You should check the documentation about the compiler that you,are using for the capabilities and limitations. Most of these compliers include'integrated development platform for large projects in C and C++. However,you may initially use them for developing simple C programs. Some of thepopular compilers are:

Turbo C is an Integrated Development Environment (IDE) for CProgramming Language from Borland. It is low priced software. It is a smallcompiler and has fast compilation speed.

Borland C++.is a C and C++ programming environment by Borland that wasmeant to replace Turbo. However, Turbo is still used at many places. Borlandhas better debugger than Turbo.

Microsoft Visual C++ (you may find it as a part of Microsoft Visual Studiopackage) is a commercial IDE for C, C++ with advanced library support fordeveloping applications in Windows environment.

Dev C++ is also an IDE for the C and C++ programming languages. Thissoftware is available for FREE under the GNU General Public License (GPL).

GCC was GNU C Compiler. However, now this compiler supports manyother languages including C++, Fortran, Java etc. It now is called the GNUCompiler Collection.

The rest of this section will be devoted to give you a brief overview about howto use two of these compilers - Turbo C and Dev C++.

Writing a Programme in 'C'

45

Lab Manual - 1

46

Using Dev C++:

,

Dev c++ compiler can be downloaded from the website http://www.bloodshed.netYou need to perform the following steps to use Dev C:

• You can install the compiler by executing its installation file most likely namedsetup.exe. You will find that a folder Dev-cpp is created in the folder you haveinstalled Dev C++.

• Opening this folder you will find that it contains again many folders/contents.

• Out of these folders BIN is very important, however, you may like to explorethe contents of other folders like LIB, DOC, INCLUDE etc., to "enhance yourknowledge about the subject.

• Now, to write a program like the sample program, you need to run the Dev C++software, You can run the Dev C++ compiler from Start Menu of Windowsby selecting: "Start" -7 "Programs" -7 "Bloodshed Dev-C++" -7 "Dev-C++". A GUT window will be at your disposal to write and run your programs.

• Now, you open the file menu, choose the new option, and select the option"Source File". A blank window will appear with flashing cursor, key inthe program in it and finally save the file by selecting "File" -7 "Save As"option. This will open a dialog box where you can select a file name. Pleasemake sure that in the dialog box, "SAVE AS TYPE" you select the option "Csource files (*.c)" as you are creating a C program source file.

• Once you have keyed in the program correctly, you can compile it using theMenu option "Execute" -7 "Compile" and ifthere are no compilation errors,then you can. run the program you have created by selection the Menu Option"Execute" -7 "Run". Alternatively, you can also use the shortcut keys tocompile and run the program. You can Press CTRL+F9 to compile theprogram and CTRL-FIO to run the program ifit has been successfullycompiled.

• If your programmas, has, no compilation error then it will run fine and to seeyour output you can simply press CTRL+F5; other wise the errors will belisted. In this case, you need to identify the errors and debug your code till allthe errors are removed. At this point your code will be ready to run.

• Finally to quit either use "File" -7 "Exit" option of the File menu.

Using Turbo C:

Turbo C compiler is easy to use compiler for beginners. If you want to use TurboC, you must make sure that you get licensed copy of the Software. you need toperform the following. steps to use Turbo C:

-• You can install the compiler by executing its installation file i.e. TC.exe. You will

. find that a folder TC is created in the folder you have installed Turbo C.

• Opening this folder you will find that it contains again many folders/contents.

"

• Out of these folders ~IN is very important, however, you may like to explorethe contents of other folders like; LIB, DOC, INCLUDE etc., to enhance yourknowledge about the subject.

• Now, to write a program like the sample program, you need to open the BINfolder and find the file named TC.exe inside it. You should double click on thisfile and a GUI window will be at your disposal to write and run yourprograms.

-~• Now you open the file menu, choose the new option, a blank window will

appear, key in the program in it and finally save the file (by pressingfunction key F2 or use the save option offile menu) with the extension c. Forexample, you can give name as citprogram1.c, try.c, program1.c etc. Pleasenote that the file will automatically be saved in the BIN folder. You mayexplore the BIN folder to locate your saved file.,

• Although when you look at the menu bar, you will find that the options forcompiling and running the programs are available there, but you can simplyuse ALT+F9 or Ctrl+F9 to perform the job.

• The program will first be compiled. If your program no compilation error thenit will run fine and to see your output you can simply press ALT+F5; otherwise the errors will be listed. In this case, you need to identify the errors anddebug your code till all the errors are removed. At this point your code will beready to run.

• Finally to quit either use QUIT option of the File menu or use ALT+X.

An important observation about Dev C++ and Turbo C for you. The momentyou save a file, let us say with the name u2progl.c, only one file of name try existsin the BIN folder, having the extension .c. But after compiling you find that threemore files with same name but with different extensions (i.e .obj, .bak, .exe)appear in the BIN. The answer is hidden in the steps of execution of C program.You wrote u2progl.c after compiling u2progl.obj file is created further to takecare of errors in your created file, the u2progl.bak file is generated and finallyon linking the u2prog1.obj file with the system libraries u2prog1.exe is created.So, you create u2prog1.c and system will create u2prog1.obj, u2prog1.bak andu2prog1.exe along with u2prog1.c and all these files will reside in BIN folder.

The following sections present a brief Recapitulation ofC Programming. Please notethat it is not complete C programming. You may refer to further readings, if you wantto know more about C.

2.4 BASIC DATA TYPES AND OPERATORS

The concept that you must learn first before any programming language is - whatis an identifier and, how to name an identifier. An identifier is the distinguishing

"

name that is used for-a variable or function or data definition in a C program.. . - ,

Writing a Programme in 'C'

47

Lab Manual - 1 An identifier in C programming language can consist of a combination ofalphanumeric characters, the first being a letter of the alphabet or an underline,and the remaining being any letter of the alphabet, any numeric digit, 'or theunderline. While using the identifiers one has to keep in mind that that, Ccompiler is case sensitive, i.e., it takes capital letters and small ietters or eventheir combination, differently C provides a standard, minimal set of basic datatypes. Sometimes these are called "primitive" types. More complex datastructures can be built up from these basic types. These data types specifies thatidentifiers may be of the following types or may be designed to return the dataof following types as given below in Table 1.

Table 1 : Data TypesType Name Bytes Range

16 bit system

char • 1 -128 to 127

sighed char 1 -128 to 127

unsigned char 1 o to 255

short 2 -32,768 to 32,767

unsigned short 2 o to 65,535

int 2 -32,768 to 32,767

unsigned int 2 o to 65,535

long 4 -2,147,483,648 to 2,147,483,647

unsigned long 4 o to 4,294,967,295

float 4 3.4E+/-38 (7 digits)

double 8 1.7E+/-308 (15 digits)

long double 10 1.2E+/-4932 (19 digits)

Type Name Bytes Range32 bit system

char 1 -128 to 127signed char 1 -128 to 127unsigned char 1 o to 255short 2 -32,768 to 32,767unsigned short 2 o to 65,535

int 4 -2,147,483,648 to 2,147,483,647

unsigned int 4 o to 4,294,967,295long 4 -2,147,483,648 to 2,147,483,647

unsigned long 4 o to 4,294,967,295float 4 3.4E+/-38 (7 digits)double 8 1.7E+/-308 (15 digits)

long double 10 1.2E+/-4932 (19 digits)48

char It is ASCII character of at least 8 bits. As a practical matter char isbasically always a byte which is 8 bits which is enough to store a singleASCII character. 8 bits provides a signed range of -128 to 127 or anunsigned range is 0 to 255. char is also required to be the "smallestaddressable unit" for the machine -- each byte in memory has its ownaddress.

int It is default integer of at least 16 bits, with 32 bits being typical. Defmedto be the "most comfortable" size for the computer. If you do not reallycare about the range for an integer variable, declare it intsince that is likelyto be an appropriate size (16 or 3~ bit) which works well for that machine.

float A single precision floating point number i.e. numbers with a decimal pointand a fractional part with a limited accuracy. It typically occupies 4 bytes.

,double A double precision floating point number i.e., float type but with better

precision of accuracy. It occupies 8 bytes.

NOTE Further the data holding capacities of these fundamental data types can bemodified by starting or prefixing the name of these data types with any ofthe following types of modifiers i.e., short, long, unsigned short, signed,unsigned, unsigned long etc. as enlisted above, it is to be noted that theirincorporation along with the fundamental data type modifies the datamanaging capacity of the identifier, for example

Apart from the knowledge of the data types and their respective data holdingcapacities we need to know what are the various keywords available, to write a Cprogram.

There are 32 words defined as keywords in C. These have predefined uses and cannotbe used for any other purpose in a C program. They are used by the compiler as an aidto compiling the program. They are always written in lower case. A complete list isgiven in the table 2.

Table 2: Key Words

auto double int struct

break Else long switch

case Enum register typedef

char extern return union

const Float short unsigned

continue For signed void

default Goto sizeof volatile

do If static while

Writing a Programme in 'C'

49

Define a constant or a macro.

Inserts a text i.e., a portion of the program from the other text file.

Remove a macro or constant definition.

Ignore or include the following lines of code in the program.depending upon whether a name has a macro definition or not

Similar to ifdefbut with reverse test.

Include or ignore the following lines of code depending upon the. value of the expression to be 0 or 1.

Termination of a #if, #ifdef or #ifi).def.

Corresponding to #if, #ifdef and #ifndef for the else part.

In addition to this list of keywords, your compiler may define a few more. If it does,they will be listed in the documentation that came with your compiler. Almost each ofthe above keywords will be defmed, illustrated, and used in this unit.

Lab Manual - 1

Further to write a program, we need to have the knowledge of data and structuring ofprogram, none the less the comments also plays vital role in enhancing the readability .of the program. Comments in C are enclosed by slash/star pairs: 1* .. comments .. *1which may cross multiple lines. C++ introduced a form of comment started by twoslashes and extending to the end of the line: II comment until the line end The IIcomment form is so handy that many C compilers now also support it, although it isnot technically part of the C language.

Any computer program has two entities to consider, the data, and the program. Theyare highly dependent on one another and careful planning of both will lead to a wellplanned and well written program. Unfortunately, it is not possible to study eithercompletely without a good working knowledge of the other, so, knowing the syntaxrules for writing program is must., because before writing a program we should knowwhat is the program syntax and what are the basic rules to write a program.

Syntax Rules and Key Notes for beginners in C

1) 'C' is a free format language i.e., we can start writing anywhere on a line unlikeother languages like; CaBaL, FORTRAN etc.

2) Any line that has # (called hash) character appearing in the first column, is a linethat is extracted and processed by C preprocessor. These lines contain directivesthat cause the 'C' preprocessor to include 'C' source code from other files.

3) Preprocessors the C compiler has a preprocessor which reads the source codeand does some processing before passing it to the compiler for the purpose ofcompilation. The preprocessor commands are not normal C command and theyare signaled to the compiler by putting # in the first column followed by thepreprocessor command, table of preprocessor options is given below:

# define

# include

# undef"- # ifdef

# ifndef

# if

# endif .

50 # else

4) A 'C' program, in general consists of many functions in addition to a functioncalled main, which may be standard or developed by the programmer. Thisfunction main must be mentioned only once in the program and since programexecution starts from main only, so it must be the first function, and can befollowed by any number of functions. The format of main function is mainO.

Note:• The blank parenthesis following the main indicates that there are no

arguments to the main program. However, the arguments can be given, theyare argc (argument count) and argv (argument variable), generally used forcommand line programming. The main function is present in the TUBfolder of the turboC compiler.

• C uses curly braces ({}) to group multiple statements together. Thestatements execute in order. Some languages let you declare variables on anyline (C++): Other languages insist that variables are declared only at thebeginning of functions (Pascal). C takes the middle road -- variables may bedeclared within the body of a function, but they must follow a '{'. Moremodem languages like Java and C++ allow you to declare variables on anyline, which is handy.

5) Variables: User defined variable names must follow following rules:a) First character-must be a letter, remaining characters can be letters or digits or

underscoreb) Lowercase and upper case letters are different.c) Although there is no restriction on the variable names, but only first 8 characters

are taken, so the first 8 characters of two variables should be different.d) Variable should not be a: reserved word Le. keyword.e) Each variable must be ~eclared before its usage within the program, this

declaration is achieved by linking variable name to its type.f) Variable may be an array or pointer of respective data type- we will discuss

them later. "g) Storage classes and their meaning.

Storage class Meaning

auto Local variables declared inside the function. Default isauto. No need to specify/write storage class.

static It may be internal or external type. Local variable whichexists and retains its value even after the control istransferred to the calling function.

extern Global variables are known and available to all thefunctions in the file.

register Local variable which is stored in the register of CPUinstead of memory.

h), On the basis of the scope' of a Variable (i.e., the region in which the variablecan perform), the variables are classified as:

Writing a Programme in 'C'

. 51

Lab Manual - 1 • i) External Variables: Variables whose scope is entire program, .declared before maint) or the function definition, the externalvariables are available in maim) as well as in the other functionsdefined in the program, and share the same memory location, thustheir value is available in all the functions including main( ).

ii) Internal or Local or Automatic Variables: Variables whose scopeis limited to the region where they are specified, declared inside thefunctions. A local variable exists only as long as the function where itis declared is still executing (we'll see functions shortly).

NOTE:

• Two variables defined with in two functions with the same name are different,they do not share the common memory location.

• External variables are defined so that that they remain common to more than,one function with in the same source file, these external variables are alsocalled as Global variables.

• However, C provides for storing the functions in different source files and tocompile these separately. In such case, we might like the global variable to bedefined across a single source file. For this purpose, we use extern statement.The external variables need to be defined in one source file only. In the othersource files, these variables should be defined with the extern statement. Thevariables declared in the extern statement share the common memory locationin the other source files with the same name. No, new location is reserved forthose variables syntax: extern type variables;

• Local variables are internal to the function in which those are defined. Afterthe execution of the function these values are undefined for optimization ofthe code the C compiler can assign the same memory location to other internalvariables of another function. Thus, without the knowledge of theprogrammer, the memory addresses can be assigned and reassigned todifferent variables by the compiler. However, it does not happen in the caseof external variables, because their definition is valid across the functions, andthe addresses assigned are permanent which cannot be reassigned to any othervariable by the compiler. By extern, these extern variables can be sharedacross the source files

• Static Variable: Ifwe want that the a permanent address should be assignedto the internal variable then that variable should be declared as static.Declaring an internal variable as static, the addresses of the variables remainfixed during the multiple calls to the same function. The static variables havetheir scope limited to one source file, these can not be extended to othersource files as in the case of the external variable with the use of extern. So,static variables can not appear in the extern statement.

• Register Variables: It is another storage class offered by C, the use of theseregister locations has limitations depending upon the type of hardware beingused. The registers are special memory locations with in the hardware which

52

6)

are faster than the normal memory locations. The memory locations which areoften used by the program can be declared as register type, so that thecompiler stores them in these memory locations for faster processing, syntax: registet type variables;Constants: C provides various types of constants:a) Integer constants

i) Decimal notations e.g. 457, -457,593L,etc.ii) Octal notations e.g. 056 Le. 46 is decimal value of octal 056

iii) Hexadecimal notations e.g. Ox9A4Fb) Float constants

iv) Standard notations e.g. 23.5, -95.375,46370.0v) Scientific notations e.g.4.3E4 (m E n, m-mantissa, n-exponent)

c) Character constants e.g. 'a' ,'$' ,'9'vi) Special character constants-or backs lash character constants

\ '\a' Audible alert (bell) '\b' back space'\f form feed '\n' new line'\r' carriage return '\1' horizontal tab'\v' vertical tab '\" single quote'\'" double quote '\?, question mark'\\' back slash '\0" null

d) String constants, is assumed to be array of type char, later we will learnwhat arrays are, e.g."C is Great".

7) Whatever may be the type of variable or constant but to have output or to giveinput you need to work with seme standard functions like printf and scanf,and to work with them you need to have idea of the format codes, whichsupport the concerned data types, a list of format codes is given below intable 3.

Table 3 : Format Codes

Code Meaning%d

' ".",~, ,;:, .for decimal output of an mteger..

%0 for ul1signedoctal output(without the leading zero)%x Hexadecimal output/without the leading OX)%u unsigned decimal output of an integer%c character output of a character variable%s output of a string%e output of a float or double value in exponent notation

e.g. 4.1 E 3%f output of a float or double value in fixed notation e.g. 4.543%g output of a float or double value in %e or %f which ever is

shorter.%% output a single % symbol

Writing a Programme in 'C'

Table 4 : Operator Precedence Table

Lab Manual - 1 • Note: in between the % and the format conversion characters listed above,there may be :

• A minus sign to indicate left alignment within the field, by default allvalues are just right justified

• An number specifying the field width, precision etc.

• The letter I, indicating the data item is a long int8) Operators are essential to form expressions to perform arithmetical and

logical operations, the operators are classified as :

a) Assignment operator (=)

b) Arithmetic operators (unary minus; *, / , % ; +,-,)

c) Relational operators (= =, !=, >, >=, <, <=)

d) Logical operators (&&, 11, ! )•

e) Increment & decrement operators (var++, var--, ++var, --var)

f) Bitwise operators(&, I, I" «, »)

g) Ternary operator (exp 1 ? exp2 : exp3)

List of all C operators are given in Table 4 : Operator Precedence Table.This table shows the order of precedence in the evaluation, operators ofgroup 1 are evaluated first followed by that of group 2 and so on. The ordershould bekept in mind while evaluating any expression.

54

GROUP OPERATOR MEANING1 0 Parenthesis and function

invocation[] Array subscripting

~Pointer qualificationStructure qualification

2 ! Logical negation

- Bitwise ones complement++ Increment-- Decrement

- Unary minusType Type

* Pointer dereferencing& Address of operandSizeof Size of

3 * Multiplication/ Division% Remainder

4 + Addition- Subtraction

5 « Shift left bits» Shift right bits

6 < Less than<=- Less than or equal to

> Greater than

>= Greater than or equal to

7 equal to

!= Not equal to

8 & Bitwise and

9 A Bitwise exclusive or

10 Bitwise or

11 && Logical and

11 Logical or12?:13

14

Ternary

Assignment=(+ = - = etc.)

Note: C does not have a distinct Boolean type, in fact int is used instead. Thelanguage treats integer 0 as false and all non-zero values as true. So the

statementi~O;while (i - 10) {

...}wiII execute until the variable itakes on the value 10 at which time the expression (i -lO)will become false (Le. 0). (we'll see.the whilet) statement a bit later)

8) Standard Library Functions: Many basic housekeeping functions are

available to a C program in form of standard library functions. To call these, aprogram must #include the appropriate .h file. Most compilers link in the

standard library code by default. The functions listed in the next section are themost commonly used ones, but there are many more which are not listed here.

• stdio.h file input and output functions like prmtff), scanft) etc.

• ctype.h character tests

• string.h string operations like strcmpt), strcatt) etc

-- math.h mathematical functions such as sinO , cosO etc

• stdlib.h utility functions such as mallocO and randt) etc.

• assert.h the assertt) debugging macros

• time.h date and time

Note: You can refer to the functions written inside these header files, by referring to

the help section of the compiler you are using, for turbo C you simply pressCtfl+F 1 and the help is activated for your reference, however a brief summaryof the functions present in these header files is given at the end of this unit.

Writing a Programme in 'C'

55

printf("Hello, all of you"); II printf is the library function defined inII stdio.h and is used to print

Lab Manual - I 2.4.1 Examples Programs

If you are gone through the concepts discussed above then you are in the situation towrite and understand the C programs, now you are advised to go through theprograms given below, execute them and identify how they are workingProgram 1 : Write a Program to print "Hello, all of you"

II Comments- this program will say hello to all of you

#include <stdio.h> II preprocessor include is used to include printf and scanf inIlyour program from header file stdio.hII start of the programmaim)

{

}

Program 2 : Write a Program to print sum and average of two numbers

II program to fin sum and average of two numbers

#inc1ude<stdio.h>

mainO{

int a,b,sum, avg; /1 declaration of variables

a=lO; b=20; II assigning values to the variables

sum=a+b; avg= sum/2; II performing addition and subtraction operation

printf("SUM = %d ; Average=%f', sum, avg); /I using format codes to print results}

Program 3 :Write a program to print sum and average of two numbers enteredby the user

II program to fin sum and average of two numbers entered by the user

#inc1ude<stdio.h>mairu)

{int a,b,sum, avg;

scanf("%d o/od\n", &a, &b);input

printf("you entered a= o/odand b= o/od\n", a,b);

sum=a+b; avg= sum/2; II performing addition and subtraction operation

printf("SUM = o/od ; A verage=%f", sum, avg); II using format codes to print results

II declaration of variables

II using scanffunction defined in stdio.h to take

}

56

Note: In the above program3 see how printf and scanf statements are written, inscanfwe are using &a and &b, because the values entered by the user are to bestored at the address of the variables a and b, so & is used. Where as in printstatement only a and b are used, because when a and b are referred then resultwill come from the address location of variable a and b. Further \n is used toincorporate new line in the output.

Lab Exercises 1

1) You are advised to write the program3 without \n and try printing the values ofthe address of a and b.

................................................................................................I

.................................................................................................

2) Modify the program 2 to perform all basic mathematical operations like sum,difference, product, average, division; on the two numbers entered by the user .

................................................................................................

..................................................... , .

3) Run the program given below and analyze its output.

#include<stdio.h> .

maim)

{

int a = 98; Ilnote here we are declaring and initializing the variablesimultaneously

float b = 23.566;

char c = 'A';

printf("address of a : %d", &a);

printf("Decimal : %d \n", a);.

printf("Octal : 0/00 \n", a);

printf("Hexa : %x \n", a);

printf("Real : %f\n", a);

printf("Real : %e \n", a);

printf("Real : %5.2 \n", a);

printf("Character : %c \n", c);

printf("ASCII code ofc : %d \n", c);

}

Writing a Programme in 'C'

57

Lab Manual - 1

58

--.

2.5 CONTROL STRUCTURES

After going through the previous section we hope you got an idea about the basic

components of C and their concerned syntax rules. Further to write a proper, wellstructured C program, we need to understand the working of various controlstructures, available-to facilitate the writing of a C program.

Control structures in Care classified as follows:1. if, if-else'

2. while, do-while3. for

4. switch.,

2.5.1 If Statement

Both an if and an if-else are available in C. The <expression> can be any validexpression. The parentheses around the expression are required, even if it is just asingle variable. Syntax of this control structure is as follows:

Syntax 1if «expression» <statement> .

clauseII simple form with no {}'s or else

Program 4 : Program for syntax 1,mainO{

in! a=10,b=5,c=10;if(a>b)

c=c+5;

printf("c=o/od",c); .}

Syntax 2if «expression>)-{ , II simple form with {}'s to group statements

<statement><statement>

}Program 5 : Program for syntax 2

maim){int a=l O,b=5,c;printf("a=o/od b=%d",a,b);if(a!=b)

{c=a; a=b; b=c;

prini:f("values of a and b are interchanged");

}printf("Interchanged values a=o/od b=o/od",a,b);

} --~Syntax 3

if «expression»{ IIfull then/else form

<statement>}else{

<statement>} ,

Program 6 : Program for syntax 3rnairu)

{int a=10,b=5,c;printf("a=o/od b=O/od",a,b);

if(a!=b){c=a; a=b; b=c;printf(''values of a and b are interchanged");

}else

{printf("a and b are equal");

}}

Conditional Expression -or- The Ternary Operator: The conditional expressioncan be used as a shorthand for some if-else statements. The general syntax of the

conditional operator is:

<expression1> ? <expression2> : ~expression3>

This is an expression, not a statement, so it represents a value. The operator works by

evaluating expressionl. If it is true (non-zero), it evaluates and returns expression2 .

Otherwise, it evaluates and returns expression3.The classic example of the ternary operator is to return the smaller of two variables,Every once in a while, the following form is just what you needed. Instead of...

if (x < y) {min = x;}else {min = y;}

You just saymin= (x < y) ? x : y;

Writing a Programme in 'C'

59

Lab Manual - 1/"

Program 7: Program to find maximum of three numbers enteredby the user

II program to demonstrate the use of nested if statement#include <stdio.h>maim){int a,b,c,high;printf("enter three numbers");scanf("%d o/od o/od\n\n",&a,&b,&c);if(a>b)

if(a>c)high =a;

elsehigh =c;

else11

if(b>c)high =b;

elsehigh =c

printf("Highest = o/od\n", high);}

Now you are advised to write the program 7 by using Conditional Expression i.e.,The Ternary Operator(: ? )

2.5.2 While Loop

The while, loop evaluates the test expression before every loop, so it can execute zerotimes if the condition is initially false. It requires the parenthesis like the if., thesyntax is as follows

while «expression»{

<statement>}

Program 8 : Program to dump the contents of input using while

1* this program reads the data until '$' is entered by the user and prints it, here we usethe getchan) and putchan) functions defined in stdio.h*1#include<stdio.h>mairu){char c;while((c=getcharO)!='$')

putchar( c );Ilhere I/O of the data is performed without using scanf and printf i.e. no %c, & etc}

60

2.5.3 Do-While Loop

Like a while, but with the test condition at the bottom of the loop. The loop body willalways execute at least once. The do-while is an unpopular area of the language, mosteveryone tries to use the straight whileif at all possible.

do {<statement>

} while (<expression»

Program 9: Program to print 10 numbers using do-while

#include<stdio.h>maim){int a=l;

do{

I

printf("o/od\n",a);art; //a++ means a=a+ 1

}while(a<ll)

}

2.5.4 For Loop

The for loop in C is the most general iooping construct. The loop header containsthree parts: an initialization, a continuation condition, and an action.

for «initialization>; <continuation>; <acti~n» {<statement>

}

The initialization is executed once before ~hebody of the loop is entered. The loopcontinues to run as long as the continuation condition remains true (like a while).After every execution of the loop, the action is executed. The following exampleexecutes 10 times by counting 0..9. Many loops look very much like the following.

for (i = 0; i < 10; i++){

<statement>}

C programs often have series of the form O..(some_number-I). It's idiomatic in C forthe above type loop to start at 0 and use < in the test so the series runs up to but notequal to the upper bound. In other languages, you might start at 1 and use <= in thetest.

Each of the three parts of the forloop can be made up of multiple expressionsseparated by commas. Expressions separated by commas are executed in order, left toright, and represent the value of the last expression. (See the string-reverse examplebelow for a demonstration of a complex for loop.)

Writing a Programme in 'C'

61

Lab Manual - 1 NOTE

• Writing of initialization and action expression is optional, if they are omitted thenthey are simply bypassed. But semicolon must be there to segregate theinitialization and action phase from the continuation one i.e., statement like

fore ; c> 10 ; ) //is acceptable

further ifnone of the expression is given then the loop runs infinitely i.e.,fore ; ;) //runs infinitely

Program 10: Program to print the table (i.e., first 10 multiples) of the number

entered by the user using for, and in a tabular form

#include<stdio.h>maim)

{int a, b, c;

printf("Enter the 'lumber, whose table is desired :");scanf("%d", &a);

for(b=l ;b<=lO;b++)

{

I

c=a*b;

printf("o/od X o/od = O/od", a,b,c);}

}

• Break and Continue plays vital role in altering the looping sequence, theirfunctioning is discussed below:

Lab Exercises 2

1) Write a program to print the entire list of the ASCII.codes ..................................................................................................................................................................................................................................................................................................

2) Write a program to print a right angled triangle using "*" ..................................................................................................................................................................................................................................................................................................

3) Write a program to identify that the entered number id prime or not...................................................................................................................................................................................................................................................................................................

4) Write a program to transform upper case letters to smaller case letters ..................... ' ..................................................................................................

62 ..................................................................~ .

5) Write a program to print the Fibonacci series............................................................................................................................................................................................................................................. ; .

6) Write a program to determine the grade of the student; if marks are >= 75grade should be A, if marks are >=60 grade should be B otherwise C...................................................................................................................................................................................................................................................................................................

7) Write a program to print factori~l of the number entered by the user, withoutusing function ..................................................................................................................................................................................................

•................................................................................................

8) Write a program to find six letter words in a text..................................................................................................

\................................................................................................................................................................................................

9) Use switch statement to produce the menu card ofa restaurant, the programshould ask the user about its choice and then tell the user about the dishesavailable ..................................................................................................................................................................................................................................................................................................

10) Write a program to transform the time entered in minutes in to the formatHours: Minutes ..................................................................................................................................................................................................................................................................................................

11) Write a program to transform the height entered by the user in feet's in toinches ................................................................................................ /.................................................................................................................................................................................................

12) Write a program to find the roots of a quadratic equation .................. ......... ......................................................~ .................................................................................................................................................................................................

2.5.5 Break and ContinueBreak: The breakstatement will move control outside a loop or switch statement.

. (

Stylistically speaking, breakhas the potential to be a bit vulgar. It's preferable to use astraight whilewith a single test at the top if possible. Sometimes, you are forced to use

Writing a Programme in 'C'

63

ib Manual-l

.,. ~.

4

a break because the test can occur only somewilere in the midst of the statements inthe loop body. To keep the code readable, be sure to make the break obvious--forgetting to account for the action of a break is a traditional source of bugs in loopbehaviour.

while «expression» {

<statement>

<statement>

if «condition. which can only be evaluated here»break;

<statement>

<statement>

}II control jumps down here on the break

The break does not work with if. It only works in loops and switches. Thinking thata break refers to an if when it really refers to the enclosing while has created somehigh quality bugs. When using a break, it's nice to write the enclosing loop to iteratein the most straightforward, obvious, normal way, and then use the break toexplicitly catch the exceptional, weird cases .

Program 11: Program to Demonstrate Break Statement

#include<stdio.h>maim){int x=O;for(; ;){

if(x>=10) break;else printf("%d \t", x++);

}

printf("that's all friends! \n");}

Continue: The continue statement causes control to jump to the bottom of the loop,effectively skipping over any code below the continue. As with break, this has areputation as being vulgar, souse it sparingly. You can almost always get the effectmore clearly using an if inside your loop.

while «expression» {

-, if «condition»continue;

II control jumps here on the continue

Program 12: Program to demonstrate continue statement

#include<stdio.h>maim){int x;for(x=l ;x<6 ;x++){if(x = = 3) continue;else printf("%d \t", x);

}}printf("that's all ! \n");}

2.5.6 Switch Statement,

The switch statement is a sort of specialized form of ifused to efficientlyseparate different blocks of code based on the value of an integer. The switchexpression is evaluated, and then the flow of control jumps to the matchingconst-expression case. The case expressions are typically int or char constants.The switch statement is probably the single most syntactically awkward anderror-prone features of the C language. Syntax of this control structure is asfollows:

switch «expression»{

case <const-expression-l >:<statement>break;

case <const-expression-Z>:<statement>break;

case <const-expression-J>:case <const-expression-4>:

II here we combine case 3 and 4

<statement>break;

default:<statement>

II optional

}

The classic example of the ternary operator is to return the smaller of two variables.Every once in a while, the following form is just what you needed. Instead of.. ",The syntax includes break statement, however, there is one more statement which iscontinue, we will discuss them afterwards.

Writing a Programme in 'C'

65

Lab Manual - I Each constant needs its own case keyword and a trailing colon (:). Once, executionhas jumped to a particular case, the program will keep running through all the casesfrom that point down -- this so called -"fall through" operation is used in the aboveexample so that expression-3 and expression-4 run the same statements. The explicitbreakstatements are necessary to exit the switch. Omitting the breakstatements is acommon error - it compiles, but leads to inadvertent fall-through behaviour.

Program 13: Program to count number of vowels, commas, and periods; usingSwitch

#include<stdio.h>mainO{int c, vowel, comma, period;vowel=comma=period=O;while((c= getch()) != '$')

switch(c)

{case 'a':case 'A':case 'e':

case 'E':case'i':case 'I':case '0':case '0':case 'u':case 'U':

vowel++;break;

case",':comma++;break;

case' .':

•period++;break;

}

printf("VOWELS=O/cd\n",vowel);printf("COMMAS=%d\n" ,comma);printf("PERIOD=%d\n" ,period); , ,

}66

2.6 COMPLEX DATA TYPES

We cannot only restrict ourselves to the data types given, their might be requirementsof defining the user defined data types, a collection of say lOO's of same type of dataetc. In order to work with that, we need to have the knowledge of complex data types,they are classified as:

1. Structures

2. Arrays

a. Multidimensional Arrays

b. Arrays of Structures ,3. Strings

4. Pointers

5. User Defined Type Declaration

Now, in this section, we will discuss these complex data types

2.6.1 Structures'

C has the usual facilities for grouping things together to form composite types, thisfacility is given through the arrays and structures (also called records).We will discussstructure here, keyword struct is used for the purpose. For the sake of understandingthe format of structure, following definition declares a type called "struct student"where struct is the keyword a~d student is the name of the structure it has three fieldsof different types named "roll_number" ,"percentage"and "grade", concentrating onthe data types of the field you will appreciate the feature because now we are clubbingup the data of different types in to one form, which is in our control and this is thebeauty of C. If you forget the semicolon at the end of the curly braces, which is theend of the structure definition then it tends to produce a syntax error in whatever thingfollows the struct declaration.

struct student{

int roll_number;

float percentage;

char grade;};

~ ,..This declaration introduces the type struct student (both words are required)as a new type. C uses the period (.) to access the fields in a record. You cancopy two records of the same type using a single assignment statement,however == does not work on structs,

Writing a Programme in 'C'

67

Lab Manual - 1 struct student X, YXroll number = I;X.percentage = 89;X.grade = 'B';Y ..roll_number = 11;Y.percentage = 98;

.: Y.grade = 'A';~.t.

Program 14: Program to take record of the student, like its roll number, name,marks, using structures

#incIude<stdio.h>struct rec{

int roll;char mime[20];int marks;};

maim){

struct rec student;cIrscr();

printf("\n enter name and roll no of students \n");scanf("%d %s", &student.roll, student.name);printf("\n enter marks");scanf("%d",&stud~nt.marks);printf("\n\n entered details are:\n");printf("O/od \n %s \n O/od",student.roll,student.name,student.marks);}

Note: we can have array of structures

2.6.2 Arrays

The simplest type of array in C is one which is declared and used in one place.There are more complex uses of arrays which we will address later along withpointers. The following declares an array called scores to hold 100 integersand sets the first and last elements. C arrays are always indexed from o. So thefirst int in scores array is scores[O] and the last is scores[99] as shown inFigure I.

int scores[IOO] ;

scores[O]=13; II set first element

scores[99]=42;11 set last element

68

Score

'Cl3Index 0

~ C-5673:J C22541 ~I 2

C42~99

There is space foreach int element inthe scores array-this element isreferred to as scores [0]

These elements have randomvalues because the code has notyet initialized them to anyting.

Someone else's memoryoff either and of thearray-do not read orwrite this memory.

Figure 1: Example of an ArrayIt's a very common error to try to refer to non-existent scores[ 1OO]element.C does notdo any run time or compile time bounds checking in arrays. At run time the code willjust access or mange whatever memory it happens to hit and crash or misbehave insome unpredictable way thereafter. "Professional programmer's language." Theconvention of numbering things O..(number of things - l)pervades the language.

Program 15: Program to read a string

#include<stdio.h>mainO{

char name[20];scanf("%s", name);

. • printf("your name is : %s", name);}

Program 16 : Program to find average of 5 numbers, using arrays

#include<stdio.h>maim){int i,sum=O,num[S];for(i=O; i<=4 ;i++){

scanf("%d",num~i]);sum=sum+num[i];}printf("Average = %d", sum/S);}

Multidimensional Arrays

The following declares a two-dimensional 10 by 10 array of integers, in the samemanner we can define more dimensions of the array, here the first and last elementsare initialized to be 13.

. Writing a Programme in 'C'

69

Lab Manual - 1

70

int board [10][10];board[O][O]= 13;board[9][9] = 13;

The implementation of the array stores all the elements in a single contiguous blockof memory. The other possible implementation wO,uldbe a combination of severaldistinct one dimensional arrays that's not how C does it. In memory, the array isarranged with the elements of the rightmost index next to each other. In other words,board[I][8] comes right before board[I][9] in memory. (highly optional efficiencypoint). Ifs typically efficient to access memory which is near other recently accessedmemory. This means that the most efficient way to read through a chunk of the arrayis to vary the rightmost index the most frequently since that will access elements thatare near each other in memory.'

Program 16 : Program to find sum of all the numbers entered in a twodimensional array of size 5x5

#include<stdio.h>maim){ int i,k,sum=O,num[5][5];

for(i=O; i<=4 ;i++)..{ for(k=O; k<=4 ;k++)

{

scanf("%d",num[i][k]);sum=sum+num[i][k];}

}-printf("SUM = o/od",sum); }

Array of Structures

The following declares an array named "numbers" which holds 1000 struct fraction's.

struct fraction numbers[1000];

numbers[O].numerator = 22;numbers[O].denominator = 7;

/* set the Othstruct fraction */

Here's a general trick for unraveling C variable declarations: ,look at the rlgItl'handside and imagine that it is an expression. The type of that expression is the left handside. For the above declarations, an expression w~ich looks like the right hand side(numbers[1000],or really anything ofthe form numbers[ ...]) will be the type on theleft hand side (struct fraction).

Program 18 : Program to take records of5 student, like its roll number, name,marks, using structures

#inc1ude<stdio.h>

struct rec

{int roll;char name[20];

int marks;

};maim){ int i;

struct rec student[ 4]iclrscrt);for(i=O; i<=4 ;i++){ printf("\n enter roll no. and name of students \n");

scanf("O/od %S", &student[i].roll, student[i].name);

printf("\n enter marks");scanf("O/od",&student[i].marks); }printf("\n\n entered details are:\n");

for(i=O; i<:::::4·;i++)

{printf("o/od. \n %s \n o/od",student[i].roll,student[i].name,student[i].marks);

}}

2.6.3 Strings1(

C has minimal support of character strings. For the most part, strings operate asordinary arrays of characters. Their maintenance is up to the programmer using thestandard facilities availabl~ior arrays and pointers. C does includea standard libraryof functions which perform common string operations, but the programmer isresponsible for the managirig the string memory and calling the right functions.Unfortunately computations involving strings are very common, so becoming a good

. .C programmer often requires becoming adept at writing code which manages stringswhich means managing pointers and arrays.

C string is just an array of char with the one additional convention that a "null"character ('\0') is stored after the last real character in the array to mark the end of thestring. The compiler represents string constants in the source code such as "binky" asarrays which follow this convention. The string library functions (see the appendixfor a partial list) operate on strings stored in this way. The most useful libraryfunction'is strcpy( char dest[], const char source[]); which copies the bytes of onestring over to another. The order of the arguments to strcpyt) mimics the arguments inof '='~- the right is assigned to the left. Another useful string function is strlen( constchar string[]);which returns the number of characters in C string not counting the

trailing '\0'.

Writing a Programme in 'C'

71

char local String [I 0];

strcpy(localString, "pinky");

Lab Manual - r Note: that the regular assignment operator (=) does not do string copying which iswhy strcpyt) is necessary. See Section 6, Advanced Pointers and Arrays, for moredetail on how arrays and pointers work.

The following code allocates a 10 char array and uses strcpyt) to copy the bytes ofthe string constant "pinky" into that local array ..

maim){

02

The memory drawing shows the local variable local Stringwith the string "pinky"copied into it. The letters take up the first 5 characters and the '\0' char marks the endof the string after the 'y'. The x's represent characters which have not been set to anyparticular value.

If the code instead tried to store the string "We enjoy languages which have goodstring support" into local String, the code would just crash at run time since the 10character array can contain at most a 9 character string. The large string will bewritten passed the right hand side of local String, overwriting whatever was storedthere.

Program 19 : Program to check that the string entered by user is palindrome ornot

maim){

char strl [80],str2[80];int ij;clrscn);printf("enter the string to be checked for palindrome\n");

scanf("%s" ,str 1);j=O;for(i=strlen(str 1);i>=O;i--)

{//printf("o/oe",strl [iD;str2O]=str1 [i];j++;

}str2[j++]='\0';if(strcmp(strl,str2)==O)

printf("entered a palindrome\n");72 }

2.6.4 Pointers

A pointer is a value which represents a reference to another value sometimes knownas the pointer's "pointee" .Syntactically C uses the asterisk or "star" (*) to indicate apointer. C defines pointer types based on the type pointee. A char*is type of pointerwhich refers to a single char. A struct fraction*is type of pointer which refers to astruct fraction.

int* intPtr;char* charPtr;

11declare an integer pointer variable intPtr/I declares a character pointer --

/*Below we declare two struct fraction pointers (when declaring multiple variables onone lline, the * should go on the right with the variable) *1

,

struct fraction *fl, *f2;

Further, the pointers are used to point to a certain data object Le., it stores the address,rather than the value of a given data "object. Once, the address of the variable is storedin a pointer, its value can be accessed in an indirect manner. The pointers are declaredby a type statement with a * appearing before the variable e.g. int *ptr or int* ptr bothmean same. Now, the name ptr is now used to point to a variable by storing itsaddress. Now to get the address of the variable, it has to be used with a unary operator& inthe following manner:~

<, •

int *ptr; ,int a, b, c;a=25;

ptr= &a;b = ptr;c = *ptr;

Note:

I/ptr gets the address of a and not its valueI/variable b is assigned the address stored in ptr

/I variable b is assigned the value stored at the address stored in ptr '';".

• Since, the pointers are supposed to store the address of a variable or array, so,it is -illegal to use it with constants and expressions Le. , &(a+b), &~5,&(a+25) are illegal,

• A pointer can be assigned the value 0 to explicitly represent that it does notcurrently have a pointee. Having a standard representation for "no current .

. pointee" turns out to be very handy when using pointers. The con_stant NULLis defmed to be 0 and is typically used when setting a pointer to NULL. Sinceit is just 0, a NULL pointer will behave like a Boolean false when used in aBooleancontext,

Writing a Programme in 'C'

73

Lab Manual - 1 Program 20 : Program to demonstrate simple working of pointers

maim)

{

int a = lO ,b, *ptr;ptr= &a;

b = *ptr;printf("Value ofb = %d \n", b);b = *ptr+5;printf(''New value ofb = o/od\n",b);

}

2.6.5 User Defined Type Declaration

C supports a feature known as "type definition" that allows user to define identifierthat would represent an existing data. Two type of user defined data types areavailable in C language:

• typedef~ • enumeratedienum)

typedef, this user-defined data type identifier can later be used to declare variables. Ittakes the general form :

Typedef type identifier;

Where type refers to an existing data type and "identifier" refers to "new" name givento the data type. The existing data type may belong to any class of type, including theuser-defined ones. Example

typedef int X;typedef float Y;

here x symbolizes int and y symbolizes float. They can later be used to declarevariables as follows:

X batch!" batch2; ..

Y namel [100], name2[75];

Now, batchl and batch2 are declared as int variables where as namel and name2 aredeclared as 100 and 75 floating point array variables.

74

( )

Exampletypedef struct fraction Fraction;Fraction fraction; II Declare the variable "fraction" of type "Fraction"

II which is really just a synonym for "struct fraction".

The following typedef defmes the name Tree as a standard pointer to a binary treenode where each node contains some data and "smaller" and "larger" subtree pointers.

typedef struct treenode* Tree;struct treenode{int data; .Tree smaller, larger; II equivalently, this-line could say}; II "struct treenode *smaller, *larger"

The main advantage of typedef is that we can create meaningful data type names for

increasing the readability of the program.

enum, it is defined as follows:

enum identifier {value 1, value 2, value 3, , value n};

The "identifier" is a user defined enumerated data type which can be used to declarevariables that can have one of the values enclosed with in the braces (known asenumeration constants). After this defmition, we can declare variables to be of this

new type as below:

enum identifier vl,v2,v3, ..... ,vn ;

The enumerated variables v1,v2, ..... ,vn can only have of the values value1, value2,..... value n . The arguments of the following types are valid i.e.

v 1= value3; v5= value 1;

Example:enum year {January, February; ..... ,December};enum year financeyear start, financeyear end;financeyear start = April;financeyear end = march;if (financeyear_start = January)

printf("its not the start of financial year");

Writing a Programme in 'C'

Lab Manual - 1 Note: The compiler automatically assigns integer digits beginning with 0 to all theenumeration constants. That is, the enumeration constant valuel is assignedo ;value 2 is assigned l, and so on. However, the automatic assignment can beoverridden by assigning values explicitly to the enumeration constants. Forexample enum day {Monday=2, Tuesday, .... , Sunday};

Lab Exercises 3

1) Write a program to find the highest and lowest of all the elements of aninteger array .

....................... , .,

.................................................................................................

............... , .2) Write a program to sort the elements of an array .

••• ••••••• •••••• t •••••••••••••••••••• - •••••••••••••••••••••••••••••••• '" ••••••••••••••••••••••••

3) Write a program to find sum, difference and product of two 2-D matrices .

. 4) Write a program to reverse the string entered b~ the user.-,.

::-~ .-'~"""'-! •.' •••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••"

•• t.... •••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••

. 5) Write a program to find that the entered string is palindrome or not.

••••••••••••••••• ~ ••••••••••••••••••••••••••••••••••••• ',' ••••••••••••••••••••••••••••••••••• 0 •••

"

6) Write a program using structures that takes the details of the students rollnumber, name, marks in 4 subjects, calculate the percentage marks securedby the student and accordingly award the grade to the student. The output .should show the roll number .name , percentage, and Grade secured by thestudent.

........•........................................................................................•• • i ••••••••••••••••••••••••••••• 0 •• 0.0 •••••• 0 ••••••• 00 ••••••• 0.0 •••••••••••••••• 0 ••• 0 •••••• 0 •••

7) Write a program using pointers to compute the sum of all elements stored inan integer array .

•• 0 •••••• 0 •• 00 •• 0 •• 0.0 •••••••• 0.0 •••••••• 0 ••••••••• 0 ••••••••••••• 0.•• 0 ••• 0 •••••• 0 r •• t: :._0 •••• 0.0. o.

76

2.7 FUNCTIONS

A function is a self contained block of statements that perform a coherent task ofsome kind, for which it is designed.

Writing functions avoid rewriting the same code again. The declared function can becalled whenever required. Using functions it become easier to write programs andkeep track of what they are doing. If the operation of a program can be divided in toseparate activities, and each activity placed in a different function, then each could bewritten and checked more or less independently. Separating the code in to modularfunctions also makes the program easier to design and understand.

Syntax:return data type function-name(parameters declaration){

local declarationstatement list

return( data);

Note: Function can be categorized in two ways:,a. Library functions, andb. User defined functions

Library functions are designed by compiler designers and these are stored on the diskexamplescanf, printf, getch etc. Functions that are not available in the disk, may bedefined by the programmer are called user defined functions.

important points for functions usage:

• Any C program contains at least one function, if the program contain~ only onefunction then it must be rnaint) function.

• If there are more than one function in the C program then one and only onefunction must be maim), because execution of the program begins with aim),

• The number of defined functions can be, any number, depending of programmerschoice and logic.

• Each function in a program is called in the sequence specified by the function _calls in maint)

• After each function has done its job, control returns to main. When maim) runsout ofthe function calls, the program ends.

• All C functions have state of perfect equality, except that the program executionbegins withmaim )., further full liberty is there that one function can call other.

Writing a Programme in 'C'·

77

addt);

Lab Manual - 1 2.7.1 Declaration and Definition of Functions

A function gets called (declared) when the function name is followed by semicolon.

Example:main( ){

}A function is defmed when function name is "followed by a pair of braces in whichone or more statements may be present:

Example:• add()

{

Statement 1;Statement 2;

}

Examples regarding the basic working of functions and their return type management:

Example 1maim){

display _msgt);}void display _msgt){

printf("this message is displayed by function");}

Example 2mainO{

float a,b,c;a==10.6;b==20.2;c=average/ a,b);printf("average of a and b= %f\n",c);

}

float average (float a, float b)

{float z;z==(x+y)/2retum(z);

78 }

int f;if(x= =1)

retum(1);

Lab Manual- 1 void message 1( ){

message2( );printf("\n close"); }

Here message 1( ) is called before message 2( ). However, it is recommended thatdefine the function in the same order in which they are called

4) 'A function can be called from other function. but a function can not be definedinside another function

main( ){ printf("\n this is main function");

multiplyt);/*This is wrong*/

{ mult (int a , int b);int c= a*b;

}}

5) A function can call itself. This process is called recursion.mainO{

int a, fact;printf("\n enter any number");scanf("%d1', &a);fact("%d",&a);

.: • ~t*=!ec(a2; " '~~printf("factorial value = O/od",fact);

} -rec (i~t x): "'{

elsef=x * rect(x-l);

return (f)}

2.7.3 Call by Value and Call by Reference

In general, the parameter passing in C is by value rather than by address, but passingthe parameter by value generally creates ambiguity. So.jhe technique of call byreference came in to picture which maintains persistence in the data stored by thevariables. To understand consider the example:

Example: Call by Value

maim){

80int a,b;

a=J; b=5; II or you can write scanf("%d %d", &a,&b);fun_abc(a,b);printf("value of a, b ; inside main = %d, %d \n ", a,b");

}fun abc(int a, int b)

{a=10; b=20;printf("value of a , b ; inside fun_ abc = o/od, o/od\n ", a,b");return;

}

The output will be:

value of a , b ; inside fun _ abc = 10, 20value of a , b ; inside main = 3 , 5 "

Ambiguity, note that, in above example although the values of the parameters a andb have been modified in the function but these are local to the functions. It is notreflected in the main program. So, the values in the main program remain unaltered.This form of parameter passing and calling is known as Call by Value. '

Example: Call by reference

From the above example, we find that any Jlarameter value changed in the function isnot reflected in the calling function. But, if we want that the change should bereflected in the calling function then the parameters shouldbe passed, as pointers tothe data element (i.e., the address of the data element) and not the value stored in thatdata element. This will produce reference to the same address i.e., same storagelocation, when referred by the calling program and the function, thus the ambiguity isresolved.

Such calls to function may look like fun_abc(&a,&b), now here the addresses of thevariable a and b are passed to the function and not the value which was the case ofcall by value i.e., fun_abc(a,b). Further the declaration of the function will now be

fun abc(int *a, int *b){------- }

Note: In the case of call by value, we can only return maximum of one value by any

function. However, in some situations it may be desired that the values to be

returned through the parameters so that the changes can be reflected there by

allowing more than one value to be returned by a function. In such situation,

we need to pass the parameters to the function as a pointer to the data element

rather than its value. So, that the same storage is referred by both the calling

program and the function

Let us rewrite the program written above for call by value, now by call by reference

Writing a Programme in 'C'

81

82

}arr_avg(int x[] , int y){

IIOR arr_avg(int *x , int y)

Lab Manual - 1Example: Call by reference \

mainO{

int a,b;

a=3; b=5; II or you can write scanf("%d %d", &a,&b);fun_abc(&a, &b);

printf("value of a, b ; inside main = %d, %d \n ", a,b");}

fun_abc(int *a, int *b)

{

*a=lO. *b=20;

printf("value of a, b ; inside fun_abc = o/od, %d \n ", a,b");return;

}

The output will be:

value of a , b ; inside fun_ abc = 10, 20

value of a , b ; inside main = 10, 20

Note: Passing arrays a s parameter

In order to pass array as an parameter, the name of the array is only desired to be

passed as an argument to the function, because the name of the array represents thestarting address (i.e., base address) of the array. Thus, pointers can be used toreference all the elements of the array in the function.

Example: to read 10 integers in an array and use the function to return the average

maim){

int n[IO], i ,a;for(i=O; i<=9; i++)

scanf("o/od", &n[i]);a=arr _avg(n, lO);printf("average = o/od\n", a);

int b, i;"b=O;for(i=O; i<y; i++)b=b+x[i];b=b/y;return(b);

}

Program 21 : Program to find factorial of entered number using functions

maim){

intn,m;printf("Enter the number whose factorial is to be found: ");scanf("%d",&n); ,m=fact(n);printf("factorial of%d = O/od",n,m);

}fact(int a){

int i,f;f=1;for(i= 1;i<=a;l++)

f=P];return(f);

}

La b Exercises 4

1) Write a program to swap two numbers, demonstrate the swapping by usingboth call by value and call by reference.

2) Write a program using functions, to determine the simple interestand the compound interest that a person is going to earn if s/he is goingto lend One lakh Rupees for 5 years at.15% rate of interest to Mr. X.

3) .Write a program using functions, to compute the surface area of circle,-. .square, rectangle, sphere. Hint - define a separate function for eachGeometry.

Writing a Programme in 'C'

83

'"'"Lab Manual - 1 2.9 SUMMARY

C is a powerful language, using this you can do many miracles like; assemblylanguage programming, embedded programming, Micro controller programmingetc. Although the topics discussed in this unit are very fundamental ones butno doubt a strong building can only stand on a strong foundation. So, jt isadvised that you learn the concepts taught in this unit and apply the same to upbring your hidden C Programmer.

2.10 REFERENCESIFURTHER READINGS

• E Balagurusamy, Programming in ANSI C,Third Edition, Tata Mc-Graw Hill.

• Yashwant-Kanetkar, Exploring C, BPB publications.• Fundamentals Of Computers And Information Technology by M N Doja, Deep

& Deep Publications• httpt//www.cprogramming.com/• http://inner-smile.com/• http://www.geocities.com/Silicon Valley /Park/7113/• http://www.codearchive.com/

84