programming fundamentals - wordpress.com · software engineering which will enable you to construct...

56
ER/CORP/CRS/LA06/003 1 Programming Fundamentals

Upload: others

Post on 17-May-2020

5 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Programming Fundamentals - WordPress.com · software engineering which will enable you to construct logical, readable, efficient programs. Though the language C will be used as a

ER/CORP/CRS/LA06/003 1

Programming Fundamentals

Page 2: Programming Fundamentals - WordPress.com · software engineering which will enable you to construct logical, readable, efficient programs. Though the language C will be used as a

ER/CORP/CRS/LA06/003 2

Copyright © 2004, Infosys Technologies Ltd

ER/CORP/CRS/LA06/003 Version no: 2.0

2

Course Objective

• To enable the participants to solve problems using the top down approach.

• To enable the participants to solve problems using modular approach through use of functions.

• Error Handling Techniques

• To introduce the participants to structured programming and datastructures; to illustrate the use of data structures and structured statements to write good and efficient code.

• To enable participants to understand and code string handling functions

• Sorting and Searching

• Project related discussion

Page 3: Programming Fundamentals - WordPress.com · software engineering which will enable you to construct logical, readable, efficient programs. Though the language C will be used as a

ER/CORP/CRS/LA06/003 3

Copyright © 2004, Infosys Technologies Ltd

ER/CORP/CRS/LA06/003 Version no: 2.0

3

Session Plan

• Introduction to Programming

• Functions

• Arrays and Strings

• Searching and Sorting

• Error handling

• File handling

Page 4: Programming Fundamentals - WordPress.com · software engineering which will enable you to construct logical, readable, efficient programs. Though the language C will be used as a

ER/CORP/CRS/LA06/003 4

Copyright © 2004, Infosys Technologies Ltd

ER/CORP/CRS/LA06/003 Version no: 2.0

4

Day 1

• Basic Programming concepts

• Algorithms

Day 2

• Functions

• Programming Specifications for the PF Project given

Day 3

• Arrays and Strings

The module focuses on how to approach a given problem statement. The main objective of the module is to make the participants algorithmically build solutions. The algorithm solutions will be converted to C programs and tested using the Visual studio editor.

This module is a 7-day long course. The first 4 days of the course will be covering the basic concepts of programming.A project , covering the concepts learnt in the 4days will be completed in the next 3 days .

Page 5: Programming Fundamentals - WordPress.com · software engineering which will enable you to construct logical, readable, efficient programs. Though the language C will be used as a

ER/CORP/CRS/LA06/003 5

Copyright © 2004, Infosys Technologies Ltd

ER/CORP/CRS/LA06/003 Version no: 2.0

5

Day 4• Searching and Sorting techniques

• File handling and Error handling techniques

Day 5• Comparing FDD with trainees documents

Day 7

• Coding and Code review

Day 6

• Online Exam Test

• Project Evaluation

The basic programming concepts taught in this module are applicable to all programming languages. The syntax and usage of them varies from one language to other language. The course is designed to introduce the fundamentals of computing as well as certain aspects of software engineering which will enable you to construct logical, readable, efficient programs.

Though the language C will be used as a base to implement the concepts learnt this course is definitely not about C programming.

The evaluation instruments used in this module are

2 quizzes (on day3 and day4 of the course)

1 module test (on the last day of the course)

1 project (on the last day of the course)

While the coding for the project starts from Day 4 of the course, it is necessary for us to ensure that proper testing and reviews of the code is done at frequent intervals.

Page 6: Programming Fundamentals - WordPress.com · software engineering which will enable you to construct logical, readable, efficient programs. Though the language C will be used as a

ER/CORP/CRS/LA06/003 6

Copyright © 2004, Infosys Technologies Ltd

ER/CORP/CRS/LA06/003 Version no: 2.0

6

References

• Let Us C, by Yashwant Kanitker, Second Edition• Programming in C, Schaum series, Third Edition

Page 7: Programming Fundamentals - WordPress.com · software engineering which will enable you to construct logical, readable, efficient programs. Though the language C will be used as a

ER/CORP/CRS/LA06/003 7

Copyright © 2004, Infosys Technologies Ltd

ER/CORP/CRS/LA06/003 Version no: 2.0

7

Day 1

• Software life cycle

• Programming Approach

• Programming Life Cycle

• Introduction to algorithms

• Basic constructs of C language

• Programming Style

Today’s session will focus on the need for programming and how to get started with programming.

Page 8: Programming Fundamentals - WordPress.com · software engineering which will enable you to construct logical, readable, efficient programs. Though the language C will be used as a

ER/CORP/CRS/LA06/003 8

Copyright © 2004, Infosys Technologies Ltd

ER/CORP/CRS/LA06/003 Version no: 2.0

8

What

How

D o it

T e s t

U s e

Software life cycle

REQUIREMENTS GATHERING, PROBLEM DEFINITION

ANALYSIS AND DESIGN

CODING

TESTING

IMPLEMENTATION AND MAINTENANCE

In the SDM session the various phases of the Software Life Cycle were discussed. Lets have a quick recap of the phases of SDLC (the waterfall model).

Any project starts with the Initiation phase in which the need for such a solution is identified. During this phase the software requirements are identified and scope for the project is freezed.After the requirements are collected from the client using a requirements specifications document, these are analyzed. The requirements after analysis are translated to define the actual structure of the project during the deign phase. The output of the design phase is ‘program specifications’ . Using these program specifications the actual programs are written. This is the coding phase. Once the project is built its tested for conformance to specifications. Test plans are prepared using the specifications and these are used during the testing phase. If the project is tested successful, its then installed. The installation phase may also involve some kind of user training in some cases. The final phase of the SDLC life cycle would be then maintenance of the project . During maintenance some more new requirements are identified and the cycle continue

Page 9: Programming Fundamentals - WordPress.com · software engineering which will enable you to construct logical, readable, efficient programs. Though the language C will be used as a

ER/CORP/CRS/LA06/003 9

Copyright © 2004, Infosys Technologies Ltd

ER/CORP/CRS/LA06/003 Version no: 2.0

9

Programming Approach

End User perspective– Sequential Approach (Demo Sequential_Demo)– Event Driven Approach (Demo EventDriven_Demo)

Programmer’s perspective– Structured Programming– Object Oriented Programming

Its during the coding phase of the SDLC life where one needs to write program using the specifications given. While writing programs there are lot of approaches used by the programmers.

From the programmers point of view the approaches can be classified into 2 types -structured programming and object oriented programming.

Structured programming is built on systematically breaking down the problem into modules The programs are organized into modules that are coded using independent functions and data. Eg. MSDOS programs

Object oriented programming style results in programs that are organized into objects that encapsulate functions and data. Eg. C++ / Java / Windows programming.

From the end users point of view the approaches can be classified into 2 types – Sequential and Event driven

Sequential programming results in programs that allow the user to follow a predefined sequence of events. For example if there is a structured program written to accept student info the sequence in which this input is prompted is fixed. Any user using the application has to necessarily enter the input in that sequence only. Eg. MSDOS programs. CUI applications

On the other hand , in event driven programming the user can control the flow of events and may choose the sequence of events. In such cases the UI is displayed to the user. User is then allowed to enter the input in the sequence which the user wants. The program waits for the user to send a message (by raising a event) which is processed and the program proceeds with execution.Eg. Windows/GUI programs

Page 10: Programming Fundamentals - WordPress.com · software engineering which will enable you to construct logical, readable, efficient programs. Though the language C will be used as a

ER/CORP/CRS/LA06/003 10

Copyright © 2004, Infosys Technologies Ltd

ER/CORP/CRS/LA06/003 Version no: 2.0

10

Algorithms

• What is an algorithm?

• Difference between a program & algorithm

• Definition of algorithm(broader look)

• Uses of Algorithms

Let us now look at the steps involved in writing a solution to solve a given problem.

Page 11: Programming Fundamentals - WordPress.com · software engineering which will enable you to construct logical, readable, efficient programs. Though the language C will be used as a

ER/CORP/CRS/LA06/003 11

Copyright © 2004, Infosys Technologies Ltd

ER/CORP/CRS/LA06/003 Version no: 2.0

11

Algorithms

• An Algorithm is a solution to a problem that is independent of any programming language.

An algorithm is just steps, written in plain English, that are needed to solve a given problem. The general form what an algorithm takes is

Step 1 : START

Step 2 : <….>

Step 3 : <…..>.

.

Step n : STOP

A flowchart on the other hand is a diagrammatic representation of an algorithm.

Page 12: Programming Fundamentals - WordPress.com · software engineering which will enable you to construct logical, readable, efficient programs. Though the language C will be used as a

ER/CORP/CRS/LA06/003 12

Copyright © 2004, Infosys Technologies Ltd

ER/CORP/CRS/LA06/003 Version no: 2.0

12

Algorithms & Programs

• An Algorithm is a solution to a problem that is independent of any programming language.

While

• A program is an algorithm expressed in a programming language.

Let us now take an example.

We will write an algorithm to find the average of three numbers. Read the problem statement and find out

-what is the input required to solve the problem ( 3 numbers in case of the example above)

-What is the processing needed on the input that will generate the desired output (the 3 numbers input are added and the total is divided by 3 to give us the average)

-What is the output (the result we get is average which is displayed back to the user)

Page 13: Programming Fundamentals - WordPress.com · software engineering which will enable you to construct logical, readable, efficient programs. Though the language C will be used as a

ER/CORP/CRS/LA06/003 13

Copyright © 2004, Infosys Technologies Ltd

ER/CORP/CRS/LA06/003 Version no: 2.0

13

Definition of Algorithm(broader look)

• An algorithm is – a finite sequence of steps– each step shall be explicit and unambiguous– for each input, it shall terminate in finite time with output

Now lets write the algorithm for the problem statements

We need to accept 3 numbers from the user, add them , divide by three, get the average and show that to the user.

So the steps would be

Step 1 : START

Step 2 : Accept 3 numbers say num1, num2,num3

Step 3 : Add num1 num2 num3 and store the result in sum

Step 4 : Divide sum by 3 and find the average

Step 5 : Display Average

Step 6 : STOP

In the above algorithm

num1,num2,num3,sum,average are variables which are used to store values. A variable can be defined as a location in memory that is capable of holding varying values. We have different categories of variables – Simple / Array / Pointer / Structure variables

Accept and Display statements are input and output statements

Page 14: Programming Fundamentals - WordPress.com · software engineering which will enable you to construct logical, readable, efficient programs. Though the language C will be used as a

ER/CORP/CRS/LA06/003 14

Copyright © 2004, Infosys Technologies Ltd

ER/CORP/CRS/LA06/003 Version no: 2.0

14

Use of algorithms• Facilitates easy development of programs

– Iterative refinement– Easy to convert it to a program

• Review is easier

Writing algorithms makes logical thinking easier since there is no specific syntax/rules for writing algorithms.Iterative refinement : This is stepwise refinement of the algorithm to get to the actual solution ex. Taking names,then marks, validating marks, finding average. Its easy to understand as its in plain English format.

Page 15: Programming Fundamentals - WordPress.com · software engineering which will enable you to construct logical, readable, efficient programs. Though the language C will be used as a

ER/CORP/CRS/LA06/003 15

Copyright © 2004, Infosys Technologies Ltd

ER/CORP/CRS/LA06/003 Version no: 2.0

15

Basic three programming algorithm concepts.

• Sequential

• Selectional

• Iterational

While building solutions there are three major constructs on which our solutions are built up. They are Sequential / Selectional (Conditional) / Iterational (loops) Lets look at some more examples which will use these type of constructs

Page 16: Programming Fundamentals - WordPress.com · software engineering which will enable you to construct logical, readable, efficient programs. Though the language C will be used as a

ER/CORP/CRS/LA06/003 16

Copyright © 2004, Infosys Technologies Ltd

ER/CORP/CRS/LA06/003 Version no: 2.0

16

Example (Sequential)

• Write an algorithm to find the average marks of a student given the marks he has obtained in three subjects.

Example 1. Write an algorithm to find the average marks of a student given the marks he has obtained in three subjects.

Input identified is marks in 3 subjects

Process is add the 3 marks and then divide

Output is the average marks

Step 1 : START

Step 2 : Accept num1,num2,num3

Step 3 : sum=num1+num2+num3

Step 4 : Avg=sum/3

Step 5 : display avg

Step 6 : STOP

The above set of algorithms clearly explains the usage of programming constructs like sequential An algorithm facilitates easy program developments of programs, An algorithm also known as pseudo code is independent of any programming language. It does not contain any syntactic details associated with a programming language. Since the algorithm only contains the logic of the solution without the implementation details it is a useful tool to review and trap logical errors in the solution. The truly creative part of programming is the design and development of correct and efficient algorithm. The coding phase can be viewed simply as the process of translating an algorithm into the syntax of the any particular language

Page 17: Programming Fundamentals - WordPress.com · software engineering which will enable you to construct logical, readable, efficient programs. Though the language C will be used as a

ER/CORP/CRS/LA06/003 17

Copyright © 2004, Infosys Technologies Ltd

ER/CORP/CRS/LA06/003 Version no: 2.0

17

Conversion of algorithm to C program

• Variables• Input statement• Assignment statement• Output statement

In our previous examples the

•Variables are num1, num2, num3

•Accept is the input statement

•Display is the output statement

Lets now get started with programming in C. C is a structured programming language. A C program consists of functions and data. C program consists of a predefined function main() along with zero or more user defined functions.

A simple hello world program

/* a simple hello world program */

#include <stdio.h>

main()

{

printf(“\n Hello World”); // displays hello world on the screen

}

The first line of the program is directive. Directives are executed during the preprocessor phase, a phase prior to compilation phase. The program begins its execution with the first instruction in the main function. The instruction is a print instruction that prints Hello World on the screen. printf() is a predefiend function of the std I/O library which is made available to your program by including it using a #include directive.

Other predefined function is scanf() for accepting input from the user during execution.

Each instruction in a C program terminates with a semicolon.

Comments are inserted in the program and more clarity and readability of the programs. They are enclosed between /*….*/ or proceeded by //.

Page 18: Programming Fundamentals - WordPress.com · software engineering which will enable you to construct logical, readable, efficient programs. Though the language C will be used as a

ER/CORP/CRS/LA06/003 18

Copyright © 2004, Infosys Technologies Ltd

ER/CORP/CRS/LA06/003 Version no: 2.0

18

Declaration of variables

Basic/Primitive data types supported by C are

• int• char• float

There are lot of other data types which are derived data types that are built on these primitive data types. Some worth a mention are

• long

• short

• double

Basic/Primitive data types supported by C are

int – for storing integer values. Size will vary from 2 bytes – 4 bytes

char – for storing character values – Size is 1 byte

Float – for storing decimal values – single precision values are stored where number of digits of precision after the decimal point is 6.

There are lot of other data types which are derived data types that are built on these primitive data types. Some worth a mention are

long – used to store long int

short – used to store short int

Double – used to store decimal values of 12-digit precision

Page 19: Programming Fundamentals - WordPress.com · software engineering which will enable you to construct logical, readable, efficient programs. Though the language C will be used as a

ER/CORP/CRS/LA06/003 19

Copyright © 2004, Infosys Technologies Ltd

ER/CORP/CRS/LA06/003 Version no: 2.0

19

Input statement

• Read from user (standard input)• scanf(“format”, .... )

– %d - for int – %l - for long

– %f - for double and float datatype– %c - for characters

The scanf statement is used for accepting user input. Some other std input functions available are

int getch() – defied in conio.h accepts a character

int getchar() – defined in stdio.h, accepts a character

int getc(FILE * fp) – reads a character from the file pointer specified (stdin in case input to read in from the keyboard the standard input file)

Eg. char a=getch(); reads a char

char a=getchar();reads a char

char a=getc(stdin); reads a char

A standard lib function used often in conjunction with scanf is the fflush(stdin); function. This function is responsible for clearing the input buffer before / after any input operation.

Page 20: Programming Fundamentals - WordPress.com · software engineering which will enable you to construct logical, readable, efficient programs. Though the language C will be used as a

ER/CORP/CRS/LA06/003 20

Copyright © 2004, Infosys Technologies Ltd

ER/CORP/CRS/LA06/003 Version no: 2.0

20

Output statement

• Write onto screen (standard output)• printf(“format_string”, .... )

– %d - for int

– %l - for long– %f - for double and float datatype

– %c - for characters

• Arguments are expressions

The printf statement is used for displaying user output. Some other std output functions available are

int getchar(int) – defined in stdio.h, accepts a character

int getc(int, FILE * fp) – writes a character in the file pointer specified (stdout in case output is written on the screen the standard output file)

Eg.. putchar(5); will print the character equivalent to the ASCII value 5.

putc(65,stdout) will print the character equivalen to the ASCII value 65 which is ‘A’

char a=‘*’; putcha(a) will print character * on the screen

char a=‘*’; putc(a,stdout) will print character * on the screen

Page 21: Programming Fundamentals - WordPress.com · software engineering which will enable you to construct logical, readable, efficient programs. Though the language C will be used as a

ER/CORP/CRS/LA06/003 21

Copyright © 2004, Infosys Technologies Ltd

ER/CORP/CRS/LA06/003 Version no: 2.0

21

Assignment statement

• Assign an expression to a variable• var = expr ;

Consider an example

int x,y; // this instruction delcares 2 integer variables. Indicating 2 memory locations are created that can store integer values. The locations contains no value currently (ie junk value)

x=5; // x is intialised to 5. This indicates the memory location x now stores value 5

Y=x; // x is assigned to 5. This indicates the value of memory location x is copied to the value in

memory location y

Page 22: Programming Fundamentals - WordPress.com · software engineering which will enable you to construct logical, readable, efficient programs. Though the language C will be used as a

ER/CORP/CRS/LA06/003 22

Copyright © 2004, Infosys Technologies Ltd

ER/CORP/CRS/LA06/003 Version no: 2.0

22

Operators In C

•Arithmetic Operators : + , - , * , /, %

•Relational Operators : >, >=, <, <=, == , !=

•Logical Operators : !, &&, ||

•Compound Assignment Operator : =, +=, -=, /=, *=, %=

•Address Operator : &

•Pre and Post Operator : ++, --

The basic arithmetic operators help us in performing the arithmetic operations.The % (modulo operator) is used to find the reminder of a divide operation

eg.int x=5,y=2;

int z=5/2; will store 2 in z

int z=5%2 will store 1 in z

% operator cannot be applied to float data type. Hence the instruction 5.2 % 2.5 will result in erro

For comparing if 2 values are equal for not remember to use == and not a single =. == indicates comparisons and = indicates assignment operation

eg. int x=5,y=3

x==y will be considered as an conditional expression that will be evaluated to true(non-zero) for false(zero)

x=y will be considered as an assignment expression which will assign 3 (value of y) to x. x after the instruction will have value 3.

Logical operators available are ! (NOT), && (AND), || (OR)

eg. consider 3 variables x,y,x containing values 1,2,3 respectively

x=1, y=2, z=3

the condition x==1 && y == 3 will evaluate to false

the condition x==1 && z==3 will evaluate to true

the condition x==1 || y==3 will evaluate to true

the condition x==1 || z==3 will evaluate to true

the condition !(x <2 && y==2) will evaluate to false

AND table followed for evaluation is : T && T~T, T && F~F, F && T~F, F && F~T

OR table followed for evaluation is : T || T~T, T || F~T, F || T~T, F || F~F

NOT table followed is : ! T~F,! F~T

Page 23: Programming Fundamentals - WordPress.com · software engineering which will enable you to construct logical, readable, efficient programs. Though the language C will be used as a

ER/CORP/CRS/LA06/003 23

Copyright © 2004, Infosys Technologies Ltd

ER/CORP/CRS/LA06/003 Version no: 2.0

23

Precedence will be in order of

•Arithemtic – highest precedence

•Relational – lower than arithmetic

•Logical – lower that relational

Operator Precedence and Associativity

C offers a large variety of compound assignment operators. These operators are designed to handle multiple operations using a single instruction

Pre and Post increment operations are used when add / subtract has to happen with before / after some other operation.

eg. int x=4;

int y=++x; // this is preincrement operation. The result will be increment the value of x by 1 and then assign the updated value to y. x after the instruction gets executed will contain 5 and y will have 5

ie x=x+1;

y=x

int y=x++; // this is post increment operation. The result will be assign the value to x to y then increment the value of x by by 1. x after the instruction gets executed will contain 5 and y will have 4

ie y=x;

x=x+1;

Consider below

int y= x++ + ++x; this expr would translate to : x=x+1; y=x+x; x=x+1

After the instruction gets executed x contains 6 and y contain 10

In evaluating expressions the order of precedence starting from highest one is

•Compound assignment operators (+,=,*,/ - in order of BODMAS)

•Logical operators,Relational operators,& Address operators,* Indirection operator,Post increment / decrement,Pre increment / decrement

Each of the operators set are evaluated with Left to right associativity except Pre incrementation / decrementation that’s evaluated with right to left associativity.

Page 24: Programming Fundamentals - WordPress.com · software engineering which will enable you to construct logical, readable, efficient programs. Though the language C will be used as a

ER/CORP/CRS/LA06/003 24

Copyright © 2004, Infosys Technologies Ltd

ER/CORP/CRS/LA06/003 Version no: 2.0

24

Finishing touches!

• Each C-program has a main function• Execution of a program starts from main()• include header files

– #include <stdio.h>

Having understood the basic C program structure lets convert our earlier algorithm into C Program.

Converting it to C Program

/* this program takes the marks as input, calculates average and prints the same */

#include <stdio.h> //including the std input output library

void main(void) //main is defined which does not take any parameters and returns no value.

{ //hence indicated as void

float fMark1, fMark2, fMark3,fSum,fAvg; //variable names need to follow naming conventions

scanf(“%f%f%f”,&fMark1,&fMark2,&fMark3); //use & while accepting

fSum=fMark1+fMark2+fMark3;

fAvg=fSum/3;

printf(“%f”,fAvg);

Page 25: Programming Fundamentals - WordPress.com · software engineering which will enable you to construct logical, readable, efficient programs. Though the language C will be used as a

ER/CORP/CRS/LA06/003 25

Copyright © 2004, Infosys Technologies Ltd

ER/CORP/CRS/LA06/003 Version no: 2.0

25

PreprocessorPreprocessor

CompilerCompiler

Object File Object File

LinkerLinker

Debug Version Debug Version

LibrariesLibrariesObject FilesObject Files

Source Source Header FilesHeader Files

EditorEditor

Release Version Release Version

Program Life Cycle

Now lets look at how do we test the program we have just written. The diagram above depicts the various phases involved in the program life cycle.

Editing Phase : The first step in the process of building a program is creating source code files with the code statements in header and source files. The code statements are entered into the files using a standard editor (Visual Studio in our case). Care must be taken to enter the code such that it is properly formatted and follows programming standards. Since a program is the most detailed design specifications it must be easily understandable.

Preprocessing and Compiling phase : When the compiler is invoked the preprocessor (which performs the preliminary operations on the source code before they are passed to the compiler) runs first to create the compiler input. The compiler then scans the entire source code for any syntax errors and creates an OBJ file that contains machine code linker directives, sections, external references , function and data generated from the source files.

If there are any syntax errors the code is edited and recompiled. It is a good practice to review the code once the code passes the compilation stage to locate logic errors and ensure conformance to standards

Linking phase : During linking the linker combines all of the object code from the statically linked libraries and other object files, resolves the named resource and creates and executable. The linker gives an error message if an external reference is not found. Library is a catalog of previously developed objects ie sources which are independently developed, compiled and tested.Certain libraries are supplied along with the compiler. These standard libraries contain functions for performing the basic input/output , arithmetic etc functions. Users can create their own libraries

Debugging phase : During testing of the programs debuggers are used to execute the program instruction by instruction display intermediate result set new values to variable etc. Debuggers speedup the testing process. After the program is linked the final executable could be a debug version / final version product

Page 26: Programming Fundamentals - WordPress.com · software engineering which will enable you to construct logical, readable, efficient programs. Though the language C will be used as a

ER/CORP/CRS/LA06/003 26

Copyright © 2004, Infosys Technologies Ltd

ER/CORP/CRS/LA06/003 Version no: 2.0

26

File test.c:#include <stdio.h>void main(void ){int iResult;scanf(“%d%d”, &a,&b);iResult = a + b;printf(“%d”, iResult);}

Life Cycle

Edit test.c

Compile test.oGives error as a and b are not declared

EXE not CREATED

An Example

Variables have to be declared before use. If not declared the compiler gives on error and does not create a object code for the program. Hence the exe which is created using the object code is also not created. The program uses ”+” operator on ‘a’ and ‘b’ where as ‘a’and ‘b’ are not declared anywhere. This will result in compile time error

Page 27: Programming Fundamentals - WordPress.com · software engineering which will enable you to construct logical, readable, efficient programs. Though the language C will be used as a

ER/CORP/CRS/LA06/003 27

Copyright © 2004, Infosys Technologies Ltd

ER/CORP/CRS/LA06/003 Version no: 2.0

27

File test.c:#include <stdio.h>void main(void){int iResult,iN1,iN2;scanf(“%d%d”, &iN1,iN2);iResult = diff (iN1,iN2);printf(“%d”, iResult);}

Life Cycle

Edit test.cCompile Error test.oLink No Exe created

EXE NOT CREATED

Another example

The program calls function ”diff” where as function “diff” is not declared /defined before the function invocation statement This will result in compile time error.

Page 28: Programming Fundamentals - WordPress.com · software engineering which will enable you to construct logical, readable, efficient programs. Though the language C will be used as a

ER/CORP/CRS/LA06/003 28

Copyright © 2004, Infosys Technologies Ltd

ER/CORP/CRS/LA06/003 Version no: 2.0

28

File test.c:#include <stdio.h>int sum(int a, int b);void main(void){int iResult,iN1,iN2;scanf(“%d%d”, &iN1,iN2);iResult = sum (iN1,iN2);printf(“%d”, iResult);}

Life Cycle

Edit test.cCompile test.oLink ERROR

EXE NOT CREATEDFunction definition for sum ismissing

Another example

The program compiles successfully and creates an object code. However during the linking phase all function references are resolved. When a reference to ‘sum ‘ function needs to be resolved it searches for the definition of the function. Because the function definition is not available the reference is ‘sum’ function does not get resolved. This results in a linker error and the exe does not get created. The program calls function ”sum” where as function “sum”is not defined anywhere. This will result in linker time error.

Page 29: Programming Fundamentals - WordPress.com · software engineering which will enable you to construct logical, readable, efficient programs. Though the language C will be used as a

ER/CORP/CRS/LA06/003 29

Copyright © 2004, Infosys Technologies Ltd

ER/CORP/CRS/LA06/003 Version no: 2.0

29

One more example

// Prg to find out the cube of a number#include <stdio.h>main(){

int iNum;printf("Enter a number");scanf("%d",&iNum);fflush(stdin);printf(“\n Cube of the number is %d",iNum*iNum);

}

The above program when complied and linked gives no compilation (syntactic) / linking errors. But when executed it gives us the wrong output. These errors are logical errors

\n used in the program in a white space character which indicates return key. Other white space characters available are \t (tab), space,\0 (null terminator), \r,\”,\b,\f,\a. They are also called as escape sequence characters.

Page 30: Programming Fundamentals - WordPress.com · software engineering which will enable you to construct logical, readable, efficient programs. Though the language C will be used as a

ER/CORP/CRS/LA06/003 30

Copyright © 2004, Infosys Technologies Ltd

ER/CORP/CRS/LA06/003 Version no: 2.0

30

Libraries

Given a set of files (say .c files) we can build an executable or a library.A Library is a collection of object modules whichget linked to the object modules of the program atCompile time (Static Linked Library)Run time (Dynamically Linked Library)• Why do we need Libraries ?• Can we have user defined Libraries ?

The stdio.h basically includes the standard input/output library in our application. And during the linker stage this is linked to our object code and the exe is created. Since the linking is during exe creation stage the library is a static linked library. There could be libraries which get linked while the program is under execution. Such libraries are dynamic linked libraries

Adv of Static Linked LibraryDisAdv. of Static Linked Library

Faster access to the functions defined in the library Resulting EXE is big in size

Adv of Dynamic Linked LibraryDisAdv. of Dynamic Linked Library

Slower access to the functions defined in the library Resulting EXE is small in size

It is possible for us to create user defined libraries and include them within our program through user defined header files. By default all standard header files are available under the include directory. Enclosing the header file name in angular brackets signifies that the file is available under include directory. When we create user defined libraries the header files corresponding to it are created in our current working directory. These header file names are included by enclosing them in double quotes.

A #include statement can be used to include any file content and not necessarily a header file.

Page 31: Programming Fundamentals - WordPress.com · software engineering which will enable you to construct logical, readable, efficient programs. Though the language C will be used as a

ER/CORP/CRS/LA06/003 31

Copyright © 2004, Infosys Technologies Ltd

ER/CORP/CRS/LA06/003 Version no: 2.0

31

Library Vs Executable files

LIBRARY

• Just an Archive (collection) of object modules

• No main ( )

EXECUTABLE

• Object modules are linked to form an exe

• main( ) is present(Only One Main)

Libraries are basically reusable pieces of code which needs to be linked to every executable that makes use of its functionality. This linking can be static / dynamic in nature. As discussed static linking of libraries mean the libraries are linked to your code before exe gets created whereas a dynamic linking of libraries mean the libraries are linked to your code while the code is under execution. Dynamic link libraries link to your code on demand when your code tries to refer to a function that is part of dynamic link library (DLL).

Page 32: Programming Fundamentals - WordPress.com · software engineering which will enable you to construct logical, readable, efficient programs. Though the language C will be used as a

ER/CORP/CRS/LA06/003 32

Copyright © 2004, Infosys Technologies Ltd

ER/CORP/CRS/LA06/003 Version no: 2.0

32

Assignment

• Write a program which reads the marks of a student in 3 subjects and finds the standard deviation of the marks

Page 33: Programming Fundamentals - WordPress.com · software engineering which will enable you to construct logical, readable, efficient programs. Though the language C will be used as a

ER/CORP/CRS/LA06/003 33

Copyright © 2004, Infosys Technologies Ltd

ER/CORP/CRS/LA06/003 Version no: 2.0

33

Example (Selectional)

• Write a program to find the average marks of a student given the marks he has obtained in three subjects. Then test whether he has passed or failed.

• For a student to pass, average should not be less than 50.

We have earlier written a program to find out the average marks of a student given marks in 3 subjects. Let us now extend the scope of the problem to find out whether is has passed our failed. Now this introduces us to a next construct – the selectional construct

Step 1 : START

Step 2 : Accept num1,num2,num3

Step 3 : sum=num1+num2+num3

Step 4 : avg=sum/3

Step 5 : if avg > 50 then display the student has passed else display the student has failed.

Step 6 : STOP

Page 34: Programming Fundamentals - WordPress.com · software engineering which will enable you to construct logical, readable, efficient programs. Though the language C will be used as a

ER/CORP/CRS/LA06/003 34

Copyright © 2004, Infosys Technologies Ltd

ER/CORP/CRS/LA06/003 Version no: 2.0

34

Conditional statement

• Used for deciding on which action to take

if (expr)stmt1;

if (expr)stmt1;

elsestmt2;

if (expr)stmt1;

else if (expr)stmt2;

The if statement controls conditional branching The body of an if statement is executed if the value of the expression is nonzero.

Stmt1 is executed if the condition evaluates to true , else Stmt2 is executed.Note that semicolon is placed at the end of Stmnt forming the if and else clauses. If the number of statements to be executed is more than one then the statements need to be enclosed in a block

ie if (expr)

{

Stmnt1; Stmnt2;Stmnt3;

}

For each else there needs to be a matching if. The compiler resolves this by associating each else with the closed if that lacks else. If constructs can also be nested,

Some examples :-

int iN1,iN2,iN3 ,iN =0;

iN1=1,iN2y=2,iN3=3;

1) if(iN > iN2)

printf(“iN1 is larger”);

else

printf(“iN2 is larger”);

2) if(iN1 > iN2)

printf(“iN1 is larger”);

else if(iN1 < iN2)

printf(“iN2 is larger”);

else

printf(“Both iN1 and iN2 are equal”);

3) if(iN==1) // prints iN is not one

printf(“iN is one”);

else

printf(“iN is not one”);

Page 35: Programming Fundamentals - WordPress.com · software engineering which will enable you to construct logical, readable, efficient programs. Though the language C will be used as a

ER/CORP/CRS/LA06/003 35

Copyright © 2004, Infosys Technologies Ltd

ER/CORP/CRS/LA06/003 Version no: 2.0

35

Conditional statement-(Contd..)

• Please refer to Notes page for more explanation on previous slide

4) if(iN=1) // prints iN1 is one

printf(“iN is one”);else

printf(“iN1 is not-one”);In the above example the expr that’s evaluated is an assignment expr and not a conditional expr. (becoz of = and not ==). The expr will assign a non-zero value to iN and then iN is evaluated. Since it contains a non-zero value (indicating true evaluation) the if part is executed5) if(iN1=0) // prints iN1 is non-zero

printf(“iN1 is zero”);else

printf(“iN1 is non-zero”);In the above example the expr that’s evaluated is an assignment expr and not a conditional expr. (becoz of = and not ==). The expr will assign a zero value to iN1 and then iN1 is evaluated. Since it contains a zero value (indicating false evaluation) the else part is executed6) if(5) //prints true.

printf(“True’); //becoz expr evaluates to a non-zero value.

else printf(“false”);

Page 36: Programming Fundamentals - WordPress.com · software engineering which will enable you to construct logical, readable, efficient programs. Though the language C will be used as a

ER/CORP/CRS/LA06/003 36

Copyright © 2004, Infosys Technologies Ltd

ER/CORP/CRS/LA06/003 Version no: 2.0

36

Conditional statement-(Contd..)

• Please refer to Notes page for more explanation on previous slide

7) if(0) //prints falseprintf(“True”); // becoz the expr evaluates to zero value

elseprintf(“False”);

8) if(iN==3); //gives a compilation as if terminates after expr.printf(“true”); // this means there is no matching if for the

else belowelse // hence a error at compilation time is

reportedprintf(“false”);

9) if(iN1==1 && iN2 <3) //prints true as the expr evaluates to true – T && Tprintf(“True”);else

printf(“false”);10) if(!4) // not of a non zero value is zero hence false is printed

printf(“true”);elseprintf(“false”);

Page 37: Programming Fundamentals - WordPress.com · software engineering which will enable you to construct logical, readable, efficient programs. Though the language C will be used as a

ER/CORP/CRS/LA06/003 37

Copyright © 2004, Infosys Technologies Ltd

ER/CORP/CRS/LA06/003 Version no: 2.0

37

Alternative conditional statements

• ? : operator < (cond.)?true:false >

• switch block

switch (expr){case value1: stmt1; stmt2; break;case value2 :stmt1; stmt2; break;

default : stmt1;break}

The ternary operator is used as a replacement to simple if conditions.

Example :-

iMax = (iN1 > iN2) ? iN1 : iN2;

Here the condition evaluated is iN1 > iN2. If it evaluates to true then iN1 is assigned to iMaxelse iN2 is assigned to iMax.

The switch block is used as an alternative to if construct when the value in a variable needs to be matched against a set to values. The expr needs to be of int / char type only. All case values need to be unique. The switch-case help control complex conditional and branching operations. The expr value is matched against all case values. If a match is found the case block executes and the control comes out of the switch (becoz of a break). In absence of a break statement the execution continues with the next case block till it encounters a break / the switch block terminates (which ever is earlier).If expr does not match with any of the listed case values then the default block executes. The default is an optional statement and it need not come at the end; it can appear anywhere in the body of the switch statement. In fact it is often more efficient if it appears at the beginning of the switch statement.

This is one of the code tuning technique in which we place cases according to the frequency which they occur in . i.e if we know that the user is going to give the options that is invalid most of the times we can place the default as the first case so that the first case statement is satisfied and executed , instead of checking all the cases and then executing the default.

According to ANSI at least 257 case labels are allowed in a switch statement.

Page 38: Programming Fundamentals - WordPress.com · software engineering which will enable you to construct logical, readable, efficient programs. Though the language C will be used as a

ER/CORP/CRS/LA06/003 38

Algorithm to find if a year is a leap year

Step 1 : START

Step 2 : Accept year

Step 3 : if year % 4 ==0 then print year is leap else print year is not leap

Step 4 : STOP

Algorithm to find the largest of 3 numbers

Step 1 : START

Step 2 : Accept num1,num2,num3

Step 3 : if num1 is > num2 and num1 is > num3 then display num1 is largest

Step 4 : if num2 is > num1 and num1 is > num3 then display num2 is largest

Step 5 : if num3 is > num1 and num1 is > num2 then display num3 is largest

Step 6 : STOP

Copyright © 2004, Infosys Technologies Ltd

ER/CORP/CRS/LA06/003 Version no: 2.0

38

Assignment

• Write an algorithm to find whether a given year is a leap year or not.• Write an algorithm to find the largest of 3 numbers

Page 39: Programming Fundamentals - WordPress.com · software engineering which will enable you to construct logical, readable, efficient programs. Though the language C will be used as a

ER/CORP/CRS/LA06/003 39

Copyright © 2004, Infosys Technologies Ltd

ER/CORP/CRS/LA06/003 Version no: 2.0

39

Example (Iterational)

• Do the following for N input values. Read N from user� Write an algorithm to find whether a given year is a leap year or not.� Write an algorithm to find the largest of N numbers� Write a program to find the average of a student given the marks he

obtained in three subjects. Then test whether he passed or failed. For a student to pass, average should not be less than 50.

Now lets extend the scope of our algorithms. The problem definition now needs to give us solution for a set of input values. This introduces to us the the concepts of looping constructs

Algorithm 1

Step 1 : START

Step 2 : Read N

Step 3 : ctr=1

Step 4 :-Accept year

Step 4 : if year % 4 ==0 then print year is leap else print year is not leap

Step 5 : ctr=ctr+1

Step 6 : if ctr < N goto step 4

Step 7 : STOP

Page 40: Programming Fundamentals - WordPress.com · software engineering which will enable you to construct logical, readable, efficient programs. Though the language C will be used as a

ER/CORP/CRS/LA06/003 40

Copyright © 2004, Infosys Technologies Ltd

ER/CORP/CRS/LA06/003 Version no: 2.0

40

Example (Iterational)- (Contd…)

• Please refer to Notes page for more explanation on previous slide

Algorithm 2

Step 1 : START

Step 2 : Read N

Step 3 : ctr=1

Step 4 : read num

Step 5 : max =num

Step 6 : read num

Step 7 : if (max < num) max =num

Step 8: ctr=ctr+1

Step 9 : if (ctr <=N) goto step 6

Step 10 : display max

Step 11 : STOP

Algorithm 3

Step 1 : START

Step 2 : Read N

Step 3 : ctr=1

Step 4 : Accept num1,num2,num3

Step 5 : sum=num1+num2+num3

Step 6 : Avg=sum/3

Step 7 : display avg

Step 8: ctr=ctr+1

Step 9 : if (ctr <=N) goto step 4

Step 10 : STOP

Page 41: Programming Fundamentals - WordPress.com · software engineering which will enable you to construct logical, readable, efficient programs. Though the language C will be used as a

ER/CORP/CRS/LA06/003 41

Copyright © 2004, Infosys Technologies Ltd

ER/CORP/CRS/LA06/003 Version no: 2.0

41

Looping statements

• Repeat an action specified number of times

for(expr1; expr2; expr3)stmt;

The for statement lets you repeat a statement or compound statement a specified number of times. The body of a for statement is executed zero or more times until an optional condition becomes false. You can use optional expressions within the for statement to initialize and change values during the for statement’s execution.

Execution of a for statement proceeds as follows:

1. The initial-expression, if any, is evaluated. This specifies the initialization for the loop. There is no restriction on the type of initial-expression.

2. The conditional-expression, if any, is evaluated. This expression must have arithmetic or pointer type. It is evaluated before each iteration. Three results are possible:

· If conditional-expression is true (nonzero), statement is executed; then looping-expression, if any, is evaluated. The looping-expression is evaluated after each iteration. There is no restriction on its type. The process then begins again with the evaluation of conditional-expression.· If conditional-expression is omitted, conditional-expression is considered true, and execution proceeds exactly as described in the previous paragraph. A for statement without a conditional- expression argument terminates only when a break or return statement within the statement body is executed, or when a goto (to a labeled statement outside the for statement body) is executed.

· If conditional-expression is false (0), execution of the for statement terminates and control passes to the next statement in the program.

A continue statement in a for loop causes looping-expression to be evaluated.

for( ;; ); - creates an infinite loop

Page 42: Programming Fundamentals - WordPress.com · software engineering which will enable you to construct logical, readable, efficient programs. Though the language C will be used as a

ER/CORP/CRS/LA06/003 42

Copyright © 2004, Infosys Technologies Ltd

ER/CORP/CRS/LA06/003 Version no: 2.0

42

Looping statements - (Contd…)

• Please refer to Notes page for more explanation on previous slide

The following example illustrates the for statement:

for ( i = 1; i < N; i = i + 1 )

{

sum = sum + i;

}

This example calculates the sum of the first N –1 natural numbers. First i is initialized to 1. Then i is compared with the constant N; if i is less than N, the statement body is executed. Then i is incremented and tested against N; the statement body is executed repeatedly as long as i is less than N.

Note: One operator comma “ , ” is often used in the for statement. In a for statement, a pair of expressions separated by a comma is evaluated left to right and the type and value of the result are the type and value of the right operand.

Page 43: Programming Fundamentals - WordPress.com · software engineering which will enable you to construct logical, readable, efficient programs. Though the language C will be used as a

ER/CORP/CRS/LA06/003 43

Copyright © 2004, Infosys Technologies Ltd

ER/CORP/CRS/LA06/003 Version no: 2.0

43

Looping statements - (Contd…)

• Please refer to Notes page for more explanation on previous slide

The program converted for our algo 2 in as under.

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

int iMark1;int iMark2;int iMark3;int iCounter;int iEmpNo;int iNumber;

float fAverage;

printf (“Enter the number of students “);scanf (“%d”, &iNumber);for ( iCounter=1; iCounter<=iNumber; iCounter++){

printf (“Enter the Empno, Mark1, Mark2 and Mark3”);scanf (“%d %d %d %d”, &iEmpNo,&iMark1, &iMark2, &iMark3);fAverage = ( iMark1 + iMark2 + iMark3 ) / 3.0;

if (fAverage >= 50 ) printf (“Employee Number %d has passed”, iEmpNo);

elseprintf (“Employee Number %d has failed”, iEmpNo);

}}

Page 44: Programming Fundamentals - WordPress.com · software engineering which will enable you to construct logical, readable, efficient programs. Though the language C will be used as a

ER/CORP/CRS/LA06/003 44

Copyright © 2004, Infosys Technologies Ltd

ER/CORP/CRS/LA06/003 Version no: 2.0

44

Looping statements

• repeat an action until an unknown number of times

while (expr)stmt;

The while statement lets you repeat a statement until a specified expression becomes false.

The expression must have arithmetic or pointer type. Execution proceeds as follows:

1. The expression is evaluated.

2. If expression is initially false, the body of the while statement is never executed, and control passes from the while statement to the next statement in the program.

3. If expression is true (nonzero), the body of the statement is executed and the process is repeated beginning at step 1.

The while statement can also terminate when a break, goto, or return within the statement body is executed. Use the continue statement to terminate an iteration without exiting the while loop. The continue statement passes control to the next iteration of the while statement. The following is an example of the while statement:

while ( i >= 0 )

{

sum = sum + i;

i = i –1;

}

This example adds the value of i to sum if i is greater than or equal to 0 and then decrements i. When i reaches or falls below 0, execution of the while statement terminates.The above example 1.4 can also be written using the while loop.

while(2) - creates a infinite loop

{

}

while (true) - creates a infinite loop

{

}

while(expr); - create a infinite loop

{

}

Page 45: Programming Fundamentals - WordPress.com · software engineering which will enable you to construct logical, readable, efficient programs. Though the language C will be used as a

ER/CORP/CRS/LA06/003 45

Copyright © 2004, Infosys Technologies Ltd

ER/CORP/CRS/LA06/003 Version no: 2.0

45

Assignment

• Do the following for an unknown number of students• Write a program to find the average of a student given the marks he obtained

in three subjects. Then test whether he passed or failed. • For a student to pass, average should not be less than 50.

#include <stdio.h>

void main (void)

{

int iMark1,iMark2, iMark3;

int iCounter, iNumber, iEmpNo;

float fAverage;

char cCh;

while (true)

{

printf (“Enter the Empno, Mark1, Mark2 and Mark3”);

scanf (“%d %d %d %d”, &iEmpNo,&iMark1, &iMark2, &iMark3);

fAverage = ( iMark1 + iMark2 + iMark3 ) / 3.0;

if (fAverage >= 50 )

printf (“Employee Number %d has passed”, iEmpNo);

else

printf (“Employee Number %d has failed”, iEmpNo);

printf(“Do you wish to continue ? (y/n)”);

scanf(“%c”,&cCh);

fflush(stdin);

if(cCh==‘y’) continue; else break;

}

}

Page 46: Programming Fundamentals - WordPress.com · software engineering which will enable you to construct logical, readable, efficient programs. Though the language C will be used as a

ER/CORP/CRS/LA06/003 46

Copyright © 2004, Infosys Technologies Ltd

ER/CORP/CRS/LA06/003 Version no: 2.0

46

Other looping statements

do {stmts;

} while (expr);

The do-while statement lets you repeat a statement or compound statement until a specified expression becomes false.

Syntax

iteration-statement :

do

statement

while ( expression ) ;

The condition is evaluated after body of the loop is executed. Hence body of the loop executes at least if the condition is true /false

Execution proceeds as follows:

First the loop is executed, next the condition is evaluated, if condition evaluates to true the loop continues execution else control passes to the next statement following the loop

The do-while statement can also terminate when a break, goto, or return statement is executed within the statement body. This is an example of the do-while statement:

do

{ a = b ; b = b – 1; } while ( b > 0 );

In this do-while statement, the two statements a = b; and b = b - 1; are executed, regardless of the initial value of b. Then b > 0 is evaluated. If b is greater than 0, the statement body is executed again and b > 0 is reevaluated. The statement body is executed repeatedly as long as b remains greater than 0. Execution of the do-while statement terminates when b becomes 0 or –ve. The body of the loop is executed at least once.

Page 47: Programming Fundamentals - WordPress.com · software engineering which will enable you to construct logical, readable, efficient programs. Though the language C will be used as a

ER/CORP/CRS/LA06/003 47

Copyright © 2004, Infosys Technologies Ltd

ER/CORP/CRS/LA06/003 Version no: 2.0

47

for & while loops

Givenfor (expr1; expr2; expr3)

stmt;for(iSum=iCtr=0;iCtr<10;iCtr=iCtr+1){scanf(“%d”,&iNum);fflsuh(stdin);iSum=iSum+iNum;}printf(“%d”,iSum);

Rewrite it using while statementiSum=iCtr=0;while(iCtr<10){scanf(“%d”,&iNum);iSum=iSum+iNum;iCtr=iCtr+1;}printf(”%d”,iSum);

Consider the for loop to find accept 10 numbers, find their sum and print the result. Now lets convert the same to a while loop

The 1st component of the loop is initialization, 2nd component is condition and 3rd is increment. Considering this lets convert into a while loop

Page 48: Programming Fundamentals - WordPress.com · software engineering which will enable you to construct logical, readable, efficient programs. Though the language C will be used as a

ER/CORP/CRS/LA06/003 48

Copyright © 2004, Infosys Technologies Ltd

ER/CORP/CRS/LA06/003 Version no: 2.0

48

while & for loops

• Givenwhile (expr)

stmt;iCtr=10;while(iCtr>0){printf(“%d”,iCtr);iCtr=iCtr-1;}

• Rewrite it using for statement

The while loop will print numbers for 10 to 1 in the reverse order. Try writing the same using a for loop and test your solution.

We arrive at a conclusion that all while loops could be converted to for loop and the vise versa.

Page 49: Programming Fundamentals - WordPress.com · software engineering which will enable you to construct logical, readable, efficient programs. Though the language C will be used as a

ER/CORP/CRS/LA06/003 49

Copyright © 2004, Infosys Technologies Ltd

ER/CORP/CRS/LA06/003 Version no: 2.0

49

Programming Style

• Proper Naming • Commenting• Indenting• Standards

• Distribute» Good Code Text» Bad Code Text

When your program is submitted to a C compiler, style makes little difference. The comments, the well-chosen names, and the careful alignment of the code have no effect on the ultimate execution of the program. So why bother?

The effort you put into achieving good style in your program is clearly for the human element, and the most important person who is going to read your code is you. A program written with good style is more likely to be correct than one without and it will be easier for you to debug and modify as you move it to its final form.

That last point is worth noting. When you develop software in the real world, and even for this course, it is rarely the case that you write the entire program in one attempt. It is far more likely that you will get the essential "core" of the program running, then add the remaining features. Large problems are simply too complex to tackle any other way.

The result of this approach is that you will spend some time looking at your own code, asking questions like "What was I trying to do at this particular point," or "Where is the best place to add a new feature?" It is at this point that you will realize the value of an investment in good code.

Here is a simple example. Which of the following lines of code would you rather work on?

m = s * h;

distance = rate * time;

The first line gives no hint as to its meaning. If you are lucky, you remember what quantities the variables hold. If you don't, or if someone else wrote the code, you will have to spend some time figuring out what is going on. The second line holds no such mysteries.

Page 50: Programming Fundamentals - WordPress.com · software engineering which will enable you to construct logical, readable, efficient programs. Though the language C will be used as a

ER/CORP/CRS/LA06/003 50

Copyright © 2004, Infosys Technologies Ltd

ER/CORP/CRS/LA06/003 Version no: 2.0

50

Programming Style - (Contd…)

• Please refer to Notes page for more explanation on previous slide

Now consider the following attempt to determine a commission based on sales:

if (salesAmt <= 50.0) commission = 0.0;

if (salesAmt > 50.0) if (salesAmt <= 100.0)

commission = 0.02 * salesAmt;

if (salesAmt > 100.0) commission = 0.03 * salesAmt;

Though it produces the correct answer, the code above is not nearly as easy to understand or modify as the following equivalent version:

if (salesAmt <= 50.0)

{

commission = 0.0;

}

else if (salesAmt <= 100.0)

{

commission = 0.02 * salesAmt;

}

else

{

commission = 0.03 * salesAmt;

}

Just these two examples should make the point. Writing with clarity is as important for software as it is for literature.

Page 51: Programming Fundamentals - WordPress.com · software engineering which will enable you to construct logical, readable, efficient programs. Though the language C will be used as a

ER/CORP/CRS/LA06/003 51

Copyright © 2004, Infosys Technologies Ltd

ER/CORP/CRS/LA06/003 Version no: 2.0

51

Programming Style-(Contd…)

• Please refer to Notes page for more explanation on previous slide

Choosing NamesThe first step in documenting code is choosing meaningful names for things. For variables names the question is "What is it?" For functions, the question is "What does it do?" A well named variable or function helps document all the code where it appears. You should not have much difficulty deciding whether your names contribute to readability. Here are a few guidelines:

- Use lower/upper case EmpSalary- Use nouns for variables EmpNumber- Use verbs for functions PrintPayroll- Use uppercase for constants #define MAX_VALUE 100- Use moderate length

numberOfPeopleOnTeam too longntm too shortnumTeamMembers about right- Follow the standard (See Appendix –I)

Examples of good variable names include:iEmpNumbercCourseCodeiAssignmentmarkscCourseGrade

Examples of good function names include:GetEmpGradeSheet()EnterEmpAttendance()ModifyEmpDetails()CreateNewEmployee()In a nutshell, the name should be meaningful to the reader.

Page 52: Programming Fundamentals - WordPress.com · software engineering which will enable you to construct logical, readable, efficient programs. Though the language C will be used as a

ER/CORP/CRS/LA06/003 52

Copyright © 2004, Infosys Technologies Ltd

ER/CORP/CRS/LA06/003 Version no: 2.0

52

Programming Style-(Contd…)

• Please refer to Notes page for more explanation on previous slide

There are a few variable naming idioms that are so prevalent among programmers that they form theirown exception class:i, j, k Integer loop counters.n, len, Length or Integer number of elements in some sort of aggregationx, y Cartesian coordinates. May be integer or real.head, current, tail Pointers used to iterate over lists.The uses of the above are so common, that the apparent lack of content is acceptable.Using comments effectively

The motivation for commenting comes from the fact that a program is not just compiled and executed by the computer but is also read by people. A program must strive to be readable, and not just to the programmer who wrote it. A program expresses an algorithm to the computer. A program is clear or "readable" if it also does a good job of communicating the algorithm to a human. Given that C is a rather cryptic means of communication, an English description is often needed to understand what a program is trying to accomplish or how it was designed. Comments can provide information that is difficult or impossible to get from reading the code. Some examples of information you might find in comments:- General overview. What are the goals and requirements of this program? This function?- Data structures. How is data is stored? How is it ordered, searched, accessed?- Design decisions. Why was a particular data structure or algorithm chosen? Were other strategies tried and rejected?- Error handling. How are error conditions handled? What assumptions are made? What happens if those assumptions are violated?- Nitty-gritty code details. Comments are invaluable for explaining the inner workings of particularly complicated (often labeled "clever") paths of the code.- Planning for future. How might one make modifications or extensions later?- And much more... (This list is by no means exhaustive)

At the top of each file, it is a good convention to begin with an overview comment for the program, interface, or implementation contained in the file. The overview is the single most important comment in a program. It's the first thing that anyone reading your code will read. The overview comment explains, in general terms, what strategy the program uses to produce its output. The program header should lay out a roadmap of how the algorithm works— pointing out the important routines and discussing the data structures.

Page 53: Programming Fundamentals - WordPress.com · software engineering which will enable you to construct logical, readable, efficient programs. Though the language C will be used as a

ER/CORP/CRS/LA06/003 53

Copyright © 2004, Infosys Technologies Ltd

ER/CORP/CRS/LA06/003 Version no: 2.0

53

Programming Style-(Contd…)

• Please refer to Notes page for more explanation on previous slide

Here are a few guidelines for comments:- Comments should make the code accessible to the reader- Explain the code's intent in the heading- Keep the comments up to date (if you update the code, update the comment)- Don't comment bad code--fix it- Avoid useless comments

ConstantsAvoid embedding magic numbers and string literals into the body of your code. Instead you should #define a symbolic name to represent the value. This improves the readability of the code and provides for localized editing. You only need change the value in one place and all uses will refer to the newly updated value.

#define-d constants should be independent; that is, you should only need to change one #define to change something about a program. For example,

#define RECT_WIDTH 3#define RECT_HEIGHT 2#define RECT_PERIMETER 10 /*WARNING: problem */

is not so hot, because if you wanted to change RectWidth or RectHeight, you would also have to remember to change RectPerimeter. A better way is:

#define RECT_WIDTH 3#define RECT_HEIGHT 2#define RECT_PERIMETER (2 * RECT_WIDTH + 2 * RECT_HEIGHT)

Remember that you must always enclose your #define values in parentheses when they are not simple integer constants to guarantee that the compiler interprets the value properly.

Page 54: Programming Fundamentals - WordPress.com · software engineering which will enable you to construct logical, readable, efficient programs. Though the language C will be used as a

ER/CORP/CRS/LA06/003 54

Copyright © 2004, Infosys Technologies Ltd

ER/CORP/CRS/LA06/003 Version no: 2.0

54

Programming Style-(Contd…)

• Please refer to Notes page for more explanation on previous slide

Formatting One final point about style is that you should develop a consistent approach. Doing so improves readability and adds information to the code. For example, if you always use all caps and underscores for constants, then when you see a line like this:

ChoosePlayers(MAX_TEAM_SIZE);

you know right away that MAX_TEAM_SIZE is a constant and that it is defined somewhere in a #define statement. If sometimes your constants use mixed case, and sometimes your variables are all caps, then you can't tell for sure and you've lost one small chance to make your code more understandable.

One convention you will have to decide on is the placement of braces. Choose the convention that you believe does this best and be consistent.

You should take care in the formatting and layout of your programs. The font should be large enough to be easily readable. Use white space to separate functions from one another. Properly indent the body of loops, if, and switch statements in order to emphasize the nested structure of the code.

Likewise, for capitalization schemes, choose a strategy and stick with it. In this course we will typically capitalize each word in the name of a function, variables will be named beginning with a prefix confirming to its data type, #define constants will be completely uppercased, etc. . This allows a reader to determine more quickly which category a given identifier belongs to.

Page 55: Programming Fundamentals - WordPress.com · software engineering which will enable you to construct logical, readable, efficient programs. Though the language C will be used as a

ER/CORP/CRS/LA06/003 55

Copyright © 2004, Infosys Technologies Ltd

ER/CORP/CRS/LA06/003 Version no: 2.0

55

Summary

• Software Life Cycle• Programming Approach• Algorithms• Program life cycle• Basic constructs

– input, output – assignment statements– conditional statements– looping statements

• Programming Styles

Page 56: Programming Fundamentals - WordPress.com · software engineering which will enable you to construct logical, readable, efficient programs. Though the language C will be used as a

ER/CORP/CRS/LA06/003 56

Copyright © 2004, Infosys Technologies Ltd

ER/CORP/CRS/LA06/003 Version no: 2.0

56

Thank You!