Programming Techniques_PG(New 2009) (1)

202
Day 1 Day 2 Day 3 Day 4 Day 5 9:00 - 9:15 Morning Review Morning Review Morning Review 9:15 - 9:30 9:30 - 9:45 9:45 - 10:00 10:00 - 10:15 10:15 - 10:30 10:30 -10:45 10:45 - 11:00 11:00 - 11:15 11:15 - 11:30 11:30 - 11:45 11:45 - 12:00 12:00 - 12:15 12:15 - 12:30 12:30 - 12:45 12:45 - 1:00 1:00 -2:00 LUNCH LUNCH LUNCH LUNCH LUNCH 2:00 - 2:15 2:15 - 2:30 2:30 - 2:45 2:45 - 3:00 3:00 - 3:15 3:15 - 3:30 3:30 - 3:45 3:45 - 4:00 4:00 - 4:15 4:15 - 4:30 4:30 - 4:45 4:45 - 5:00 5:00 - 5:15 Day 5 Summary 5:15 - 5:30 5:30 - 5:45 5:45 - 6:00 Day 1 Summary Day 2 Summary Day 3 Summary Day 4 Summary Programming Techniques Course Map Design and documentation of Case study 2 Review and Feed back of Case study 1 & 2 Sr Manager talk with ASEs Coding, Testing & Documentation of Case study 1. Coding, Testing & Documentation of Case study 2 Module 2.1:Fundamental Programming Concepts Module1:Course Introduction Module 2.2:Programming Life Cycle Module3.1:Introdu ction to C (basic constructs, Keywords, literals, Module 4.2:Pointers Module 4.3:Memory Management Module 4.5:Coding Conventions Module 4.1:Introduction to Arrays Design and Documentation of Case study 1 Module 3.1(contd..): Declaring and defining variables,control structures,Best Practices) Module 3.2:Functions Module 4.4:Introduction to Structures Module 5:Searcing and Sorting

Transcript of Programming Techniques_PG(New 2009) (1)

Page 1: Programming Techniques_PG(New 2009) (1)

Day 1 Day 2 Day 3 Day 4 Day 5

9:00 - 9:15 Morning Review Morning Review Morning Review

9:15 - 9:309:30 - 9:45

9:45 - 10:0010:00 - 10:1510:15 - 10:3010:30 -10:45

10:45 - 11:0011:00 - 11:1511:15 - 11:3011:30 - 11:4511:45 - 12:0012:00 - 12:1512:15 - 12:3012:30 - 12:4512:45 - 1:00

1:00 -2:00 LUNCH LUNCH LUNCH LUNCH LUNCH

2:00 - 2:152:15 - 2:302:30 - 2:452:45 - 3:003:00 - 3:153:15 - 3:303:30 - 3:453:45 - 4:004:00 - 4:154:15 - 4:304:30 - 4:454:45 - 5:005:00 - 5:15 Day 5 Summary

5:15 - 5:305:30 - 5:455:45 - 6:00 Day 1 Summary Day 2 Summary Day 3 Summary Day 4 Summary

Programming Techniques Course Map

Design and documentation of Case study 2

Review and Feed back of

Case study 1 & 2

Sr Manager talk with ASEs

Coding, Testing &

Documentation of Case study

1.

Coding, Testing &

Documentation of Case study 2

Module 2.1:Fundamental

Programming Concepts

Module1:Course Introduction

Module 2.2:Programming

Life Cycle

Module3.1:Introduction to C (basic

constructs, Keywords, literals,

Module 4.2:Pointers

Module 4.3:Memory

Management

Module 4.5:Coding Conventions

Module 4.1:Introduction to

Arrays

Design and Documentation of Case study 1

Module 3.1(contd..):

Declaring and defining

variables,control structures,Best

Practices)

Module 3.2:Functions

Module 4.4:Introduction to

Structures

Module 5:Searcing and Sorting

Page 2: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 1: Course Overview

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

1_Course Overview.ppt

Copyright © 2009 Accenture All Rights Reserved. Accenture, its logo, and Accenture High Performance Delivered are trademarks of Accenture.

Module 1: Course Overview

Programming Techniques

2Copyright © 2009 Accenture All Rights Reserved.

• Welcome• Objectives• Introductions• Expectations of Participants• Ground Rules• Course Objectives• Course Approach and Outline

Agenda

1

Page 3: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 1: Course Overview

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

1_Course Overview.ppt

3Copyright © 2009 Accenture All Rights Reserved.

Welcome to Programming Techniques Course

During this 2 days you will learn about programming techniques.

You will learn how to simplify a given task with Algorithm, flowchart and the different techniques of programming. You will get an introduction to Unit Testing.

Welcome

4Copyright © 2009 Accenture All Rights Reserved.

At the end of this presentation, you should be able to:• Understand the expectations and ground rules• Understand the training approach and evaluation process.• Understand how to access the school resources, including:

the online book, online support, team members and faculty.

Objectives

2

Page 4: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 1: Course Overview

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

1_Course Overview.ppt

5Copyright © 2009 Accenture All Rights Reserved.

• Name• Your self assessment based on:

– “Why I’m here.”– “I am a programmer (using a different programming

language).”– “I am familiar with Programming concepts.”– “I know how to program using C.”– “I am a C Programmer and practice Best programming

Techniques.”• One interesting note about yourself (e.g., a hobby or

talent)• Your expectations from the course

Introductions

6Copyright © 2009 Accenture All Rights Reserved.

• You will work as a team to complete the deliverables of the course.

• You should be resourceful and creative. Utilize the tools and materials that have been provided.

• Participate in discussions, ask questions to clarify if necessary.

Expectations of participants

3

Page 5: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 1: Course Overview

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

1_Course Overview.ppt

7Copyright © 2009 Accenture All Rights Reserved.

• Introduction to algorithms and it’s analysis, various approaches used in programming, flow chart, testing & debugging the solution

• Importance of documentation• Introduction to best practices to be followed in

programming like• Introduction to commonly used concepts in programming

like – Functions– Arrays - Strings– Pointers

Course Objectives

8Copyright © 2009 Accenture All Rights Reserved.

Learn by Doing• Hands-on programming

Activity-based Learning• Activities are designed to be difficult but doable• Activities have time limits to encourage wise use of your time• Activities will force you to research on the required knowledge

Resource-rich Environment• Use available resources (i.e., online/offline materials, human

resources, etc…)• Encourage research and learning on your own

Course Approach

4

Page 6: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 1: Course Overview

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

1_Course Overview.ppt

9Copyright © 2009 Accenture All Rights Reserved.

Teaching Method• This is not a lecture course! • Lessons serve only as guideposts and reminders, and are not

expected to be complete classes on these topics• Instructors serve mainly as facilitators and knowledge coaches

Performance Evaluation• Each participant will be evaluated

Participate• Don’t just listen to discussions, interact!• If in doubt, ask questions to clarify.• Spot problems and suggest alternatives or workarounds.

Course Approach (Cont.)

10Copyright © 2009 Accenture All Rights Reserved.

Teamwork• Cooperate, coordinate, collaborate!• Work together to complete the deliverables for the

course.

Be resourceful • Don’t ask for answers or solutions, find them!• The course environment provides all the necessary tools

and materials to learn, utilize them well.

Course Approach (Cont.)

5

Page 7: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 1: Course Overview

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

1_Course Overview.ppt

11Copyright © 2009 Accenture All Rights Reserved.

• One of the tenets of the school is that the best way to learn is to take a more active, ‘hands-on’ approach.

• The majority of the activities consist of participants working to complete the appropriate deliverables.

• The faculty will act as knowledge coaches and technical consultants.

• This course encourages participants to be resourceful and inquisitive.

Course Approach - Learn By Doing

12Copyright © 2009 Accenture All Rights Reserved.

Level 1 – You– Try to resolve the problem on your own.– Read documentation, try sample codes, surf the web…

Level 2 – Teammates– Try to resolve the problem with your teammates.– Consult entire team, investigate, work together to solve the

problem.Level 3 – Other Teams

– Try to resolve problem with other teams. – Share tips, guides, resolutions, workarounds…

Level 4 – Faculty– Try to resolve problem with your faculty members.

Course Approach - Tiers of Support

6

Page 8: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 1: Course Overview

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

1_Course Overview.ppt

13Copyright © 2009 Accenture All Rights Reserved.

Course Map

Module 4.4: Introduction to Structures

Module 4.5: Coding Conventions

Module 5: Searching and Sorting

Module 3.1(contd..): (Declaring and Defining Variables, Control Structures, Best Practices)

Module 3.2: Functions

LunchLunch

Module 4.1: Introduction to Arrays

Module 4.2: Pointers

Module 4.3: Memory Management

Module 1: Course Introduction

Module 2.1: Fundamental Programming Concepts

Module 2.2: Programming Life Cycle

Module 3.1: Introduction to C (basic constructs, keywords, literals, identifiers)

Day 2Day 1

14Copyright © 2009 Accenture All Rights Reserved.

Ground Rules• Observe proper professional behavior at all times.

– Core hours are from 9:00 a.m. to 6:00 p.m. Inform your supervisors when you will be late or absent.

– Set phones (or beepers) to silent/vibrate mode or turn them off.

– The Accenture Code of Ethics is enforced at all times.

• Observe proper use of Accenture resources and facilities.– No unauthorized software (especially games) installed on

workstations.– Landline is strictly for business purposes or emergency calls

only.– Turn off your machines when you leave for the day. – Downloading of non-training related materials is strictly

prohibited.

7

Page 9: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 1: Course Overview

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

1_Course Overview.ppt

15Copyright © 2009 Accenture All Rights Reserved.

– No unauthorized software especially games should be installed in workstations

– Landline is strictly for business purposes or emergency calls only

– Observe proper dress code

– Proper use of Accenture resources and facilities (e.g. desktops, training room, pantry)

– Maintain confidentiality of company and client-related matters

Ground Rules (Cont.)

16Copyright © 2009 Accenture All Rights Reserved.

• Be aware there will be Knowledge Checks (quizzes) to test your understanding of the information presented.

• You may use the Internet, as long as you use it responsibly to access or research Programming technique related resources.

• We recommend self study.

• Get to know your fellow students and the resources they offer. Tell your fellow students about your strengths and the resources you bring.

Training Resources

8

Page 10: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 1: Course Overview

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

1_Course Overview.ppt

17Copyright © 2009 Accenture All Rights Reserved.

Questions/ Comments• What questions or

comments do you have?

9

Page 11: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 2: Fundamental Programming Concepts

2.1_FundamentalProgrammingConcepts.ppt

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

Copyright © 2009 Accenture All Rights Reserved. Accenture, its logo, and Accenture High Performance Delivered are trademarks of Accenture.Course Code #IDCGRF001-A

Module 2.1: Fundamental Programming Concepts

Programming Techniques

2Copyright © 2009 Accenture All Rights Reserved.

• Algorithm• Benefits of Algorithm• Approaches to Algorithm• Efficiency of Algorithm• Structure of Algorithm • Flowchart• Benefits of Flowchart• Concept of Testing• Unit Testing

Contents

10

Page 12: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 2: Fundamental Programming Concepts

2.1_FundamentalProgrammingConcepts.ppt

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

3Copyright © 2009 Accenture All Rights Reserved.

At the end of this section, you should be able to:• Describe and understand the need of algorithms• Measure the efficiency of Algorithms• Understand the advantages & disadvantages of Flowcharts• Work with Flowcharts • Describe the concepts of testing• Implement Unit Testing

Objective

4Copyright © 2009 Accenture All Rights Reserved.

• Algorithm is a detailed sequence of actions to perform or accomplish some task

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

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

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

What is an Algorithm

11

Page 13: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 2: Fundamental Programming Concepts

2.1_FundamentalProgrammingConcepts.ppt

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

5Copyright © 2009 Accenture All Rights Reserved.

• An algorithm is a definite procedure for performing certain task

• It is written using simple English sentences• Facilitates easy development of programs

– Iterative refinement – Easy to convert it to a program

• It helps resolving complex problems• Review is easier

Benefits of Algorithm

12

Page 14: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 2: Fundamental Programming Concepts

2.1_FundamentalProgrammingConcepts.ppt

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

6Copyright © 2009 Accenture All Rights Reserved.

• There are different approaches of algorithm in analyzing a problem.

– Empirical (a posteriori) approach• It is a method consisting of programming the competing techniques

and trying them on different instances.

– Theoretical (a priori) approach • It determines mathematically the quantity of resources needed by

each algorithm as a function of the size of the instances.

– Hybrid approach • Combination of Empirical and theoretical approach.

Analyzing An Algorithm(1 of 2)

There are two basic approaches:The empirical (posteriori) approach:The empirical approach to choosing an algorithm consists of programming the competing techniques and trying them on different instances with the help of a computer. The theoretical (priori) approach: The theoretical approach consists of determining mathematically the quantity of resources needed by each algorithm as a function of the size of the instances. The resources of most interest are computing time and storage space, with the former usually being the more critical. We compare the algorithms on the basis of their execution times, an algorithm’s storage requirements. The size of an instance corresponds formally to the number of bits needed to represent the instance on a computer, using some precisely defined and reasonably compact coding scheme. (The word “size” to mean any integer that in some way measures the number of components in an instance.) E.g. when we talk about sorting, we usually measure the size of an instance by the number of items to be sorted, ignoring the fact that each of these items may take more than once bit to represent on a computer. Similarly, when we talk about graphs, we usually measure the size of an instance by the number of nodes or edges (or both) involved.

13

Page 15: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 2: Fundamental Programming Concepts

2.1_FundamentalProgrammingConcepts.ppt

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

7Copyright © 2009 Accenture All Rights Reserved.

• There are different approaches of algorithm in analyzing a problem.

– Empirical (a posteriori) approach• It is a method consisting of programming the competing techniques

and trying them on different instances.

– Theoretical (a priori) approach • It determines mathematically the quantity of resources needed by

each algorithm as a function of the size of the instances.

– Hybrid approach • Combination of Empirical and theoretical approach.

Analyzing An Algorithm(2 of 2)

Content ContinuedThe advantage of the theoretical approach is that it depends on neither the computer being used, nor the programming language, nor even the skill of the programmer. It saves both the time that would have been spent needlessly programming an inefficient algorithm and the machine that would have been wasted testing it. More significantly it allows us to study the efficiency of an algorithm when used on instances of any size. This is often not the case with the empirical approach, where practical consideration my force us to test our algorithms only on a small number of arbitrarily chosen instances of moderate size. Since it is often the case that newly discovered algorithm begins to perform better than its predecessor only when they are both used on large instances, this last point is particularly importantOne can also think of a hybrid approach while analyzing the algorithms, where the form of the function describing the algorithm’s efficiency is determined theoretically, and then any required numerical parameters are determined empirically for a particular program and machine, usually by some kind of regression. Using this approach we can predict the time an actual implementation will take to solve an instance much larger than those used in the tests. Beware however of making such an extrapolation solely on the basis of a small number of empirical test, ignoring all theoretical considerations. Predictions made without theoretical support are likely to be very imprecise, if not plain wrong.

14

Page 16: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 2: Fundamental Programming Concepts

2.1_FundamentalProgrammingConcepts.ppt

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

8Copyright © 2009 Accenture All Rights Reserved.

• Complexities are the parameters to capture the challenges or complications

• Few of the algorithm complexities are captured based on:– Time Complexity

• Is the amount of computer time it needs to run to completion

– Space Complexity• Is the amount of memory it needs to run to completion

Algorithm Complexities

Time Complexity - Is the amount of computer time it needs to run to completion. Suppose the space is fixed for one algorithm then only run time will be considered for obtaining the complexity of the algorithm.

Space Complexity - Is the amount of memory it needs to run to completion. The space needed by a program is the sum of space for the code, space for variables, space for constants, space needed by components variables whose size is dependent on the particular problem and the stack space used by recursive procedures.

15

Page 17: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 2: Fundamental Programming Concepts

2.1_FundamentalProgrammingConcepts.ppt

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

9Copyright © 2009 Accenture All Rights Reserved.

• Algorithm can be written using a standard structure• Most of the time it has the following contents

– Begin– Step – Control – Comments– Variables– Input / Output– Exit

• Algorithm Always Begins with – Begin or Start• Algorithm Ends with – End or Exit or Stop• Rest of the structure contents are used depending on the

need

Structure of an Algorithm

10Copyright © 2009 Accenture All Rights Reserved.

Example of an algorithm to find the sum of two numbers

1. Begin

2. Input num1,num2

3. Sum=num1+num2

4. Print Sum

5. End

Algorithm Starting point

End of Algorithm

num1, num2 are the variables declared

“Input” is used to perform read values to num1 & num2

“print” is used to print the output (result)

Structure of an Algorithm - Example 1

16

Page 18: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 2: Fundamental Programming Concepts

2.1_FundamentalProgrammingConcepts.ppt

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

11Copyright © 2009 Accenture All Rights Reserved.

• There are three types of algorithm concepts– Sequential

• Modules are executed in some sequence/ in a linear fashion– Selection (Single & Multiple)

• Single Alternative – based on a particular condition a set of one (or) more statements will be

executed• Multi Alternative

– based on a particular condition a set of one (or) more statements will be executed

– else another set of one (or) more statements will be executed .

– Iterational• Looping statements• Repeat step m thru n, N times

Algorithm concepts

12Copyright © 2009 Accenture All Rights Reserved.

Example of an algorithm to read marks of three subjects and to find the average scored by the student

1. Begin

2. Print “Enter Marks of 3 subjects”

3. Input Marks1, Marks2, Marks3

4. AVG = (Marks1+Marks2+Marks3) / 3

5. Output “Average Marks =“, AVG

6. End

Enter Marks of 3 subjects

60

70

80

Average Marks = 70

Output:Implementation of Sequential Algorithm Method

Sequential Algorithm – Example 2

17

Page 19: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 2: Fundamental Programming Concepts

2.1_FundamentalProgrammingConcepts.ppt

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

13Copyright © 2009 Accenture All Rights Reserved.

Example of an algorithm to read marks of three subjects. Find the average scored by the student, and print pass if the score is more than 50

1. Begin

2. Print “Enter Marks of 3 subjects”

3. Input Marks1, Marks2, Marks3

4. Avg = (marks1+marks2+marks3)/3

5. If (Avg >= 50) Then Print “Passed”

6. End

Enter Marks of 3 subjects

60

70

80

Passed

Output:Implementation of single Alternative algorithm

Single Alternative Algorithm – Example 3

1. The example calculates the Total2. Finds the average of it3. Verifies if the Average score is more than 50, if it is More than 50 Prints resultsThink about the following question:What will be the out come if the marks is less than 50?

18

Page 20: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 2: Fundamental Programming Concepts

2.1_FundamentalProgrammingConcepts.ppt

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

14Copyright © 2009 Accenture All Rights Reserved.

Example of an algorithm to read marks of three subjects. Find the average scored by the student, and print “Pass” if the score is more than 50 otherwise print “Fail”

1. Begin

2. Print “Enter Marks of 3 subjects”

3. Input marks1, marks2,marks3Avg=marks1+marks2+marks3)/3

4. If (Avg >= 50) ThenPrint “Passed”

Else Print “Failed”

5. End

Enter Marks of 3 subjects403030Failed

Output:Implementation of Multiple Alternative algorithm

Multiple Alternative algorithm – Example 4

15Copyright © 2009 Accenture All Rights Reserved.

Begin

1. Print “Enter number of students”

2. Input N

3. Repeat step 4 thru step 7, N TIMES

4. Print “Enter Marks of 3 subjects”

5. Input marks1, marks2, marks3

6. Avg = (marks1+marks2+marks3)/3

7. If (Avg >= 50) Then

Print “Passed”

Else

Print “Failed”

End-if

8. End

Implementation of Iteration Algorithm

Enter number of Students 2

Enter Marks of 3 subjects

30 40 50

Failed

Enter Marks of 3 subjects

60 60 70

Passed

Example of an algorithm to read marks of three subjects. Find the average scored by the student, and print “Pass” if the score is more than 50 otherwise print “Fail” for N number of Students

Algorithm Iteration – Example 5

19

Page 21: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 2: Fundamental Programming Concepts

2.1_FundamentalProgrammingConcepts.ppt

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

16Copyright © 2009 Accenture All Rights Reserved.

• Flowchart is a graphic representation of the logic or steps in a program or system.

• The flowchart can be defined as a diagram of the problem solving steps in a process.

• A flowchart is a schematic representation of a process.

Flowcharts

17Copyright © 2009 Accenture All Rights Reserved.

• Each symbol depicts a process

• The start point, end points, inputs, outputs, etc are represented by a graphical image

• Any flow chart – should have– Start in the beginning– End to the end of the flow

chart– Depending on the

requirement, rest of the symbols are used

Start – End points

Processing Logic

Input/Output

Decisions

Connectors

Loops

Flow Line

Flowchart depictions

20

Page 22: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 2: Fundamental Programming Concepts

2.1_FundamentalProgrammingConcepts.ppt

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

18Copyright © 2009 Accenture All Rights Reserved.

Start

Enter m1,m2,m3

Avg=m1+m2+m3/3

pass

end

Avg>50

Fail

Example of Flow chart to read marks of three subjects. Find the average scored by the student, and print “Pass” if the score is more than 50 otherwise print “Fail”.

Flowchart – Example 1

19Copyright © 2009 Accenture All Rights Reserved.

The essentials of what is done can easily be lost in the technical details of how it is done

Proper documentation

Efficient Coding

Proper Debugging

Alterations and modifications will be difficult

Effective analysis

Complex logicCommunicationDisadvantageAdvantage

Advantages and Disadvantages

21

Page 23: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 2: Fundamental Programming Concepts

2.1_FundamentalProgrammingConcepts.ppt

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

20Copyright © 2009 Accenture All Rights Reserved.

• Testing is a process used to help identify the correctness, completeness and quality of developed computer software.

• Testing is the process of running a system with the intention of finding errors

• It enhances the integrity of a system by detecting deviations in design and errors in the system.

• It aims at detecting error-prone areas, which helps in the prevention of errors in a system.

• Testing also adds value to the product by conforming to the user requirements.

• It is Oriented to 'detection'

Testing

Content:The purpose of testing is to discover errors. Testing is the process of trying to discover every conceivable fault or weakness in a work product. Software testing is a process used to identify the correctness, completeness and quality of developed computer software. Actually, testing can never establish the correctness of computer software, as this can only be done by formal verification (and only when there is no mistake in the formal verification process). It can only find defects, not prove that there are none.

22

Page 24: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 2: Fundamental Programming Concepts

2.1_FundamentalProgrammingConcepts.ppt

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

21Copyright © 2009 Accenture All Rights Reserved.

• A unit test is a method of testing the correctness of a particular module of source code.

• Unit testing is also known as Component/ Module/ Program Testing.

• It is the most 'micro' scale of testing.

• The goal of unit testing is to isolate each part of the program and show that the individual parts are correct

• Most thorough look at detail.

Unit Testing

Content:In computer programming, a unit test is a procedure used to verify that a particular module of source code is working properly. The idea about unit tests is to write test cases for all functions and methods so that whenever a change causes a regression, it can be quickly identified and fixed. Ideally, each test case is separate from the others; constructs such as mock objects can assist in separating unit tests. This type of testing is mostly done by the developers and not by end-users.

The goal of unit testing is to isolate each part of the program and show that the individual parts are correct. Unit testing provides a strict, written contract that the piece of code must satisfy. As a result, it affords several benefits.Unit testing is done by the programmer as it requires detailed knowledge of the internal program design and code.

23

Page 25: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 2: Fundamental Programming Concepts

2.1_FundamentalProgrammingConcepts.ppt

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

22Copyright © 2009 Accenture All Rights Reserved.

Entry criteria:• After completion of each class/method, unit testing should

be done.

Exit criteria: • Functionality is achieved• All requirements tested & verifiedResult:• No Incorrect data, or data recorded in the wrong field,

account or database • No side-effects or bugs remain vis-à-vis functionality • No errors in calculations, formulas or rounding• No data corruption errors

Unit Testing (Cont.)

23Copyright © 2009 Accenture All Rights Reserved.

• Test case is a set of test inputs, execution conditions, and expected results developed for a particular objective, such as to exercise a particular program path or to verify compliance with a specific requirement

• Test cases are written for each unit in the main program

• A program will execute all the test cases and record the results in a document called test file.

• Test cases will have Description, inputs, expected outcomes

Test Cases

24

Page 26: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 2: Fundamental Programming Concepts

2.1_FundamentalProgrammingConcepts.ppt

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

24Copyright © 2009 Accenture All Rights Reserved.

1. Begin

2. Print “Enter number of students”

3. Input N

4. Repeat step 4 thru step 8, N TIMES

5. Print “Enter Marks of 3 subjects”

6. Input marks1, marks2, marks3

7. Avg = (marks1+marks2+marks3)/3

8. If (Avg >= 50) ThenPrint “Passed”

ElsePrint “Failed”

End-if

9. End

Enter number of Students 2

Enter Marks of 3 subjects

30 40 50

Failed

Enter Marks of 3 subjects

60 60 70

Passed

Test Case - Example

25Copyright © 2009 Accenture All Rights Reserved.

Correct Input, should continue the next stage

Number : XEnter number1.004

Invalid inputSpecial character : X

Enter a special character

1.003

Negative inputNumber : XEnter negative number

1.002

Invalid inputCharacter : XEnter character1.001

Expected ResultInput DataAction / Description

Step Number

Example-test cases

25

Page 27: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 2: Fundamental Programming Concepts

2.1_FundamentalProgrammingConcepts.ppt

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

26Copyright © 2009 Accenture All Rights Reserved.

• Tasks– Hands on using Algorithms, Flowcharts and Unit Testing

• Input Documents– Module 1_activities.doc

• Exercise 1

Algorithm, Flowchart & Unit Testing - Activity

30 minutes

27Copyright © 2009 Accenture All Rights Reserved.

• Algorithm is a detailed sequence of actions to perform or accomplish some task

• Algorithms facilitate easy development of programs• Flowchart is a graphic representation of the logic or

steps in a program or system • Testing is the process of running a system with the

intention of finding errors. • Unit testing is used to isolate each part of the program and

show that the individual parts are correct.

Key Points

26

Page 28: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 2.2: Programming Life Cycle

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

2.2_ProgrammingLifeCycle.ppt

Copyright © 2009 Accenture All Rights Reserved. Accenture, its logo, and Accenture High Performance Delivered are trademarks of Accenture.Course Code #IDCGRF001-A

Module 2.2: Programming Life Cycle

Programming Techniques

2Copyright © 2009 Accenture All Rights Reserved.

• Programming• Programming Life Cycle• Types of Programming Design

– Top-Down Approach– Bottom-Up Approach – Linear Programming– Structured Programming

Contents

27

Page 29: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 2.2: Programming Life Cycle

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

2.2_ProgrammingLifeCycle.ppt

3Copyright © 2009 Accenture All Rights Reserved.

At the end of this section, you should be able to:• Understand what is programming• Work with program life cycle• Understand different types of Programming Design

– Top-Down Approach– Bottom-Up Approach – Linear Programming– Structured Programming

Objectives

4Copyright © 2009 Accenture All Rights Reserved.

• A program is an algorithm expressed in a programming language

• Programming is an act of creating software or some other set of instructions for a computer

• Computer programming is the craft of implementing one or more interrelated algorithms using a particular programming language to produce a concrete computer program

Programming

28

Page 30: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 2.2: Programming Life Cycle

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

2.2_ProgrammingLifeCycle.ppt

5Copyright © 2009 Accenture All Rights Reserved.

RequirementsGathering,Problem definition

Build

Analysis & Design

Testing

Deploy & Maintain

WHAT

HOW

DO IT

TEST

USE

Program Development Life cycle

6Copyright © 2009 Accenture All Rights Reserved.

• Different Types of Programming Design Approach are– Top-down programming – Bottom-up programming– Linear programming– Structured programming

Program Design Approaches

29

Page 31: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 2.2: Programming Life Cycle

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

2.2_ProgrammingLifeCycle.ppt

7Copyright © 2009 Accenture All Rights Reserved.

• Based on the fact that large problem become more manageable if they are divided into a number of smaller and simpler tasks which can be tackled separately.

• Top – down design approach is performed in a special way. • The main program is written first. It is tested before sub-

programs are written. • To do this, actual sub programs are replaced with stubs.

Top-Down Design

A stub is a dummy module, which imitates the functionality of the real module.

For example, say, we have to code a function which receives an employee number as the input and returns the details of that employee after doing a database look up. A stub of this function would be a function with the same name and same number of arguments. But, instead of doing a database lookup, the stub may return the dummy details of an employee after receiving employee number.

30

Page 32: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 2.2: Programming Life Cycle

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

2.2_ProgrammingLifeCycle.ppt

8Copyright © 2009 Accenture All Rights Reserved.

Top-Down Design (contd..)

• The stubs tests to see if the data is passed correctly. After the main program is written and checked, each module is written and tested in turn.

• If the modules run properly, then it is tested with the main program. If the module and the main run properly then the next module is written and checked and so on..

9Copyright © 2009 Accenture All Rights Reserved.

• Write the most basic subroutines in the hierarchy first and then use them to make more sophisticated subroutines

• The pure bottom-up approach is generally not recommended because it is difficult to anticipate which low subroutines will be needed for any particular program

• In this approach it is usually assumed that the basic routines created will be generic enough to be used more than once

• This approach is designed to generate reusable code

• This is more like a basic instruction in the programming language than a large scale program component.

Bottom-Up Design

31

Page 33: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 2.2: Programming Life Cycle

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

2.2_ProgrammingLifeCycle.ppt

10Copyright © 2009 Accenture All Rights Reserved.

• Straightforward programming in sequential manner is Linear Programming

• This does not involve any decision making. • General model of the linear program is :

– Read a data value.– Compute an intermediate result.– Use the intermediate result to compute the desired

answer.– Print the answer.– Stop

Linear Programming

11Copyright © 2009 Accenture All Rights Reserved.

• The technique for writing a program using decisions, branching points, loops, etc. is called structured programming.

• It in turn results in more complex programs.

• There are procedures that can be used for writing those complex programs that makes them much less error prone and much easier in debug.

Structured Programming

32

Page 34: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 2.2: Programming Life Cycle

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

2.2_ProgrammingLifeCycle.ppt

12Copyright © 2009 Accenture All Rights Reserved.

CodingCoding

Debugging /Testing

Debugging /Testing

LinkingLinking

CompilationCompilation

Source Code + Test Script

Object code

LibrariesExecutable

File

AlgorithmAlgorithm

Test PlanTest Plan

Req. Gathering

Req. Gathering

Pseudo code

Program life cycle

13Copyright © 2009 Accenture All Rights Reserved.

• Requirement Gathering– Gathering all the required information to understand the

problem in hand

• Algorithm– A simple English, programming language independent

pseudo code is generated.

• Test Plan– Gives a plan to test the solution. It involves test cases, test

scripts and test data

Program life cycle (Cont.)

33

Page 35: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 2.2: Programming Life Cycle

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

2.2_ProgrammingLifeCycle.ppt

14Copyright © 2009 Accenture All Rights Reserved.

• Coding– Enter the source code using some standard editor, care must

be taken for proper formatting, indenting and using comment entries.

• Compilation– The compiler program scans the source code for SYNTAX

errors, and if it does not find any errors, it converts the source code to OBJECT code.

• Link– The object files are combined with other ‘library’ files to create

the EXECUTABLE file.

Program life cycle (Cont.)

15Copyright © 2009 Accenture All Rights Reserved.

• Library – It is a catalogue of previously developed objects. They contain

procedures for input, output, math, etc. A user can create theirown libraries

• Testing – Synthesize test data such that it will evaluate the different

criteria. The testing should be NEGATIVE testing.• Debugger

– It is a very useful tool to test the program as the intermediate results, new values of the variables, etc are visible

Program life cycle (Cont.)

34

Page 36: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 2.2: Programming Life Cycle

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

2.2_ProgrammingLifeCycle.ppt

16Copyright © 2009 Accenture All Rights Reserved.

• A program is an algorithm expressed in a programming language

• Programming is the craft of implementing one or more interrelated algorithms using a particular programming language

• Large problem become more manageable if they are divided into a number of smaller and simpler tasks which can be tackled separately.

• Straightforward programming in sequential manner is Linear Programming

Key points

17Copyright © 2009 Accenture All Rights Reserved.

• Tasks– Hands on using Top down approach

• Input Documents– Module 1_activities.doc

• Exercise 2

Program design - Activity

20 minutes

35

Page 37: Programming Techniques_PG(New 2009) (1)

Programming TechniquesModule 3.1: Introduction to C

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

3.1_IntroductionToC.ppt

Copyright © 2009 Accenture All Rights Reserved. Accenture, its logo, and Accenture High Performance Delivered are trademarks of Accenture.Course Code #IDCGRF001-A

Programming TechniquesModule 3.1: Introduction to C

2Copyright © 2009 Accenture All Rights Reserved.

• Introduction to C programming• Basic Constructs of C• Keywords• Identifiers• Literals• Declaring and Defining Variables• Control Structures• Best Practices

Contents

36

Page 38: Programming Techniques_PG(New 2009) (1)

Programming TechniquesModule 3.1: Introduction to C

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

3.1_IntroductionToC.ppt

3Copyright © 2009 Accenture All Rights Reserved.

Objectives

At the end of this section, you should be able to:• Use basic constructs of C programming language

• Use Different types of Control & Branching statements

• Apply best programming practices

4Copyright © 2009 Accenture All Rights Reserved.

• C is Structured Programming Language• The C programming language is a standardized

programming language developed by Ken Thompson and Dennis Ritchie

• It was developed in early 1970s • It is one of the most widely used programming languages • It is praised for its efficiency, and is the most popular

programming language for writing system software

C Programming

37

Page 39: Programming Techniques_PG(New 2009) (1)

Programming TechniquesModule 3.1: Introduction to C

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

3.1_IntroductionToC.ppt

5Copyright © 2009 Accenture All Rights Reserved.

1. A “C” program is written

2. The program is compiled

3. An object file is created – it is in machine code

4. Object modules are converted into executable programs with the help of linkers allowing the program to be run on an operating system

Compiler

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

printf ( “Hello World!”); return 0;

}

Source Code

Object file Assembly language

statements

Linkers Links library files and object files

Forms executable file to run on the operating

system

How does C work?

6Copyright © 2009 Accenture All Rights Reserved.

/****************************************************** hello.c -- program to print out "Hello World". ** Not an especially earth-shattering program. ** ** Author: @AuthorName ** ** Date : 06-03-06 ** ** Purpose: Demonstration of a simple program. ** ** Usage: ** Runs the program and the message appears. *

*****************************************************/#include <stdio.h>

int main(){

/* Say Hello to world */printf("Hello World\n");return (0);

}

The sentence beginning with # is a preprocessor directive.Here stdio.h is known as a header file. It includes standard input and output header file in to the program

Preprocessors

The main() function is the point from where the C program begins execution. Any C program to be executed should have a main() function.

main ()

C programs consist of functionsA function should always be followed by a pair of parentheses ()

Functions

C Source File Structure

38

Page 40: Programming Techniques_PG(New 2009) (1)

Programming TechniquesModule 3.1: Introduction to C

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

3.1_IntroductionToC.ppt

7Copyright © 2009 Accenture All Rights Reserved.

/****************************************************** hello.c -- program to print out "Hello World". ** Not an especially earth-shattering program. ** ** Author: @AuthorName ** ** Date : 06-03-06 ** ** Purpose: Demonstration of a simple program. ** ** Usage: ** Runs the program and the message appears. *

*****************************************************/#include <stdio.h>

int main(){

/* Say Hello to world */printf("Hello World\n");return (0);

}

Braces are used for grouping statements or blocks of code.The left brace ( { ) indicates the beginning of a function or a class, which contains the variables and methods needed. The left brace also indicates the beginning of a method body.For every left brace that opens a class or method you need a corresponding right brace ( } ) to close the class or method.A right brace always closes its nearest left brace

Braces

C Source File Structure (Cont.)

8Copyright © 2009 Accenture All Rights Reserved.

/****************************************************** hello.c -- program to print out "Hello World". ** Not an especially earth-shattering program. ** ** Author: @AuthorName ** ** Date : 06-03-06 ** ** Purpose: Demonstration of a simple program. ** ** Usage: ** Runs the program and the message appears. *

*****************************************************/#include <stdio.h>

int main(){

/* Say Hello to world */printf("Hello World\n");return (0);

}

printf() is the standard output function of the C program ( the display screen).printf is included in the stdio.h header file.

printf()

return instructs the function to end and return the code that follows the instruction. In this case return (0); return will end main() and will return 0 to the system console, which is an integer value.

return (0)

C Source File Structure (Cont.)

39

Page 41: Programming Techniques_PG(New 2009) (1)

Programming TechniquesModule 3.1: Introduction to C

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

3.1_IntroductionToC.ppt

9Copyright © 2009 Accenture All Rights Reserved.

• To compile a C Program– Write the program in Turbo C Editor– Alt + F9– If any errors Generated – Correct them– Re compile the program using Alt + F9

• To Run a C Program– The program should have No Compile errors – Ctrl+ F9

• Files that get linked and get generated– Header files .h– Object files .obj or .o– Linker files .lnk

File Extensions & Program Execution

10Copyright © 2009 Accenture All Rights Reserved.

• Starts from main()

• Have to declare variable before using them

• The variable declaration should be the first part in any function.

• Variables must be declared following the naming conventions

• Use appropriate Statements in a logical sequence

• Use Comments - A comment is a self explanatory information that is contained in the program to assist the reader to read the program.(/*…..*/)

• Writing comments is a good programming practice and a good source of self documentation.

Tips for C program

40

Page 42: Programming Techniques_PG(New 2009) (1)

Programming TechniquesModule 3.1: Introduction to C

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

3.1_IntroductionToC.ppt

11Copyright © 2009 Accenture All Rights Reserved.

whilesignedgotodovoidshortfordefaultunsignedreturnfarcontinueunionregisterfloatconsttypedefnearexterncharswitchlongenumcasestructintelsebreakstaticifdoubleauto

C key words

12Copyright © 2009 Accenture All Rights Reserved.

printMe is not the same as PrintMe

• An identifier is the name given by a programmer to a variable, statement label and function– An identifier must begin with a

letter.– Subsequent characters must

be letters, numbers, $ or _– An identifier must not be a C

keyword– Identifiers are case-sensitive

Switchswitch

Write_PrintWrite&Print

strikes33strikes

CorrectIncorrect

Identifiers

41

Page 43: Programming Techniques_PG(New 2009) (1)

Programming TechniquesModule 3.1: Introduction to C

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

3.1_IntroductionToC.ppt

13Copyright © 2009 Accenture All Rights Reserved.

• Any identifier name should be long enough to be descriptive. Avoid cryptic abbreviations.

• Pick a notation style, and use it consistently.

• Be certain identifiers look and sound different from one another to minimize confusion.

Identifiers (cond…)

14Copyright © 2009 Accenture All Rights Reserved.

• A literal is a representation of a value of a particular type• Literals can also be constants • The different types of literals are:

– Integer number – Floating point number– Character– String

Examples & ValuesType

’a’ ‘\uFFFF' ‘\777’character

123 123L O123 Ox123integer

123.5 123.5D 123.5F 123.5e+6

floating-point

\n \t \b \f \r \’ \” \\escape sequences

Literals

42

Page 44: Programming Techniques_PG(New 2009) (1)

Programming TechniquesModule 3.1: Introduction to C

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

3.1_IntroductionToC.ppt

15Copyright © 2009 Accenture All Rights Reserved.

• A variable is a named storage location used to represent data that can be changed while the program is running

• A data type determines the values that a variable can contain and the operations that can be performed on it

• Categories of data types:• Primitive data types• User Defined data types

Variable and Data Types

16Copyright © 2009 Accenture All Rights Reserved.

±1.79769313486231570e+308 ±4.94065645841246544e-32464double

±3.40282346638528860e+38 ±1.40129846432481707e-4532float

+32,767 [215-1] -32,768 [-215] 16int

'\uffff' [27-1] '\u0000' [0] 8char

Highest ValueLowest ValueBitsType

• Primitive data types represent atomic values and are built-in to C

Primitive data types

43

Page 45: Programming Techniques_PG(New 2009) (1)

Programming TechniquesModule 3.1: Introduction to C

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

3.1_IntroductionToC.ppt

17Copyright © 2009 Accenture All Rights Reserved.

0 -> +2551 unsigned char -128 -> +1271 signed char -2,147,483,648 -> +2,147,483,647 4 long int-2,147,483,648 -> +2,147,483,647 4 int 0 -> +4,294,967,2954 unsigned int 0 -> +65,535 2 unsigned short int-32,768 -> +32,767 2 short int

RangeBytesType

• Few of the data types have the following modifiers - short, long , signed and unsigned

• The modifiers define the amount of storage allocated to the variable

Primitive Data Types (contd…)

18Copyright © 2009 Accenture All Rights Reserved.

• C allows users to create and use data types • User Defined Data Types can be created with the help of

Primitive Data Types.

• Multiple data types together can be used to form a user defined data type

• Different ways in which user defined data types are created are– Structures

– Unions

User Defined Data Types

44

Page 46: Programming Techniques_PG(New 2009) (1)

Programming TechniquesModule 3.1: Introduction to C

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

3.1_IntroductionToC.ppt

19Copyright © 2009 Accenture All Rights Reserved.

• Declaring a variable with primitive data typeint age = 21;

identifier name

primitivetype

initial value

• Declaring a variable with user defined data type

struct Item Product ;

identifier name

Structure data type

Variable Declaration & initialization

20Copyright © 2009 Accenture All Rights Reserved.

declaration

int age;

type Identifier name

initialization/assignmentage = 17;

Identifier name

value

MEMORY

age 17

Stack

allot space to memory

Primitive Type Declaration

45

Page 47: Programming Techniques_PG(New 2009) (1)

Programming TechniquesModule 3.1: Introduction to C

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

3.1_IntroductionToC.ppt

21Copyright © 2009 Accenture All Rights Reserved.

• “camel notation” – This notation is often used for naming variables.– the first word is in lower case letters, and the second and all

subsequent words begin with a capital letter:– myVariable, heightOfRectangle, areaOfField,colorOfPaint

• In myVariable, the capital letter looks like a camel hump in the middle of the word, hence the name

• Another notation is called “underscore notation”:– my_variable, height_of_rectangle, area_of_field

• Avoid Hungarian notation, as C is strongly typed.– Might still use p before pointers, r before references

Naming Variables

46

Page 48: Programming Techniques_PG(New 2009) (1)

Programming TechniquesModule 3.1: Introduction to C

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

3.1_IntroductionToC.ppt

22Copyright © 2009 Accenture All Rights Reserved.

This is a test

X=5 y=12.6

Output:

• printf () is a formatted output function used to print the data to the standard output device i.e., Monitor

• It prints the list of arguments according to the specified format on the standard output device.

• It returns the number of characters printed

int printf(“<format string”,<list of variables>);

int x=5;

float y=12.6;

printf (“this is a test\n”);

printf (“x=%d y=%f”, x, y);

Example:

printf ()

Formatted function : since these functions gives the liberty to use format specifiers they are called formatted functions.

Example : printf("%d %f %s %c",12,12.3,"Accenture",'S');

47

Page 49: Programming Techniques_PG(New 2009) (1)

Programming TechniquesModule 3.1: Introduction to C

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

3.1_IntroductionToC.ppt

23Copyright © 2009 Accenture All Rights Reserved.

• scanf () is a formatted input function that reads value from the standard input device i.e. Keyboard

• The Values read are stored in a memory address allocated for that particular Variable

• If more than one variable are being read white spaces are considered to be the separators.

int scanf(“<format string>”,<list of arguments>);

int x;

float y;

printf (“Enter the values:”);

scanf (“%d %f”, &x, &y, );

Example:

& specifies the Address

scanf()

The arguments list must be the addresses of the variables being read or pointers to those variables.

48

Page 50: Programming Techniques_PG(New 2009) (1)

Programming TechniquesModule 3.1: Introduction to C

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

3.1_IntroductionToC.ppt

24Copyright © 2009 Accenture All Rights Reserved.

• getchar()- To accept a character at a time• putchar()- To print a character at a time

int c;

While ((c=getchar())!=EOF){

putchar(c);}

Task :Read a characterWhile (character is not end of file indicator)Output the character just readRead a character

Example to write a program that copies its input to its output one character at a time

Sample Code

Unformatted Functions

Unformatted functions - since these functions don’t give us the liberty to use format specifiers they are called unformatted function

49

Page 51: Programming Techniques_PG(New 2009) (1)

Programming TechniquesModule 3.1: Introduction to C

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

3.1_IntroductionToC.ppt

25Copyright © 2009 Accenture All Rights Reserved.

• Unary operators• Arithmetic operators• Relational operators• Conditional operator• Logical operator• Assignment operators• Evaluation order

Operators

26Copyright © 2009 Accenture All Rights Reserved.

• Unary operators use only one operand

Example:

Negative sign-

Positive sign+

Decrement by 1, can be prefix or postfix

--

Increment by 1, can be prefix or postfix

++

Increment & decrement operators can only be applied to variables. Expression (i+j)++ is illegal.

n=10;

x=n++; means set x to 10.

x=++n; means set x to 11.

In both the cases n becomes 11.

Unary Operators

50

Page 52: Programming Techniques_PG(New 2009) (1)

Programming TechniquesModule 3.1: Introduction to C

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

3.1_IntroductionToC.ppt

27Copyright © 2009 Accenture All Rights Reserved.

• Arithmetic operators are used for basic mathematical operations

Modulo, remainder%

Divide/

Multiply*

Subtract-

Add+

int num1=15, num2=10;

printf("calculating...");

printf(“%d”,num1 + num2);

printf(“%d”,num1 - num2);

printf(“%d”,num1 * num2);

printf(“%d”,num1 / num2);

printf(“%d”,num1 % num2);

Sample code

calculating...

25

5

150

1

5

Arithmetic operators

28Copyright © 2009 Accenture All Rights Reserved.

• Relational operators are used to compare values

Not equals!=

Equals==

Greater than or equal to>=

Greater than>

Less than or equal to<=

Less than<

Relational operators

51

Page 53: Programming Techniques_PG(New 2009) (1)

Programming TechniquesModule 3.1: Introduction to C

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

3.1_IntroductionToC.ppt

29Copyright © 2009 Accenture All Rights Reserved.

• The ternary operator ( ? : ) provides a handy way to code simple if-else() statements in a single expression

• It is also known as the conditional operator

• If condition is true, then exp1 is returned as the result of operation

• If condition is false, then exp2 is returned as the result of operation

• Can be nested to accommodate chain of conditions

int x=5,y=6;

printf (“The maximum is = %d” ,x > y ? x : y);

Syntax:condition ? exp1 : exp2;

Sample code:The maximum is = 6

Conditional operators

30Copyright © 2009 Accenture All Rights Reserved.

• Logical Operators are used to Combine 2 (or) more Relational Expressions, to check more complicated conditions.

• ! inverts a boolean value• && || evaluate operands

conditionally

OR||

AND&&

NOT!

Truth Table

true

true

true

false

Op1 || Op2

true

false

false

false

Op1 && Op2

false

false

true

true

!Op1

truetrue

falsetrue

truefalse

falsefalse

Op2Op1

Logical operators

52

Page 54: Programming Techniques_PG(New 2009) (1)

Programming TechniquesModule 3.1: Introduction to C

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

3.1_IntroductionToC.ppt

31Copyright © 2009 Accenture All Rights Reserved.

• Assignment operators are used to set the value of a variable

XOR and assign^=

OR and assign|=

AND and assign&=

Modulo and assign%=

Divide and assign/=

Multiply and assign*=

Subtract and assign-=

Add and assign+=

Assign=

Assignment operators

32Copyright © 2009 Accenture All Rights Reserved.

float unitPrice=120, qty=2, salesAmount;float discRate=15, discAmount, vatRate=10,vatAmount;/* compute gross sales*/salesAmount = unitPrice * qty;pritnf ("Gross Sales: %f" , salesAmount);/* compute tax */vatRate /= 100;vatAmount = salesAmount * vatRate;salesAmount += vatAmount;pritnf ("Tax: %f " , vatAmount);/* compute discount*/discRate /= 100;discAmount = salesAmount * discRate;salesAmount -= discAmount;printf ("Discount: %f" , discAmount);printf ("Please pay: %f”, salesAmount);

Sample code

Gross Sales: 240.0

Tax: 24.0

Discount: 39.6

Please pay: 224.4

Sample output:

Assignment operators (Cont.)

53

Page 55: Programming Techniques_PG(New 2009) (1)

Programming TechniquesModule 3.1: Introduction to C

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

3.1_IntroductionToC.ppt

33Copyright © 2009 Accenture All Rights Reserved.

Evaluation order of operators in C is as follows:

=, +=, -=, *=, /=Assignment 6

?:Conditional 5

&&, ||Logical 4

<, <=, >, >=, ==, !=Comparison 3

*, /, % (Equal precedence from left to right)

+, - (Equal precedence from left to right)

Arithmetic 2

++, --, +, -, ( ), Logical not (!)Unary 1

OperatorsLevel

Evaluation order

34Copyright © 2009 Accenture All Rights Reserved.

• if-else() statement• switch() statement• while() statement• do-while() statement• for() statement• break statement• continue statement

Flow controls

54

Page 56: Programming Techniques_PG(New 2009) (1)

Programming TechniquesModule 3.1: Introduction to C

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

3.1_IntroductionToC.ppt

35Copyright © 2009 Accenture All Rights Reserved.

1. Sequential – Perform statements in the

order they are written

2. Selection– Perform statements based on

condition

3. Iteration– Perform statements repeatedly

based on condition

Types of flow control

36Copyright © 2009 Accenture All Rights Reserved.

• if-else performs statements based on two conditions• Condition should result to a boolean expression• If condition is true, the statements following if are

executed• If condition is false, the statements following else are

executed• Can be nested to allow more conditions

Syntax: if (condition) { /* braces

optional*/

/* statement required*/

}

else { /* else clause is optional*/

/* statement required */

}

Example:int age=10;

if (age < 10) {printf("You're just a kid.");

} else if (age < 20){pritnf("You're a teenager.");

} else {pritnf("You're probably

old...");}

if-else

55

Page 57: Programming Techniques_PG(New 2009) (1)

Programming TechniquesModule 3.1: Introduction to C

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

3.1_IntroductionToC.ppt

37Copyright © 2009 Accenture All Rights Reserved.

• switch() is a selective statement which can be used when multiple conditions are available

• exp can only be char byte short int, val should be a unique constant of exp

• case statements falls through the next case unless a breakis encountered

• default is executed if none of the other cases match the exp

switch (exp) {

case val:

/* statements here*/

case val:

/* statements here*/

default:

/* statements here*/

}

Example:

char sex='M';

switch (sex){

case 'M':

pritnf("I'm a male."); break;

case 'F':

pritnf("I'm a female."); break;

default:

pritnf("I am what I am!");

}

Syntax:

switch()

38Copyright © 2009 Accenture All Rights Reserved.

• Loop is an informal term that refers to any kind of iterative control structure –any structure that causes a program to repeatedly execute a block of code based on specific condition.

• Types of loops– while– do…while– for

Loops

56

Page 58: Programming Techniques_PG(New 2009) (1)

Programming TechniquesModule 3.1: Introduction to C

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

3.1_IntroductionToC.ppt

39Copyright © 2009 Accenture All Rights Reserved.

While selecting a loop check• Flexibility :

– Whether the loop executes a specified number of times or whether it test for completion on each iteration

• Location of the test for completion :

– Beginning • The body isn't necessarily executed

– Middle • The part of the loop that precedes the test is executed at least

once, but the part of the loop that follows the test isn't executed at all

– End • The body is executed at least once

Guidelines to use Loops

40Copyright © 2009 Accenture All Rights Reserved.

while() performs statements repeatedly whilecondition remains true

int ctr=10;

while (ctr > 0) {

pritnf("Timer: %d" , ctr--);

}

Syntax:

Example: Timer: 10

Timer: 9

Timer: 8

Timer: 7

Timer: 6

Timer: 5

Timer: 4

Timer: 3

Timer: 2

Timer: 1

Output:

while (condition) { /* braces optional*/

/* statements here*/

}

while()

57

Page 59: Programming Techniques_PG(New 2009) (1)

Programming TechniquesModule 3.1: Introduction to C

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

3.1_IntroductionToC.ppt

41Copyright © 2009 Accenture All Rights Reserved.

• Flexible• Location of the test for completion :

– Beginning : The body isn't necessarily executed

Example :Doorkeeper at the Cinema hall keeps checking tickets of all & gives entry to those who have the valid tickets

Facts about while()

42Copyright © 2009 Accenture All Rights Reserved.

do-while() performs statements repeatedly (at least once) while condition remains true

do

/* statements here*/

while (condition);

int ctr=0;

do

printf("Timer: %d" , ctr++);

while (ctr < 10);

/* next statement*/

Syntax:

Example:

Timer: 0

Timer: 1

Timer: 2

Timer: 3

Timer: 4

Timer: 5

Timer: 6

Timer: 7

Timer: 8

Timer: 9

Output:

do-while()

58

Page 60: Programming Techniques_PG(New 2009) (1)

Programming TechniquesModule 3.1: Introduction to C

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

3.1_IntroductionToC.ppt

43Copyright © 2009 Accenture All Rights Reserved.

• Flexible• Location of the test for completion :

– At the End : The body isn't necessarily executed at least once

Facts about do-while()

44Copyright © 2009 Accenture All Rights Reserved.

• for() performs statements repeatedly based on a condition

• Init is a list of either declarations or expressions, evaluated first and only once

• Condition is evaluated before each iteration• Exp is a list of expressions, evaluated after each iteration• All entries inside () are optional, for(;;) is an infinite

loop

Syntax: for (init; condition; exp) { /* braces optional*/

/* statements here*/

}

for()

59

Page 61: Programming Techniques_PG(New 2009) (1)

Programming TechniquesModule 3.1: Introduction to C

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

3.1_IntroductionToC.ppt

45Copyright © 2009 Accenture All Rights Reserved.

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

printf( “the number is %d:”, i);

Example

Output The number is 1

The number is 2

The number is 3

The number is 4

The number is 5

The number is 6

The number is 7

The number is 8

The number is 9

The number is 10

•A good choice when you need to loop that executes a specified number of times

•Use it for simple activities which don’t require internal loop controls.

for() (Cont.)

46Copyright © 2009 Accenture All Rights Reserved.

• Use a while loop, if there is a condition under which execution has to jump out of a loop

• Don’t explicitly change the value of a counter variable of a for loop to force it to terminate, instead use a while loop

• for loop is for simple uses• Most complicated looping tasks are better handled by a while loop

• Use for loop when they are appropriate Note: Use for loop for simple activities that don’t require internal loop controls.

while vs. for ()

60

Page 62: Programming Techniques_PG(New 2009) (1)

Programming TechniquesModule 3.1: Introduction to C

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

3.1_IntroductionToC.ppt

47Copyright © 2009 Accenture All Rights Reserved.

• A loop with in which the exit conditions appears in the middle of the loop rather than at the beginning or at the end is known as exit-loop

• break exits loops and switch() statementsbreak;

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

{

if (i>7)

{

printf(“ I is greater than 7”);

break;

}

else

printf(“i=%d”,i);

}

Output

i=0

i=1

i=2

i=3

i=4

i=5

i=6

i=7

I is greater than 7

Example

Syntax

break

Use of break with while loop:#include<stdio.h>main(){

int cnt;cnt=0;while (cnt<=10)

{printf(“Use of Break statement”);cnt++;

if (cnt==5)break;printf(“ Still using Break statement”);

}printf (“End of program “);

}

61

Page 63: Programming Techniques_PG(New 2009) (1)

Programming TechniquesModule 3.1: Introduction to C

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

3.1_IntroductionToC.ppt

48Copyright © 2009 Accenture All Rights Reserved.

• continue is used inside loops to start a new iteration

Syntax: continue;

Example for(i=1; i<=10; i++)

{

printf(“i=%d”,i);

continue;

printf(“it will never get printed”);

}

Output i=1

i=2

i=3

i=4

i=5

i=6

i=7

i=8

i=9

i=10

continue

49Copyright © 2009 Accenture All Rights Reserved.

• The main() method is the start of execution of a C program

• Identifiers are case-sensitive• C keywords cannot be used as identifiers• Use unary, arithmetic operators for basic mathematical

operations• Use assignment operators to assign values to variables• if() and switch() are used for branching statements• Pay attention to the order of if’s and else's, especially if

they process a lot of errors. Make sure the nominal case is clear.

• Order if-then-else chains and cases in case statements for maximum readability.

Key points

62

Page 64: Programming Techniques_PG(New 2009) (1)

Programming TechniquesModule 3.1: Introduction to C

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

3.1_IntroductionToC.ppt

50Copyright © 2009 Accenture All Rights Reserved.

• Use the default clause in a case statement or the last else in a chain of if-else if- else to trap errors

• All control constructs are not created equal. Choose the control construct that’s most appropriate for each sections of code.

• while(), do-while() and for() are used for iterating statements

• Techniques for keeping loops simple include avoiding exotic kinds of loops, minimizing nesting, making entries and exits clear, and keeping housekeeping code in one place.

• Think the loop through carefully to verify that it operates normally under each case and terminates under all possible conditions.

Key points (Cont.)

51Copyright © 2009 Accenture All Rights Reserved.

• Tasks– Hands on using basic concepts of C

• Input Documents– Module 2_activities.doc

• Exercise 3

C basics - Activity

60 minutes

63

Page 65: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 3.2: Functions

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

3.2_Functions.ppt

Copyright © 2009 Accenture All Rights Reserved. Accenture, its logo, and Accenture High Performance Delivered are trademarks of Accenture.Course Code #IDCGRF001-A

Programming TechniquesModule 3.2: Functions

2Copyright © 2009 Accenture All Rights Reserved.

• Introduction to Functions• Function definition• Accessing functions• Declaring Function• Function communication• Formal and actual arguments• Scope of variables• Parameter passing• Recursive functions

Contents

64

Page 66: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 3.2: Functions

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

3.2_Functions.ppt

3Copyright © 2009 Accenture All Rights Reserved.

At the end of this section, you should able to:• Define Functions• Understand Function Communications• Understand parameter passing• Understand the scope of variables in the function• Understand how to write recursive functions

Objectives

4Copyright © 2009 Accenture All Rights Reserved.

• A C program is a collection of one (or) more functions, with a special function main() from where the Execution starts.

• Functions are the building blocks of a C program• Functions consist of sets of statements• Several functions can be grouped together as a single unit

to form a function• Functions break large computing task into smaller ones.• Function is a unit of program code, as per some syntax, to

perform specific and well defined task • Benefits of Functions

– Functions break large computing task into smaller ones, and enable people to build on what others have done instead of starting over from scratch.

Functions

65

Page 67: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 3.2: Functions

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

3.2_Functions.ppt

5Copyright © 2009 Accenture All Rights Reserved.

• Function name should begin with a capital letter

• For a function name, use a strong verb followed by an object:

– PrintReport(), CheckOrderInfo(), ShowResult()…

• It should be long enough to be descriptive

• For a function name, use a description of the return value:

– NextCutomerId(), CurrentPenColor(),….

• Avoid meaningless or wishy-washy verbs

– “DealWithOutput()” (a wishy-washy verb) can be replace by “FormatAndPrintOutput()”

Note:Naming convention should be consistent across the whole application

Naming Functions

6Copyright © 2009 Accenture All Rights Reserved.

• Describe everything the function does

– ComputerReportTotals() = not an adequate name

– ComputerReportTotalsAndSetPrintingReadyVar() = too long and silly

– An average length of 20 to 35 characters

• Establish Conventions for common operations

– Prefix “Get” for input

• e.g GetInputChar()

• Pick a notation style, and use it consistently so that others can read and understand your coding

Naming Functions (Cont.)

66

Page 68: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 3.2: Functions

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

3.2_Functions.ppt

7Copyright © 2009 Accenture All Rights Reserved.

Return_type name ( data type parameter1, data type parameter2, .....)

{ // statements

}

A return type specifier specifies the type of data returned by the function

• A statement is the function's body

• Braces { } surround the block of a statement

Each input parameter consists of a data type specifier followed by an identifier/nameInput Parameters:• Are declared like a regular variable• Are separated by commas( , )• Can be used only within a function• Allow Parameter to pass to the function

when the function is called• Are optional• Are also called arguments

• The name is the identifier of the function

- A function is called by its name

Defining a Function

8Copyright © 2009 Accenture All Rights Reserved.

int Validate_Date (int d,int m, int y)

{

/* Logic of Date Validation comes here*/

:

:

return(flag);

}

Sample code defining a function

Integer type parameters or arguments

Function Name

Return type use of return keyword

Example to Defining a Function

67

Page 69: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 3.2: Functions

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

3.2_Functions.ppt

9Copyright © 2009 Accenture All Rights Reserved.

Example of a function to find the cube of an integer

int Cube (int Number){int Cbe;Cbe = Number*Number*Number;return (Cbe);

}

Function name

Arguments

Return Type

Example to write a function

10Copyright © 2009 Accenture All Rights Reserved.

• One function can call another function• The same Function can call it self• Rules to be followed to access function

– Create a Prototype i.e., declaring a function– Call the function with appropriate arguments

Accessing functions

68

Page 70: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 3.2: Functions

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

3.2_Functions.ppt

11Copyright © 2009 Accenture All Rights Reserved.

• Like variables, functions are also declared before they are used– This informs the complier that the function will be used later in

the program – Declaring a function is known as function prototyping or a prototype

• Prototyping can be avoided if the function is defined before calling it for the first time

Note: If the function is defined before it is called for the first time, it need not have to be declared.

Declaring a Function

12Copyright © 2009 Accenture All Rights Reserved.

Return_type name ( data_type, data_type, ...);

Data type specifierindicates the type of data returned by the function

Name of the function

Data type of the parameters or arguments

; Indicates end of declaration

int Validate_Date(int d, int m, int y);Example :

Declaring a Function (Cont.)

69

Page 71: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 3.2: Functions

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

3.2_Functions.ppt

13Copyright © 2009 Accenture All Rights Reserved.

• Function Call :result=function_name(Argument1, …,ArgumentN);

• Example :ValidDate=Validate_Date(Day, Month,Year);

To call A Function

14Copyright © 2009 Accenture All Rights Reserved.

• Information is passed to a function via arguments.• The function processes the information to produce a

result (a value).• Result is returned using a return statement.

Function Communication

70

Page 72: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 3.2: Functions

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

3.2_Functions.ppt

15Copyright © 2009 Accenture All Rights Reserved.

• The arguments appearing in the function definition are FORMAL ARGUMENTS

• The arguments appearing in the function call are ACTUAL ARGUMENTS

• The number of actual arguments must be same as the number of formal arguments

• The actual argument must be of the same data type as its corresponding formal argument

Formal & Actual Arguments

16Copyright © 2009 Accenture All Rights Reserved.

• Variables can be declared anywhere before they are used

• If declared outside functions they have global scope• If declared inside a function they are local within the

function

Scope of Variables

71

Page 73: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 3.2: Functions

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

3.2_Functions.ppt

17Copyright © 2009 Accenture All Rights Reserved.

• Local variables– variables defined inside a function– Local Variables are available only within the function

in which they are declared, and only within the block in which they are declared.

– A function’s parameters have local scope.– Default value is Garbage value.

• Global variables– variables defined outside any function & are a– Global Variables are declared outside all the

functions, and are accessible by all functions and all classes.

– Default Initialization is Zero– Avoid global

Global & local variables

18Copyright © 2009 Accenture All Rights Reserved.

• The value of the actual argument is copied into the formal argument.

• The value of the corresponding formal argument can be altered within the function.

• The value of the actual argument within the calling routine will not change.

Parameter passing: Pass by value

72

Page 74: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 3.2: Functions

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

3.2_Functions.ppt

19Copyright © 2009 Accenture All Rights Reserved.

• There are advantages and Disadvantages of Pass by value• Advantages :

– Actual argument can be an expression /variable.– Protects value of the actual argument from alterations within the

function.• Disadvantages

– Information cannot be transferred back to the calling portion ofthe program via arguments.

Advantages and Disadvantages

20Copyright © 2009 Accenture All Rights Reserved.

• Recursive is a function solving a small part of the problem itself by dividing the problem into smaller pieces

• It calls itself to solve each of the smaller pieces.• Recursion is usually called when a small part of the problem

is easy to solve • It is called when a large part is easy to decompose into

smaller pieces.• Recursive functions are those which call themselves• They are elegant compared to non-recursive versions

Recursive Function

73

Page 75: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 3.2: Functions

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

3.2_Functions.ppt

21Copyright © 2009 Accenture All Rights Reserved.

• Caution while using recursion:– It leads to small code and slow execution and chews up stack

space– Small group of problems =>simple, elegant solution– Slightly larger group of problems => simple, elegant but hard

to understand solutions– Most of the problems => massively complicated solutions

• Use recursion selectively

Recursive Function (Cont.)

22Copyright © 2009 Accenture All Rights Reserved.

• Check if the recursive routine include code to stop the recursion? - Make sure the recursion stops

• Use safety counters to prevent infinite recursion

• Check if the routine limited to one routine - limit recursion to one routine

• Keep an eye on the stack, always check if the routine’s depth of recursion within the limits imposed by the size of the program’s stack?

• Check if recursion the best way to implement the routine -Don’t use recursion for simple iteration

Tips for using recursive functions

74

Page 76: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 3.2: Functions

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

3.2_Functions.ppt

23Copyright © 2009 Accenture All Rights Reserved.

• Advantages– Writing modular programs– Reusability– Easy testing & debugging– Easy program modification

• To handle the complexity of design– Divide & conquer– Reusability of code

Use of functions

24Copyright © 2009 Accenture All Rights Reserved.

• Functions are the building blocks of a C program• A function need to be declared and defined before

calling it from any other function• Void is used as the return type if the function is not

returning any value• Return statements can only return a single value• Variables are declared as global or local variables• The function that calls it self is known as Recursion

• Functions supports reusability and easy method to modify the program

Key points

75

Page 77: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 3.2: Functions

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

3.2_Functions.ppt

25Copyright © 2009 Accenture All Rights Reserved.

• Tasks– Hands on using functions in C

• Input Documents– Module 2_activities.doc

• Exercise 4

Functions - Activity

60 minutes

26Copyright © 2009 Accenture All Rights Reserved.

Questions/ Comments• What questions or

comments do you have?

76

Page 78: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 4.1: Introduction to Arrays

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

4.1_IntroductionToArrays.ppt

Copyright © 2009 Accenture All Rights Reserved. Accenture, its logo, and Accenture High Performance Delivered are trademarks of Accenture.

Module 4.1 - Introduction to Arrays

Programming Techniques

2Copyright © 2009 Accenture All Rights Reserved.

Contents• Introduction to Arrays• Defining Arrays• Creating Arrays• Character Arrays• Multi-Dimensional Arrays

77

Page 79: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 4.1: Introduction to Arrays

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

4.1_IntroductionToArrays.ppt

3Copyright © 2009 Accenture All Rights Reserved.

Objectives

At the end of this section, you should be able to:• Define an array• Declare an array of elements• Understand the types of Arrays• State the advantage of a multi-dimensional array

4Copyright © 2009 Accenture All Rights Reserved.

What is an Array ?

An array is simply a sequence of either objects or primitives, all of the same type and packaged together under one identifier name.

A one-dimensional array

00 00 00 000 1 2 3int numbers [ 4 ]

Values

Indices

int numbers[4];

Identifier name

Object type

Indexing operator

78

Page 80: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 4.1: Introduction to Arrays

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

4.1_IntroductionToArrays.ppt

5Copyright © 2009 Accenture All Rights Reserved.

• The simplest and most common type of structured data.• Contains a group of items that are all of the same type and

are directly accessed through the use of an array index.

Why Arrays

79

Page 81: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 4.1: Introduction to Arrays

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

4.1_IntroductionToArrays.ppt

6Copyright © 2009 Accenture All Rights Reserved.

Array:– Consecutive group of memory

locations – Same name and type

• To refer to a particular element, specify: – The array name – The position number

• It is known as Index or Subscript

Arrays Mechanism

a[6]

a[11]

a[10]

a[9]

a[8]

a[7]

Position number of the element within array a

a[0]

a[1]

a[2]

a[3]

a[5]

a[4]

Name of array (Note that all elements of this array have the same name: a )

24

-5

An array is a collection of variables of the same type that are referred to through a common name. A specific element in an array is accessed by an index or subscript.All array elements are stored at contiguous memory location.

80

Page 82: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 4.1: Introduction to Arrays

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

4.1_IntroductionToArrays.ppt

7Copyright © 2009 Accenture All Rights Reserved.

• Format: array_name [ position_number ]

– First element is at position 0

• n element array a:a[0], a[1], a[2]… a[n-1]

• Array elements can function like normal variables: a[ 0 ] = 3

printf (“%d”,a[o]);

Arrays Mechanism (continued)

Array index starts from 0(zero), If an array is having n number of elements, then the nth element is referred to as array [n-1].

81

Page 83: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 4.1: Introduction to Arrays

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

4.1_IntroductionToArrays.ppt

8Copyright © 2009 Accenture All Rights Reserved.

Creating an Array

There are three steps to creating an array: #include <stdio.h>

void main()

{

int scores[3];

scores[0] = 10;

scores[1] = 7;

scores[2] = 9;

}

1. Declaration

2. Construction

3. Initialization

9Copyright © 2009 Accenture All Rights Reserved.

• Initializers– int n[ 5 ] = { 1, 2, 3, 4, 5 };

• Till arrays are not given any specific values, they contain garbage value

• If there are too many initializers, a syntax error is generated

• If the array is initialized where it is declared, mentioning the dimension is optional.- int n[] = {10,20,30,30};

Using Arrays

82

Page 84: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 4.1: Introduction to Arrays

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

4.1_IntroductionToArrays.ppt

10Copyright © 2009 Accenture All Rights Reserved.

Passing Arrays To Functions• An array can be passed to a function as an argument.• While declaring a one dimensional array as a formal

argument, the array name is written with empty square brackets, the size of the array is not specified.– Example:

• void add ( int a[ ] ) {/* function definition */

}

Contents:When declaring function prototypes, if argument names are not included in function declaration, then an empty square brackets must be specified after argument data type.Example:

void add ( int [] );

83

Page 85: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 4.1: Introduction to Arrays

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

4.1_IntroductionToArrays.ppt

11Copyright © 2009 Accenture All Rights Reserved.

Example – Using Array

/* illustrate use of arrays*/

#include<stdio.h>

#define SIZE 5

void main(){

int num[5],i;

printf(“enter elements of the array”);

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

scanf(“%d”,&num[i]);

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

printf(“%d”,num[i]);

}

Enter elements of the array1 2 3 4 5

1 2 3 4 5

Output:

12Copyright © 2009 Accenture All Rights Reserved.

Character Arrays• Arrays whose elements are characters

• All strings end with null ('\0')

• Examples:• char charStr[] = "hello";

• char charStr[] = { 'h', 'e', 'l', 'l', 'o', '\0’ };

• Subscripting is the same as for a normal array • charStr[ 0 ] is 'h'

• charStr[ 2 ] is 'l’

84

Page 86: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 4.1: Introduction to Arrays

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

4.1_IntroductionToArrays.ppt

13Copyright © 2009 Accenture All Rights Reserved.

Character Arrays (continued)• Input from keyboard

– Example:• charStr1[ 10 ];

• scanf(“%s”,charStr1);

– Takes user input• Output to screen

– Example:• printf(“%s”,charstr1);

14Copyright © 2009 Accenture All Rights Reserved.

Character Array-Strings• String of characters are a form of data used in

programming for storing and manipulating text such as word, names and sentences.

• In C, a string is not a formal data type, but it is an array of type char.

• String is a series of characters terminated by a ‘\0’ (null) character.

• String variables are used to hold text data, which comprises of letters, numerals, punctuation marks and other symbols.

85

Page 87: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 4.1: Introduction to Arrays

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

4.1_IntroductionToArrays.ppt

15Copyright © 2009 Accenture All Rights Reserved.

Input/Output of Strings

Formatted output function. New line char (\n) is required to move to the next line.

printf()

Unformatted output function. Prints the string and puts the cursor on the next line.

puts()

Formatted input function. can read only single word at a time.

scanf()

Good for space management.

Unformatted input function. can read multiple word in a string (read sentences).

gets()

DescriptionString Functions

Input String

Output String

16Copyright © 2009 Accenture All Rights Reserved.

String - Example

/*program to Read a string from the keyboard and printing it*/

void main()

{

char fname[15];

printf(“ Enter the first name:”);

scanf(“%s”, fname);

printf(“Greetings %s”, fname);

}Enter the first name:JohnGreetings John

Sample Output

Sample Code

86

Page 88: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 4.1: Introduction to Arrays

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

4.1_IntroductionToArrays.ppt

17Copyright © 2009 Accenture All Rights Reserved.

String Library Functions (continued)

Returns str1strcat(str1,str2)

Returns an integerstrlen(string)

Returns str1strcpy(str1,str2)

Returns 0 if equal, otherwise numeric difference between first non-matching char.

strcmp(str1,str2)

DescriptionString Library Function

The library functions processes strings as complete entities, thus strings can be concatenated, compared and copied.

1. strlen(string) - returns length of the string an integer value.2. strcat(str1,str2) – appends str2 to str1 and returns str13. strcmp(str1,str2) – compares the two strings and if both strings are same

the returns 0 otherwise the numeric difference between the ASCII values of the first non-matching characters

4. strcpy(str1,str2) – copies str2 to str1 and returns str1

87

Page 89: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 4.1: Introduction to Arrays

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

4.1_IntroductionToArrays.ppt

18Copyright © 2009 Accenture All Rights Reserved.

Example- Using String Functionsvoid main( ){

char source1[]=”programming”; /*initialize two strings*/char source2[]=”techniques”;char target1[20],target2[20];int len1,diff1,diff2;len1=strlen(source1); /* use of strlen function*/strcpy(target1,source1); /*use of string copy function*/strcat(source1,source2); /* use strcat function to concatenate strings*/diff2=strcmp(source2,”techniques”);/* use string compare function to compare two strings*/

printf(”the length of source1 =%d”,len1);/*prints the length*/printf(“the target string is = %s”,target1); printf(“the concatenated string is =%s”,source1); /*prints the concatenated string*/printf(“output of comparing the strings is = %d %d”,diff2);

} The length of the source1=11The Target string is=programmingThe concatenated string is=programming techniquesOutput of comparing strings is=0

Output

19Copyright © 2009 Accenture All Rights Reserved.

Multi-Dimensional Arrays• Multi-dimensional arrays with rows and columns

– Like matrices, specify row then column

Row 0Row 1Row 2

Column 0 Column 1 Column 2 Column 3a[ 0 ][ 0 ]

a[ 1 ][ 0 ]

a[ 2 ][ 0 ]

a[ 0 ][ 1 ]

a[ 1 ][ 1 ]

a[ 2 ][ 1 ]

a[ 0 ][ 2 ]

a[ 1 ][ 2 ]

a[ 2 ][ 2 ]

a[ 0 ][ 3 ]

a[ 1 ][ 3 ]

a[ 2 ][ 3 ]

Row subscript

Array nameColumn subscript

Column 0 Column 1 Column 2 Column 3

88

Page 90: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 4.1: Introduction to Arrays

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

4.1_IntroductionToArrays.ppt

20Copyright © 2009 Accenture All Rights Reserved.

Multi-Dimensional Arrays (continued)• Initializing:

– int b[2][2] = {{1, 2}, {3, 4}};

• Initializers grouped by row in braces

– int b[2][2] = {{1}, {3, 4}};

1 2

3 4

1 0

3 4

89

Page 91: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 4.1: Introduction to Arrays

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

4.1_IntroductionToArrays.ppt

21Copyright © 2009 Accenture All Rights Reserved.

• Useful when replicating matrix-like data storage– They make data access easier for any data that can be

represented in a matrix format

• Useful when we want to store entire sentences as a character string– We can declare char [][]or char* []

Advantages of Multidimensional Array

Applications of Two multidimensional array:-A matrix can be represented in a two-dimensional Array.-In a Chess-Board each square on a board can be represented in a 2D matrix.-An entire statement can be stored in a two-dimensional character array.

90

Page 92: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 4.1: Introduction to Arrays

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

4.1_IntroductionToArrays.ppt

22Copyright © 2009 Accenture All Rights Reserved.

• Tasks– Hands on using arrays in C

• Input Documents– Module 3_activities.doc

Array - Activity

30 minutes

23Copyright © 2009 Accenture All Rights Reserved.

Key Points• An array is a sequence of either objects or primitives, all of

the same type and packaged together under one identifier name

• To refer to a particular element, specify the array name and position number: array [position]

• The first element in an array is at position zero: array [0]• There are three steps to creating an array:

– Declaration– Construction– Initialization

• Character arrays are arrays whose elements are characters• For multi-dimensional arrays, specify the row first and then

the column: array [row][column]

91

Page 93: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 4.2: Pointers

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

4.2_Pointers.ppt

Copyright © 2009 Accenture All Rights Reserved. Accenture, its logo, and Accenture High Performance Delivered are trademarks of Accenture.

Module 4.2 - Pointers

Programming Techniques

92

Page 94: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 4.2: Pointers

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

4.2_Pointers.ppt

Copyright © 2009 Accenture All Rights Reserved.

Contents• Introduction to Pointers• Pointer Declaration• Pointer Operators• Arrays and Pointers• Pointer Manipulations

93

Page 95: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 4.2: Pointers

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

4.2_Pointers.ppt

Copyright © 2009 Accenture All Rights Reserved.

Objectives

At the end of this section, you will be able to:• Identify a pointer, the address a pointer holds and the

value at the address held by the pointer• Utilize the indirection/dereference operator (*)• Implement an array of pointers • Understand the use of pointers in passing arguments to

functions

94

Page 96: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 4.2: Pointers

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

4.2_Pointers.ppt

Copyright © 2009 Accenture All Rights Reserved.

Introduction to Pointers

• A pointer is a variable which holds the address of an other variable of the same type. Pointer can also be defined as a programming language data type whose value refers directly to ("points to") another value stored elsewhere in the computer memory using its address

• A Pointer is a data element whose value is an address • Pointers are

– Powerful, but can be difficult to master– Simulate call-by-reference– Has close relationship with arrays and strings

Pointer is a variable containing the address of a byte in memory.

Pointers are play a key role in C, so if you want to use the C language fully you have to have a very good understanding of pointers. They have to become comfortable for you. The goal of this section and the next several that follow is to help you build a complete understanding of pointers and how C uses them.

A pointer is a programming language data type whose value refers directly to ("points to") another value stored elsewhere in the computer memory using its address

A Pointer is a data element whose value is an address.

Pointers :are Powerful, but can be difficult to masterCan Simulate call-by-reference Has close relationship with arrays and strings

95

Page 97: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 4.2: Pointers

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

4.2_Pointers.ppt

Copyright © 2009 Accenture All Rights Reserved.

• Why Pointers ?– At times, they are the only way to express a computation, and

partly because they usually lead to more compact and efficient code than can be obtained in other ways. If implemented with discipline, pointers can also be used to achieve clarity and simplicity

• Why not pointers?– Harder than average to understand– Error prone– Tend to be machine dependent– Not portable code

Pointers

C uses pointers in three different ways:

C uses pointers to create dynamic data structures -- data structures built up from blocks of memory allocated from the heap at run-time. C uses pointers to handle variable parameters passed to functions. Pointers in C provide an alternative way to access information stored in arrays.Pointer techniques are especially valuable when you work with strings. There is an intimate link between arrays and pointers in C. In some cases, programmers also use pointers because they make the code slightly more efficient.

96

Page 98: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 4.2: Pointers

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

4.2_Pointers.ppt

Copyright © 2009 Accenture All Rights Reserved.

Pointer Variable Declaration• Pointer variables

– Contain memory addresses as their values – Normal variables contain a specific value

(direct reference)– Pointers contain the memory address

of a variable that has a specific value (indirect reference)

• Indirection (*)– Referencing the value in memory a pointer

points to

count

7

7

countPtr

Notes:Pointers point to memory addresses, regardless of what value is stored there.

To access the value at the address to which they are pointing, programmers utilize the indirection operator (*).Explain with a sample code how to declare the pointer variable and how to access value stored in.

97

Page 99: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 4.2: Pointers

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

4.2_Pointers.ppt

Copyright © 2009 Accenture All Rights Reserved.

Pointer Variable Declaration (continued)• Pointer declarations

– * indicates variable is a pointerint *Ptr;

– Declares a pointer to an int; a pointer of type int *

– Each declared pointer requires its own asterisk– int *Ptr1, *Ptr2;

Notes:A common programmer convention that pointers are named with an initial p. Following this convention the pointer to the variable named myAge would be named pmyAge, and the pointer to variable named bigStorage would be pbigStorage.

When declaring variables, one can list the type (i.e., int) and then list variable names, and all of the listed variables will be of the type int. However, when declaring pointers, each listed pointer needs to have it’s own * preceding it’s name.

98

Page 100: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 4.2: Pointers

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

4.2_Pointers.ppt

Copyright © 2009 Accenture All Rights Reserved.

Pointer Variable Declaration (continued)• Can declare pointers to any data type• Pointer initialization

– Always initialize pointers to 0, NULL, or an address• 0 or NULL points to a “specific nothing”• Un-initialized pointers are called “wild pointers” and

are very dangerous in a program– They can cause serious errors!

Notes:Always initialize a pointer to an address, to 0 or to null. A pointer initialized to nothing is very dangerous in a program. A pointer initialized to a null or 0 at least points to a specific memory location, or a specific entity allocated as blank.

Note: An uninitialized pointer will not be guaranteed to be null. It will have Garbage. This scenario will lead to the Dangling Pointer. That's why all pointers MUST be initialized to 0 or NULL, else they will become WILD.

99

Page 101: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 4.2: Pointers

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

4.2_Pointers.ppt

Copyright © 2009 Accenture All Rights Reserved.

Pointer Operators - &The Address Operator & returns the address of its operand. For example:int y = 5;int *yPtr;yPtr = &y; //yPtr gets address of y

In this example, yPtr “points to” y

yPtr y

5

yptr

500000 600000

y

600000 5

address of y is value of yptr

Notes:The & operator returns the address of the location where the information is stored in memory, and does not return the value stored there.

100

Page 102: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 4.2: Pointers

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

4.2_Pointers.ppt

Copyright © 2009 Accenture All Rights Reserved.

Pointer Operators - *• The Indirection/Dereferencing Operator ( * ):

– Returns the value of what its operand points to*yPtr returns y (because yPtr points to y)

– Assigns a value to a location in memory*yPtr = 7; // changes y to 7

• The Dereference pointer (the operand of *) must be an lvalue (not a constant)

• * and & are inverses – they cancel each other out:*&myVar == myVar

and&*yPtr == yPtr

Note:* returns a value, or can be used to change a value stored in memory& returns a memory address

101

Page 103: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 4.2: Pointers

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

4.2_Pointers.ppt

Copyright © 2009 Accenture All Rights Reserved.

An Illustration

10integer variableintj

5integer variableinti

ValueDescriptionTypeName

Data Table

int i = 5, j = 10;

int *ptr;

int **pptr;

ptr = &i;

pptr = &ptr;

*ptr = 3;

**pptr = 7;

ptr = &j;

**pptr = 9;

*pptr = &i;

*ptr = -2;

Copyright © 2009 Accenture All Rights Reserved.

int i = 5, j = 10;

int *ptr; /* declare a pointer-to-integer variable */

int **pptr;

ptr = &i;

pptr = &ptr;

*ptr = 3;

**pptr = 7;

ptr = &j;

**pptr = 9;

*pptr = &i;

*ptr = -2;

10integer variableintj

integer pointer variableint *ptr

5integer variableinti

ValueDescriptionTypeName

Data Table

An Illustration

102

Page 104: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 4.2: Pointers

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

4.2_Pointers.ppt

Copyright © 2009 Accenture All Rights Reserved.

An Illustration

int i = 5, j = 10;

int *ptr;

int **pptr; /* declare a pointer-to-pointer-to-integer variable */

ptr = &i;

pptr = &ptr;

*ptr = 3;

**pptr = 7;

ptr = &j;

**pptr = 9;

*pptr = &i;

*ptr = -2;

10integer variableintj

integer pointer pointer variableint **pptr

integer pointer variableint *ptr

5integer variableinti

ValueDescriptionTypeName

Data Table

Double Indirection

Copyright © 2009 Accenture All Rights Reserved.

An Illustration• int i = 5, j = 10;• int *ptr; • int **pptr; • ptr = &i; /* store address-of i to ptr */• pptr = &ptr; • *ptr = 3;• **pptr = 7;• ptr = &j;• **pptr = 9;• *pptr = &i;• *ptr = -2;

10integer variableintj

5de-reference of ptrint*ptr

integer pointer pointer variableint **pptr

address of iinteger pointer variableint *ptr

5integer variableinti

ValueDescriptionTypeName

Data Table

103

Page 105: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 4.2: Pointers

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

4.2_Pointers.ppt

Copyright © 2009 Accenture All Rights Reserved.

An Illustration• int i = 5, j = 10;• int *ptr; • int **pptr; • ptr = &i; • pptr = &ptr; /* store address-of ptr to pptr */• *ptr = 3;• **pptr = 7;• ptr = &j;• **pptr = 9;• *pptr = &i;• *ptr = -2;

10integer variableintj

value of ptr(address of i)

de-reference of pptrint **pptr

address of ptrinteger pointer pointer variableint **pptr

address of iinteger pointer variableint *ptr

5integer variableinti

ValueDescriptionTypeName

Data Table

Copyright © 2009 Accenture All Rights Reserved.

An Illustration• int i = 5, j = 10;• int *ptr; • int **pptr; • ptr = &i; • pptr = &ptr; • *ptr = 3;• **pptr = 7;• ptr = &j;• **pptr = 9;• *pptr = &i;• *ptr = -2;

10integer variableintj

3de-reference of ptrint*ptr

address of ptrinteger pointer pointer variableint **pptr

address of iinteger pointer variableint *ptr

3integer variableinti

ValueDescriptionTypeName

Data Table

104

Page 106: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 4.2: Pointers

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

4.2_Pointers.ppt

Copyright © 2009 Accenture All Rights Reserved.

An Illustration• int i = 5, j = 10;• int *ptr; • int **pptr; • ptr = &i; • pptr = &ptr; • *ptr = 3;• **pptr = 7;• ptr = &j;• **pptr = 9;• *pptr = &i;• *ptr = -2;

10integer variableintj

7de-reference of de-reference of pptrint**pptr

address of ptrinteger pointer pointer variableint **pptr

address of iinteger pointer variableint *ptr

7integer variableinti

ValueDescriptionTypeName

Data Table

Copyright © 2009 Accenture All Rights Reserved.

An Illustration• int i = 5, j = 10;• int *ptr; • int **pptr; • ptr = &i; • pptr = &ptr; • *ptr = 3;• **pptr = 7;• ptr = &j;• **pptr = 9;• *pptr = &i;• *ptr = -2;

10integer variableintj

10de-reference of ptrint*ptr

address of ptrinteger pointer pointer variableint **pptr

address of jinteger pointer variableint *ptr

7integer variableinti

ValueDescriptionTypeName

Data Table

105

Page 107: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 4.2: Pointers

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

4.2_Pointers.ppt

Copyright © 2009 Accenture All Rights Reserved.

An Illustration• int i = 5, j = 10;• int *ptr; • int **pptr; • ptr = &i; • pptr = &ptr; • *ptr = 3;• **pptr = 7;• ptr = &j;• **pptr = 9;• *pptr = &i;• *ptr = -2;

9integer variableintj

9de-reference of de-reference of pptrint**pptr

address of ptrinteger pointer pointer variableint **pptr

address of jinteger pointer variableint *ptr

7integer variableinti

ValueDescriptionTypeName

Data Table

Copyright © 2009 Accenture All Rights Reserved.

An Illustration• int i = 5, j = 10;• int *ptr; • int **pptr; • ptr = &i; • pptr = &ptr; • *ptr = 3;• **pptr = 7;• ptr = &j;• **pptr = 9;• *pptr = &i;• *ptr = -2;

9integer variableintj

value of ptr(address of i)

de-reference of pptrint **pptr

address of ptrinteger pointer pointer variableint **pptr

address of iinteger pointer variableint *ptr

7integer variableinti

ValueDescriptionTypeName

Data Table

106

Page 108: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 4.2: Pointers

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

4.2_Pointers.ppt

Copyright © 2009 Accenture All Rights Reserved.

An Illustration• int i = 5, j = 10;• int *ptr; • int **pptr; • ptr = &i; • pptr = &ptr; • *ptr = 3;• **pptr = 7;• ptr = &j;• **pptr = 9;• *pptr = &i;• *ptr = -2;

9integer variableintj

-2de-reference of ptrint*ptr

address of ptrinteger pointer pointer variableint **pptr

address of iinteger pointer variableint *ptr

-2integer variableinti

ValueDescriptionTypeName

Data Table

Copyright © 2009 Accenture All Rights Reserved.

Arrays and Pointers• Arrays and pointers are closely related:

– An array name is like a constant pointer– Pointers can do array subscripting operations

• For Example:– Having declared an array b[5] and a pointer bPtr:

int b[5] = {1,2,3,4,5};int *bPtr = b;

• bPtr is equal to b• bPtr == b

• bptr is equal to the address of the first element of b• bPtr == &b[ 0 ]

107

Page 109: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 4.2: Pointers

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

4.2_Pointers.ppt

Copyright © 2009 Accenture All Rights Reserved.

Arrays and Pointers (continued)

• Accessing array elements with pointers– Element b[n] can be accessed by *(Ptr + n)

• Called pointer/offset notation

– Array itself can use pointer arithmetic• b[3] same as *(b + 3)

– Pointers can be subscripted (pointer/subscript notation)• bPtr[3] same as b[3]

Copyright © 2009 Accenture All Rights Reserved.

• Arrays can contain pointers– Commonly used to store an array of strings

• char *suit[4] = {"Hearts", "Diamonds", "Clubs", "Spades" };– Each element of a suit is a pointer to a char * (a string)– The strings are not in the array; only pointers to the strings

are in the array

Arrays of Pointers (continued)

108

Page 110: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 4.2: Pointers

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

4.2_Pointers.ppt

Copyright © 2009 Accenture All Rights Reserved.

Arrays of Pointers (continued)• Arrays can contain pointers

– suit array has a fixed size, but strings can be of any size

suit[3]

suit[2]

suit[1]

suit[0] ’H’ ’e’ ’a’ ’r’ ’t’ ’s’ ’\0’

’D’ ’i’ ’a’ ’m’ ’o’ ’n’ ’d’ ’s’ ’\0’

’C’ ’l’ ’u’ ’b’ ’s’ ’\0’

’S’ ’p’ ’a’ ’d’ ’e’ ’s’ ’\0’

Copyright © 2009 Accenture All Rights Reserved.

Operator - sizeof• sizeof operator

– Returns size of operand in bytes– Returns for arrays:

– ( size of 1 element ) * ( number of elements )• If sizeof( int ) returns 4 then

int myArray[ 10 ];printf(“%d”, sizeof( myArray ));

• will print 40

– Can be used with:• Variable names• Type names• Constant values

109

Page 111: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 4.2: Pointers

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

4.2_Pointers.ppt

Copyright © 2009 Accenture All Rights Reserved.

Pointer Manipulations – Pointer Arithmetic• Pointer arithmetic

– Increment/decrement pointer (++ or --)– Add/subtract an integer to/from a pointer (+ or +=, - or -=)– Pointers may be subtracted from each other– Pointer arithmetic is meaningless unless performed on a

pointer to an array

Example for pointer arithmetic.

int main(){

int j = 10;double k = 3.14;int *intPtr = &j ;double *doublePtr = &k ;

printf( “Int Value and Int memory location are %d, %d \n“, j, intPtr);printf( “Double Value and Double memory location are %d %d \n“ ,k, doublePtr );

++intPtr; ++doublePtr;

//Value of j remains the same but memory to which intPtr is pointing is changed.printf( “Int Value and Int memory location are %d, %d \n“, j, intPtr);//Value of k remains the same but memory to which doublePtr is pointing is changed.printf( “Double Value and Double memory location are %d %d \n“ ,k, doublePtr );

}

Why pointer arithmetic is meaningless unless performed on pointer to an array ?- When we declare int a = 10; int *aPtr = &a;- Now when we do ++aPtr; – there is no valid memory allocated to this new location. And we will be

pointing to a JUNK.

- But when we have int array[5]; int *arrayPtr = &a[0];- Now when we do ++arrayPtr; this pointer will now point to &a[1]. So, there is meaning to pointer

arithmetic only when we are using it with arrays.

110

Page 112: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 4.2: Pointers

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

4.2_Pointers.ppt

Copyright © 2009 Accenture All Rights Reserved.

Example on Pointer Manipulations• 5 element int array on a machine using 4 byte int

– vPtr points to first element v[ 0 ], at location 3000• vPtr = &v[ 0 ];

– vPtr += 2; sets vPtr to 3008 (3000 + 2 * 4)• vPtr points to v[ 2 ]

• Subtracting pointers– Returns number of elements between two addresses

• vPtr2 = v[ 2 ];vPtr = v[ 0 ];vPtr2 - vPtr is 2

Copyright © 2009 Accenture All Rights Reserved.

Pointer Arithmetic and Array

float a[4];

float *ptr;

ptr = &(a[2]);

*ptr = 3.14;

ptr++;

*ptr = 9.0;

ptr = ptr - 3;

*ptr = 6.0;

ptr += 2;

*ptr = 7.0;

?de-reference of float pointer variablefloat*ptr

float pointer variablefloat *ptr

?float array element (variable)floata[3]

?float array element (variable)floata[2]

?float array element (variable)floata[1]

?float array element (variable)floata[0]

ValueDescriptionTypeName

Data Table

111

Page 113: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 4.2: Pointers

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

4.2_Pointers.ppt

Copyright © 2009 Accenture All Rights Reserved.

• float a[4];• float *ptr;• ptr = &(a[2]);• *ptr = 3.14;• ptr++;• *ptr = 9.0;• ptr = ptr - 3;• *ptr = 6.0;• ptr += 2;• *ptr = 7.0;

Pointer Arithmetic and Array

?de-reference of float pointer variablefloat*ptr

address of a[2]float pointer variablefloat *ptr

?float array element (variable)floata[3]

?float array element (variable)floata[2]

?float array element (variable)floata[1]

?float array element (variable)floata[0]

ValueDescriptionTypeName

Data Table

Copyright © 2009 Accenture All Rights Reserved.

Pointer Arithmetic and Array• float a[4];• float *ptr;• ptr = &(a[2]);• *ptr = 3.14;• ptr++;• *ptr = 9.0;• ptr = ptr - 3;• *ptr = 6.0;• ptr += 2;• *ptr = 7.0;

3.14de-reference of float pointer variablefloat*ptr

address of a[2]float pointer variablefloat *ptr

?float array element (variable)floata[3]

3.14float array element (variable)floata[2]

?float array element (variable)floata[1]

?float array element (variable)floata[0]

ValueDescriptionTypeName

Data Table

112

Page 114: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 4.2: Pointers

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

4.2_Pointers.ppt

Copyright © 2009 Accenture All Rights Reserved.

• float a[4];• float *ptr;• ptr = &(a[2]);• *ptr = 3.14;• ptr++;• *ptr = 9.0;• ptr = ptr - 3;• *ptr = 6.0;• ptr += 2;• *ptr = 7.0;

Pointer Arithmetic and Array

?de-reference of float pointer variablefloat*ptr

address of a[3]float pointer variablefloat *ptr

?float array element (variable)floata[3]

3.14float array element (variable)floata[2]

?float array element (variable)floata[1]

?float array element (variable)floata[0]

ValueDescriptionTypeName

Data Table

Copyright © 2009 Accenture All Rights Reserved.

• float a[4];• float *ptr;• ptr = &(a[2]);• *ptr = 3.14;• ptr++;• *ptr = 9.0;• ptr = ptr - 3;• *ptr = 6.0;• ptr += 2;• *ptr = 7.0;

Pointer Arithmetic and Array

9.0de-reference of float pointer variablefloat*ptr

address of a[3]float pointer variablefloat *ptr

9.0float array element (variable)floata[3]

3.14float array element (variable)floata[2]

?float array element (variable)floata[1]

?float array element (variable)floata[0]

ValueDescriptionTypeName

Data Table

113

Page 115: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 4.2: Pointers

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

4.2_Pointers.ppt

Copyright © 2009 Accenture All Rights Reserved.

• float a[4];• float *ptr;• ptr = &(a[2]);• *ptr = 3.14;• ptr++;• *ptr = 9.0;• ptr = ptr - 3;• *ptr = 6.0;• ptr += 2;• *ptr = 7.0;

Pointer Arithmetic and Array

?de-reference of float pointer variablefloat*ptr

address of a[0]float pointer variablefloat *ptr

9.0float array element (variable)floata[3]

3.14float array element (variable)floata[2]

?float array element (variable)floata[1]

?float array element (variable)floata[0]

ValueDescriptionTypeName

Data Table

Copyright © 2009 Accenture All Rights Reserved.

• float a[4];• float *ptr;• ptr = &(a[2]);• *ptr = 3.14;• ptr++;• *ptr = 9.0;• ptr = ptr - 3;• *ptr = 6.0;• ptr += 2;• *ptr = 7.0;

Pointer Arithmetic and Array

6.0de-reference of float pointer variablefloat*ptr

address of a[0]float pointer variablefloat *ptr

9.0float array element (variable)floata[3]

3.14float array element (variable)floata[2]

?float array element (variable)floata[1]

6.0float array element (variable)floata[0]

ValueDescriptionTypeName

Data Table

114

Page 116: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 4.2: Pointers

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

4.2_Pointers.ppt

Copyright © 2009 Accenture All Rights Reserved.

• float a[4];• float *ptr;• ptr = &(a[2]);• *ptr = 3.14;• ptr++;• *ptr = 9.0;• ptr = ptr - 3;• *ptr = 6.0;• ptr += 2;• *ptr = 7.0;

Pointer Arithmetic and Array

3.14de-reference of float pointer variablefloat*ptr

address of a[2]float pointer variablefloat *ptr

9.0float array element (variable)floata[3]

3.14float array element (variable)floata[2]

?float array element (variable)floata[1]

6.0float array element (variable)floata[0]

ValueDescriptionTypeName

Data Table

Copyright © 2009 Accenture All Rights Reserved.

• float a[4];• float *ptr;• ptr = &(a[2]);• *ptr = 3.14;• ptr++;• *ptr = 9.0;• ptr = ptr - 3;• *ptr = 6.0;• ptr += 2;• *ptr = 7.0;

Pointer Arithmetic and Array

7.0de-reference of float pointer variablefloat*ptr

address of a[2]float pointer variablefloat *ptr

9.0float array element (variable)floata[3]

7.0float array element (variable)floata[2]

?float array element (variable)floata[1]

6.0float array element (variable)floata[0]

ValueDescriptionTypeName

Data Table

115

Page 117: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 4.2: Pointers

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

4.2_Pointers.ppt

Copyright © 2009 Accenture All Rights Reserved.

float a[4];float *ptr;ptr = &(a[2]);*ptr = 3.14;ptr++;*ptr = 9.0;ptr = ptr - 3;*ptr = 6.0;

ptr += 2;*ptr = 7.0;

Pointer Arithmetic and Array

• Type of a is float *• a[2] *(a + 2)

ptr = &(a[2])ptr = &(*(a + 2))ptr = a + 2

• a is a memory address constant• ptr is a pointer variable

116

Page 118: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 4.2: Pointers

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

4.2_Pointers.ppt

Copyright © 2009 Accenture All Rights Reserved.

• Modify behavior in argument passing• Pass By reference method

Pointers and functions

void f(int j)

{

j = 5;

}

void g()

{

int i = 3;

f(i);

}

void f(int *ptr)

{

*ptr = 5;

}

void g()

{

int i = 3;

f(&i);

}

i = 3 i = 5

The program segment on the left is demonstrating “pass by value”, i.e. the value, actually a copy, of the variable i is passed as argument to function f(). The other program shows you “pass by reference”. The address of the variable i is passed to f() instead, thus allowing us to modify the content stored in the variable.

117

Page 119: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 4.2: Pointers

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

4.2_Pointers.ppt

Copyright © 2009 Accenture All Rights Reserved.

Pointers - Activity

• Tasks– Hands on using pointers in C

• Input Documents– Module 3_activities.doc

30 minutes

Copyright © 2009 Accenture All Rights Reserved.

• Pointers should be used carefully, as they have potential to create serious memory problems that are difficult to locate.

• Pointers should always be initialized• Pointers to arrays point to the first element of the array by

default.• Pointers can be used to pass arguments to functions .• Avoid type casting• Use explicit pointer types rather than the default type

Key Points

118

Page 120: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 4.3: Memory Management

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

4.3_MemoryManagement.ppt

Copyright © 2009 Accenture All Rights Reserved. Accenture, its logo, and Accenture High Performance Delivered are trademarks of Accenture.

Module 4.3 Memory Management

Programming Techniques

2Copyright © 2009 Accenture All Rights Reserved.

Contents• Memory and Memory Management• Automatic Storage (“The Stack”)• Static Storage• Free Storage (“The Heap”)• Dynamic Memory Allocation• Memory Leaks and Dangling Pointers

119

Page 121: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 4.3: Memory Management

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

4.3_MemoryManagement.ppt

3Copyright © 2009 Accenture All Rights Reserved.

At the end of this section, you will be able to:• List the three main types of memory• Identify what program data is stored in each type of memory• Utilize the malloc and free functions to manage memory• Define memory leaks and dangling/stray pointers

Objectives

120

Page 122: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 4.3: Memory Management

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

4.3_MemoryManagement.ppt

4Copyright © 2009 Accenture All Rights Reserved.

Memory and Memory Management• C supports the following types of memory:

– Automatic Storage– Static Storage– Free Store (Dynamic Storage)

• The storage defers in terms of variable initialization and lifetime

Examples:

1. Automatic Storage.void myFunction(){

auto int x = 5; // x is the automatic variable.int y = 10; // y is also an automatic variable by definition./*The scope of x and y is confined to the myFunction() block. They are created when program enters the

function and destroyed when program leaves this function. So, their storage is temporary.*/

}2. Static Storage.

void myFunction(){

static int s = 5; // s is a static variable./*The scope of the s is confined to this function, but the life time is the entire life of the program. ie when

program starts running the first starts running, ALL static variable will be assigned the memory. It’s different from the auto variable when the memory is created only when program enters the function. The memory will be only be freed when program terminates.

*/}

3. Dynamic Storage.void myFunction(){

int *ptr = malloc(sizeof( int));/*The dynamic memory is the most confusing and the most difficult to master. This memory will be

created WHENEVER the program enters the for-loop, but it will not be destroyed in this case. This memory is accessible outside this function also, if we can return the ptr.

*/}

121

Page 123: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 4.3: Memory Management

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

4.3_MemoryManagement.ppt

5Copyright © 2009 Accenture All Rights Reserved.

Automatic Storage• This type of storage is also called stack memory• By default all variables defined without any specific keyword are

automatic variables also commonly called as local variables.• With automatic storage:

– When a program enters a function or block, automatic objects arecreated on stack memory.

– When the program exits the function or block, those automatic objects are destroyed/removed from the stack.

– Scope of these variables are Local to that particular function in which it is defined.

– Other Function in the program can’t access these Variables.• On each entry into a function or a block, a fresh set of that

function or block’s automatic objects is created. • The default value of automatic variables is indeterminate.

6Copyright © 2009 Accenture All Rights Reserved.

Automatic Storage (continued)• The following all have automatic storage:

– Local objects that are not explicitly declared static or extern

– Local objects that are declared auto or register– Function arguments

122

Page 124: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 4.3: Memory Management

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

4.3_MemoryManagement.ppt

7Copyright © 2009 Accenture All Rights Reserved.

Static Storage• Static storage means that the objects stay in the same

memory address throughout the duration of the program.• Every static object is constructed only once during the

lifetime of the program.• By default, static data is initialized to binary zeros.• The scope of an object that is declared static within a

function is restricted to that function.• Static variable is stored in data segment.

8Copyright © 2009 Accenture All Rights Reserved.

Static Storage (continued )• The following reside in static memory:

– Global objects– Static variables in functions

123

Page 125: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 4.3: Memory Management

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

4.3_MemoryManagement.ppt

9Copyright © 2009 Accenture All Rights Reserved.

Free Store• Free store memory, also called heap memory or dynamic memory, contains objects and variables created by the function malloc

• Objects and variables that are allocated on the free store:– Persist until they're explicitly released by a subsequent free

function– Result in memory leaks if there is a failure to call free

124

Page 126: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 4.3: Memory Management

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

4.3_MemoryManagement.ppt

10Copyright © 2009 Accenture All Rights Reserved.

Dynamic Memory Allocation• The malloc function is the basic function used to allocate

memory on the heap in C. Its prototype isvoid *malloc(size_t size) which allocates size bytes of memory. If the allocation succeeds, a pointer to the block of memory is returned. malloc returns a void pointer (void *), which indicates that it is a pointer to a region of unknown data type. This pointer is typically cast to a more specific pointer type by the programmer before being used.

• Allocates single block of memory.• Default value is some garbage value.

The standard method of creating an array of ten integers on the stack:int array[10];

But if we want to allocate the array dynamically we should write:#include <stdlib.h> int *ptr = malloc(sizeof(int) * 10); /* Allocates space for an array

with 10 elements of type int */if (ptr == NULL){exit(1); /* We couldn't allocate any memory, so exit */}/* allocation succeeded */

125

Page 127: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 4.3: Memory Management

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

4.3_MemoryManagement.ppt

11Copyright © 2009 Accenture All Rights Reserved.

Dynamic Memory Allocation (continued)• Memory allocated via malloc is persistent: it will continue to

exist until the program terminates or the memory is explicitly de-allocated by the programmer (that is, the block is said to be "freed"). This is achieved by use of the free function. Its prototype is

• void free (void *pointer) which releases the block of memory pointed to by pointer.

• Free de-allocates (i.e., releases) memory from the free store– The memory can then be reused by the system to allocate

other objects

12Copyright © 2009 Accenture All Rights Reserved.

Dynamic Memory Allocation (continued)• malloc returns a block of memory that is allocated for the

programmer to use, but is un-initialized. • An alternative is to use the calloc function, which allocates

memory and then initializes it. • Its prototype is

– void *calloc(size_t nelements, size_t bytes) • which allocates a region of memory large enough to hold n

elements of size bytes each. The allocated region is initialized to zero.

• Allocates multiple blocks of memory.• Default value is zero.

126

Page 128: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 4.3: Memory Management

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

4.3_MemoryManagement.ppt

13Copyright © 2009 Accenture All Rights Reserved.

Memory Leak• A memory leak is an error condition that is created when

an object is left on the heap with no pointer variable containing its address.

void myFunction()

{

int *arrayPtr = malloc (sizeof(int)*100);

// use the Array for the while

} // arrayPtr goes out of Scope

/*The actual allocated memory for the array is still left on the heap*/

The term “memory leak” is one of those strange programmer jokes. In a memory leak, the memory is being “used,” but there is no way of using or accessing the information stored at that memory location. The memory is then unavailable to actually be utilized. Thus it is as if memory has “leaked out of the computer”because it cannot be utilized by the program.

127

Page 129: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 4.3: Memory Management

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

4.3_MemoryManagement.ppt

14Copyright © 2009 Accenture All Rights Reserved.

Dangling Pointer• A dangling pointer is created when you delete the pointer’s

stored information and then try to use the pointer. The pointer no longer points to valid storage and may corrupt the program's data.

float *floatPtr = malloc(sizeof(float));

*floatPtr = 3.14;

.

.

free (floatPtr); //now flatPtr points nowhere

.

.

*floatPtr = 4.2 //Error!

A dangling pointer is a very serious memory problem that should be avoided if at all possible. It does more than just limit the functioning of the computer – it can actually corrupt the data of the already-run portion of the program.

128

Page 130: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 4.3: Memory Management

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

4.3_MemoryManagement.ppt

15Copyright © 2009 Accenture All Rights Reserved.

Dynamic Memory – Points to Note• The problems related to dynamic memory (free store) are

among the most frequent and most difficult to debug.• Always make sure that you have a valid memory pointer or

else it will lead to the well known problem of a segmentation fault/core dump.

• Dynamic memory is taken up by the developer, and it is a developer’s duty to return it back.

• As there is no built-in garbage collector, C programmers must be very careful with dynamic memory.

Garbage is a dump of unused memory Always make sure,

the pointer in linked lists are freed in the right order? -Write routines to keep track of pointer allocations e.g. safe_calloc()If the program allocates a reserve parachute of memory so that it can shut down gracefully if it runs out of memory – Allocate a reserve parachute of memory

129

Page 131: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 4.3: Memory Management

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

4.3_MemoryManagement.ppt

16Copyright © 2009 Accenture All Rights Reserved.

Key Points• Three types of memory are Automatic Storage, Static

Storage, and Free Storage.– Automatic storage creates and destroys objects automatically

at the beginning and end, respectively, of a function or block.– Static storage contains the memory of the object throughout

the duration of the program.– Free storage contains the memory of objects until they are

explicitly deleted.• Use malloc,calloc and free functions to allocate

memory and deallocate memory.• Allocate memory very carefully to avoid dangling pointers

and memory leaks

130

Page 132: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 4.4: Introduction to Structures and Unions

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

4.4_IntroductionToStructures.ppt

Copyright © 2009 Accenture All Rights Reserved. Accenture, its logo, and Accenture High Performance Delivered are trademarks of Accenture.

Programming Techniques

Module 4.4: Introduction To Structures And Unions

2Copyright © 2009 Accenture All Rights Reserved.

Contents• Defining Structures• Declaring Structures• Defining Unions • Declaring Unions

131

Page 133: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 4.4: Introduction to Structures and Unions

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

4.4_IntroductionToStructures.ppt

3Copyright © 2009 Accenture All Rights Reserved.

Objectives

At the end of this section, you should be able to:• Define and declare Structures • Define and declare Unions• Generate code with the appropriate syntax for creating a

union, and a structure.

132

Page 134: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 4.4: Introduction to Structures and Unions

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

4.4_IntroductionToStructures.ppt

4Copyright © 2009 Accenture All Rights Reserved.

• C allows the programmer to create user defined data types using fundamental data types

• Structures and unions are user defined data types– They are collections of variables referred to by a single name– The variables can be of different data types

• Structures and Unions provide an easier means of keeping related information together

• Structures are generally used to represent real world entities, which is not possible with the fundamental data types e.g.: To represent a BOOK Entity , we need a combination of– character array to store Name– float variable to store Price– integer variable to store the Version & so on.

Structures

C allows a new data type to be created using existing data types. This is known as a user defined data type. It can be achieved using structures, unions and enumerated lists.

A structure is a collection of values of different data type. It is similar to an array, but the data that it stores is of different data types.

A structure is a collection of related elements, possibly of different data types, having a single referencing name. Each element (member) in a structure is called a field of the structure.

Structures and unions allow joining of simple variables together to form complex structures

133

Page 135: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 4.4: Introduction to Structures and Unions

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

4.4_IntroductionToStructures.ppt

5Copyright © 2009 Accenture All Rights Reserved.

• struct is the keyword used to define a structure• The complier allocates memory to accommodate all the

elements of a structure• Structure definition forms a structure template

– The templates are used to create structure variables

• Elements of a structure can be referred to by using a special operator called the . (dot) operator

• The special operator -> (called a “points to” operator or the “arrow” operator) is used to access structure elements through a pointer

Structures (continued)

6Copyright © 2009 Accenture All Rights Reserved.

Defining and Declaring a Structure

struct Person{ /* Beginning of structure template*/

int Age;int Height, Weight;char Name[50];

} Member; /* End of structure template*/

main(){

struct Person Father;

Father. Age=50;

scanf(“%d”,&member.Height);/* Continues the program */

}

Structure templatedefining structure

Use of .(dot) operator:

Assigning value to an element of a structure variable

Reading value to an element of a structure variable

Structure variableDeclaring a variable

134

Page 136: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 4.4: Introduction to Structures and Unions

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

4.4_IntroductionToStructures.ppt

7Copyright © 2009 Accenture All Rights Reserved.

Unions• A union is a type of user-defined data• union is the keyword used to define a union• The process for declaring and defining union variables is

similar to that of declaring and defining a structure• Elements of the union share common memory and only

one element is accessed at a given point of time• It requires enough storage space to hold the largest

element from its list of elements• Union is useful when it is combined together with

structures

Union allows the same portion of memory to be shared by different data types, since they share the same memory location. Its declaration is similar to structures, but the functionality is different. Unions allocate only enough memory to accommodate the largest data member.Unions are mainly used when only one data member needs to be chosen to store a value or access the value which is already stored.A union is most useful when it is combined together with structures – since it allows one piece of data to be accessed at a time.Example:

In real world if a person wants to have a new banking account they have to provide all the personal details with either the company ID or the social security number.

All the compulsory fields are part of a structure.Company id and social security number can be stored in a union and accessed.

135

Page 137: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 4.4: Introduction to Structures and Unions

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

4.4_IntroductionToStructures.ppt

8Copyright © 2009 Accenture All Rights Reserved.

Defining and Declaring a Union

union PersonalData

{ /* Beginning of union template */

char socialSecurityNumber[15];char empID[10];

} Member; /* End of Union template */

main(){

union PersonData Person;

Person.empID=“1020345”;

scanf(“%s”,Member.empID);

}

Union templatedefining union

Union VariableDeclaring a Variable

Use of .(dot) operator:

Assigning value to an element of a union variable

Reading value to an element of a union variable

136

Page 138: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 4.4: Introduction to Structures and Unions

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

4.4_IntroductionToStructures.ppt

9Copyright © 2009 Accenture All Rights Reserved.

Defining and Declaring a Union (continued)

union PersonalData

{ // Beginning of union template

char socialSecurityNumber[15];char empID[10];

} Member; // End of Union template

main(){

union PersonData Person;

Person.empID=“1020345”;

// Continue the program

}

Name of the new data type

Name of union variables. Multiple variables can be declared in this way

• Only one element can hold a value A variable of union type can hold one value of any type declared in the union

In the above example memory is allocated to socialSecurityNumber since it needs the largest amount of memory compared to all other data members or elements.

One main use of union is when it is used with structuresExample : struct BookDet{

char BookName[50]; char author[50]; union {

float dollars;int Euro;

};}

Since the name of the union is not specified in the above example, it is known as Anonymous Union.

137

Page 139: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 4.4: Introduction to Structures and Unions

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

4.4_IntroductionToStructures.ppt

10Copyright © 2009 Accenture All Rights Reserved.

Difference - Structure and Union

Allocates memory only to the largest element of the union

Memory is separately allocated for each data member of the structure

uses union keyword to define a union

uses struct keyword to define a structure

UnionsStructures

Unions allocate only enough memory to accommodate the largest data member.Unions allow a single portion of memory to be shared by different data types, and they all share the same memory location. Its declaration is similar to structures, but the functionality is different.It is mainly used only when one data member will be chosen to store a value or to access the value already stored.

138

Page 140: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 4.4: Introduction to Structures and Unions

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

4.4_IntroductionToStructures.ppt

11Copyright © 2009 Accenture All Rights Reserved.

Structures & Unions - Activity

• Tasks– Hands on using Structures and Unions in C

• Input Documents– Module 3_activities.doc

30 minutes

12Copyright © 2009 Accenture All Rights Reserved.

Key Points• Struct, union keywords are used to declare a user defined

data type• Struct and union have groups of variables referred to by a

single name• .(dot) or -> operators are used to connect structure

variables with structure elements

139

Page 141: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 4.5: Coding Conventions

Copyright © 2009 Accenture All Rights Reserved.

4.5_CodingConventions.ppt

Copyright © 2009 Accenture All Rights Reserved. Accenture, its logo, and Accenture High Performance Delivered are trademarks of Accenture.

Programming Techniques

4.5 Coding Conventions

2Copyright © 2009 Accenture All Rights Reserved.

Contents• Coding Conventions• Variable Declaration• Best Practices

– Naming Variables– Statements – if-else– switch() – while()– break & continue– Naming Functions– Arrays

• Caution when using Loops

140

Page 142: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 4.5: Coding Conventions

Copyright © 2009 Accenture All Rights Reserved.

4.5_CodingConventions.ppt

3Copyright © 2009 Accenture All Rights Reserved.

Objectives

At the end of this section, you should be able to:• Using comments• How to declare meaningful variables and use them• Using coding standards to declare variables and function

names• Best practices when using

– If– Switch– While– Array– Pointers

141

Page 143: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 4.5: Coding Conventions

Copyright © 2009 Accenture All Rights Reserved.

4.5_CodingConventions.ppt

4Copyright © 2009 Accenture All Rights Reserved.

• Comment Block – The comment block in a header file describes the purpose

and maintenance history of the file. – The comment block in a source file describes the purpose

and maintenance history of the file. – Each function (excluding Get and Set access functions and

Operators) must have a header that includes the following elements: • Name• Description• Parameters• Return• Side Effects

Coding Conventions: Best Practices

Explanation to the function elements are as given below:NAME - Name of the function. DESCRIPTION - Describes the purpose, usage and other important information

concerning this function. Any precondition should be specified here. Note: Do not describe how the function does its job. That's what the source code is for.

PARAMETERS - A list of each of the parameter names and a brief description of that parameter. The name of the parameter should be followed by one of three.

RETURN - The type returned and a brief description of that object. Include any requirement for this return type (e.g., must release the memory).

SIDE EFFECTS - Anything that might happen that would not normally be expected by a user.

142

Page 144: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 4.5: Coding Conventions

Copyright © 2009 Accenture All Rights Reserved.

4.5_CodingConventions.ppt

5Copyright © 2009 Accenture All Rights Reserved.

Declarations:• One declaration per line is recommended since it

encourages commenting. • Please Note:

– int level; /* indentation level */– int size; /* size of table is preferred over */– int level, size; /*Do not put different types on the same line*/

• For example:– int foo, fooarray[]; /* WRONG! */

• Never put two different types together– char desig; int appraisals[3]; /* WRONG! */

Variable Declaration: Best Practices

The examples above use one space between the type and the identifier.Another acceptable alternative is to use tabs, e.g.:

•int level; // indentation level •int size; // size of table Object currentEntry; •Try to initialize local variables where they're declared. The only reason not to initialize a variable where it's declared is if the initial value depends on some computation occurring first.

143

Page 145: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 4.5: Coding Conventions

Copyright © 2009 Accenture All Rights Reserved.

4.5_CodingConventions.ppt

6Copyright © 2009 Accenture All Rights Reserved.

Naming Variables : Best practice

Variable names:• Often use “camel notation” - the first word is in lower case

letters, and the second and all subsequent words begin with a capital letter:– myVariable, heightOfRectangle, areaOfField,colorOfPaint

• In myVariable, the capital letter looks like a camel hump in the middle of the word, hence the name

• Another notation is called “underscore notation”:– my_variable, height_of_rectangle, area_of_field

• Avoid Hungarian notation, as C is strongly typed.– Might still use p before pointers, r before references

7Copyright © 2009 Accenture All Rights Reserved.

Naming Variables : Best practices(continued)• Variable name should fully and accurately describe what the

variable representschar Grade; /*Captures the Grade of the Employee */

• If computed values are qualifiers, the variable should indicate.int BoolFlag; /*Captures the State of the

identification operation*/

144

Page 146: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 4.5: Coding Conventions

Copyright © 2009 Accenture All Rights Reserved.

4.5_CodingConventions.ppt

8Copyright © 2009 Accenture All Rights Reserved.

Naming Variables : Best Practices(continued)• Naming convention should distinguish among local,

functions and global data • Always avoid variable names that conflict with standard

library-routine names or predefined variable nameschar Grade; /*Captures the Grade of the

Employee in main function*/

char Valid_Grade; /*Captures the Grade of

the Employee in Valid function*/

char G_Grade; /*Captures the Grade of the

Employee as Global*/

9Copyright © 2009 Accenture All Rights Reserved.

Naming Variables : Best Practices(continued)• While abbreviating variable names, the name should not

be abbreviated to save only one character. • Don’t misspell the names while abbreviating and ensure

abbreviation is not making names completely arbitrary.• Ensure, the abbreviation doesn’t cause names that are

different by only one or two characters• Maintain consistency in abbreviations.

int boolFlg ; /*Avoid this abbreviation*/

int BoolFlag; /*Maintain Consistency with the

keyword “Bool” while declaring variables

working on true or false state*/

145

Page 147: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 4.5: Coding Conventions

Copyright © 2009 Accenture All Rights Reserved.

4.5_CodingConventions.ppt

10Copyright © 2009 Accenture All Rights Reserved.

Naming Variables : Best Practices(continued)• Avoid names that could be mispronounced, mislead or

hold similar meaning/sound.

char StrCite[20];

char StrSite[10];

• Avoid names that use numerals.

int num1,num2,num3; /* Avoid*/

int First, Second, Third; /*Advisable*/

11Copyright © 2009 Accenture All Rights Reserved.

Statements - Best Practices

StatementsEach line should contain only one statement.

Example:argv++; /* Correct */

argc--; /* Correct */

argv++; argc--; /* AVOID! */

146

Page 148: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 4.5: Coding Conventions

Copyright © 2009 Accenture All Rights Reserved.

4.5_CodingConventions.ppt

12Copyright © 2009 Accenture All Rights Reserved.

Statements - Best Practices (continued)

Line Length• Avoid lines longer than 80 characters. They are not

handled well by many terminals and tools.

Variable Assignments• Avoid assigning several variables to the same value in a

single statement. It is hard to read. – Example:

choice = empcode = 'c'; /* AVOID*/

147

Page 149: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 4.5: Coding Conventions

Copyright © 2009 Accenture All Rights Reserved.

4.5_CodingConventions.ppt

13Copyright © 2009 Accenture All Rights Reserved.

if – else : Best Practices• Check if all conditions are covered. Ensure the tests

branch correctly on equalityif (average<60)

grade='C';

else if (average<70 && average>60)

grade='B';

• Don’t avoid the else clause present in code. Ensure the correctness of the else clause i.e. check that the if and else clauses used correctly

Do the if tests branch correctly on equality? : Using > instead of >= or < instead of <= is analogous to making an off-by-one error in accessing an array or computing a loop index. Is the else clause present and documented? : Make sure, you have the else clause to take care of the if conditionsIs the else clause correct? : While testing your code, you might think that the main clause, the if, is all that needs to be tested. Test the else clause also

Are the if and else clauses used correctly – not reversed?Does the normal case follow the if rather than the else? : Put the case you normally expect to process first. This is in line with the general principle of putting code that results from a decision as close as possible to the decision

148

Page 150: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 4.5: Coding Conventions

Copyright © 2009 Accenture All Rights Reserved.

4.5_CodingConventions.ppt

14Copyright © 2009 Accenture All Rights Reserved.

if – else : Best Practices (continued)OpenFile (InputFile,

Status){if (Status==Error){ErrorType = FileOpenError ;}else {ReadFile (InputFile,

FileData,Status)if (Status = =Success){SummarizeFileData(FileData,

SummaryData, Status);if (Status = = Error)ErrorType =

DataSummaryError;

else {PrintSummary(SummarData)SaveSummaryData(SummaryData,

Status);if (Status= =Error)ErrorType = SummarySaveError;else{UpdateAllAccounts();EraseUndoFile();ErrorType =None;}else{ErrorType = FileReadError;}

Bad Practice

Bad Practice : OpenFile(InputFile, Status){if (Status= =Error){ErrorType=FileOpenError ;}else {ReadFile(InputFile, FileData,Status)if (Status = =Success){SummarizeFileData(FileData, SummaryData, Status)if (Status = = Error)ErrorType=DataSummaryErrorelse{PrintSummary(SummarData)SaveSummaryData(SummaryData, Status)if (Status= =Error)ErrorType=SummarySaveErrorelse{UpdateAllAccounts();EraseUndoFile();ErrorType=None;}else{ErrorType=FileReadError;}

149

Page 151: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 4.5: Coding Conventions

Copyright © 2009 Accenture All Rights Reserved.

4.5_CodingConventions.ppt

15Copyright © 2009 Accenture All Rights Reserved.

OpenFile (InputFile, Status){ if (Status ! =Error){ReadFile (InputFile,

FileData,Status);if (Status ==Success){SummarizeFileData(FileData,

SummaryData, Status);if (Status ! = Error){PrintSummary (SummaryData);SaveSummaryData(SummaryData,

Status);if (Status != Error){UpdateAllAccounts();EraseUndoFile();ErrorType=None;}

else{

ErrorType=SummarySaveError;}else

{ErrorType=DataSummaryError;

}else{ErrorType=FileReadError;

}else{

ErrorType=FileOpenError ;}

if – else : Best Practices(continued)

Good Practice

150

Page 152: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 4.5: Coding Conventions

Copyright © 2009 Accenture All Rights Reserved.

4.5_CodingConventions.ppt

16Copyright © 2009 Accenture All Rights Reserved.

switch : Best Practices• Always order cases meaningfully• Keep the actions for each case simple – call other routines

if necessary.• Use the default clause to detect and report unexpected

cases• Use break to end each case statement• Don’t assign or create variables specially for a switch

Always order cases meaningfully : Keep cases in a sequenceKeep the actions for each case simple – call other routines if necessary. : don’t keep much code with in a switch. Break it into routines and call these routines under each casesUse the default clause to detect and report unexpected cases : Keep the default cause present in a switch statement which will record all the unexpected casesUse break to end each case statement : Use break statement in switchDon’t use the dummy variable to be able to use the case statement : Work on actual variables, don’t assign or create variables specially for switch

151

Page 153: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 4.5: Coding Conventions

Copyright © 2009 Accenture All Rights Reserved.

4.5_CodingConventions.ppt

17Copyright © 2009 Accenture All Rights Reserved.

if – else & switch : Best Practices• A switch statement should be used for simple data that’s

easily categorized. If your data isn't simple, use if-else if-else.

152

Page 154: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 4.5: Coding Conventions

Copyright © 2009 Accenture All Rights Reserved.

4.5_CodingConventions.ppt

18Copyright © 2009 Accenture All Rights Reserved.

if – else & switch : Best Practices(continued)action = UserCommand[1];

switch(action)

{

case ‘c’: copy();

case ‘d’: delete();

case ‘f’: format();

case ‘h’: help();

default : printf(“\n Invalid Option”);

}

if (strcmp ( UserCommand, “copy”)==0)copy();else if (strcmp ( UserCommand, “delete”)==0)delete();else if (strcmp ( UserCommand, “format”)==0)format();else if (stcmp (UserCommand, “help”)==0)help();elseprintf (“\n Invalid Option”);

Bad Practice

Good Practice

A case statement should be used for simple data that’s easily categorized. If your data isn't simple, use chains of if-then-else's instead. Phony variables are confusing, and you should avoid them.

The variable that controls the case statement is action. In this case, action is created by peeling off the first character of the UserCommand, string, a string that was entered by user. This is a trouble making code. Here, if the user types “copy”the case statement peels off the first “c” and correctly calls the copy(). However, if the user enters “clambake” or “Cement” or “cellulite” etc the case statement peels off the “c” and calls the copy() and the test for an erroneous command in the case statements ‘else’ clause wont work very well because it will miss only erroneous first letter rather than erroneous commands.

153

Page 155: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 4.5: Coding Conventions

Copyright © 2009 Accenture All Rights Reserved.

4.5_CodingConventions.ppt

19Copyright © 2009 Accenture All Rights Reserved.

Caution when using Loops

Word of Caution• Enter the loop from one location only• Put initialization code directly before the loop• Avoid empty loops• Keep the loop housekeeping chores at either the beginning

or the end of the loop• Assure yourself that the loop ends• Make loop-termination conditions obvious• Avoid code that depends on the loop index’s final value

Example on loop termination condition being obvious:float x = 0.0;for (x=0.1;x != 1.1; x+= 0.1) {

printf("x = %.2f\n", x);}

This code will work with some systems; whereas in some systems it will never terminate. Since the condition checks for inequality and the way the floating variables are treated is different for different systems.This code will work fine if the condition would have been a comparison condition like > or < instead of !.

154

Page 156: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 4.5: Coding Conventions

Copyright © 2009 Accenture All Rights Reserved.

4.5_CodingConventions.ppt

20Copyright © 2009 Accenture All Rights Reserved.

Loop : Best Practices• Always enter the loop from one location only

goto start;

while (expression)

{

/* statements*/start:

/* statements*/

}

• Put initialization code directly before the loop & Assure yourself that the loop ends.

• Avoid code that depends on the loop index’s final value. Avoid empty loop.

for (count=0;count<index; count++); // Avoid

Always enter the loop from one location only : Dont jump in a loop with a gotostatementPut initialization code directly before the loop & Assure yourself that the loop ends. :

Avoid code that depends on the loop index’s final value. Avoid empty loop.

155

Page 157: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 4.5: Coding Conventions

Copyright © 2009 Accenture All Rights Reserved.

4.5_CodingConventions.ppt

21Copyright © 2009 Accenture All Rights Reserved.

Best Practices : LoopExample : WhileAn example of duplicated code that will break down under maintenance

Score=0;GetNextRating (&RatingIncrement);Rating=Rating + RatingIncrement;while (Score < TargetScore && RatingIncrement !=0){

GentNextScore (&ScoreIncrement);Score=Score + ScoreIncrement;GetNextRating (&RatingIncrement);Rating=Rating + RatingIncrement;

}

Check if the duplication of code can be avoided with some other technique.

156

Page 158: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 4.5: Coding Conventions

Copyright © 2009 Accenture All Rights Reserved.

4.5_CodingConventions.ppt

22Copyright © 2009 Accenture All Rights Reserved.

while()

/* Below given code Computes scores and ratings. The loop uses a TRUE macro and a break statement to follow a loop-with-exit loop. */

Score=0;while (TRUE){

GetNextRating (&RatingIncrement);Rating = Rating + RatingIncrement;

if (!(Score<TargetScore && RatingIncrement !=0))break;

GetNextScore (&ScoreIncrement);Score = Score + ScoreIncrement;

}

Example to illustrate to avoid the duplication of code :

The while (TRUE) loop is equivalent to for(;;)

157

Page 159: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 4.5: Coding Conventions

Copyright © 2009 Accenture All Rights Reserved.

4.5_CodingConventions.ppt

23Copyright © 2009 Accenture All Rights Reserved.

break & continue : Best Practices• If you cant defend a break or a continue, don’t use it.• Be careful of a loop with a lot of breaks scattered through

it.• Avoid using goto statement • If you use a goto to implement break, go to the statement

immediately following the loop.• Use continue for tests at the beginning of a loop

If you use a goto to implement break, go to the statement immediately following the loop. Ie., do not move back to the beginning of the program

158

Page 160: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 4.5: Coding Conventions

Copyright © 2009 Accenture All Rights Reserved.

4.5_CodingConventions.ppt

24Copyright © 2009 Accenture All Rights Reserved.

Naming Functions : Best Practices• Function name should begin with a capital letter

• For a function name, use a strong verb followed by an object:

– PrintReport(), CheckOrderInfo(), ShowResult()…

• It should be long enough to be descriptive

• For a function name, use a description of the return value:

– NextCutomerId(), CurrentPenColor(),….

• Avoid meaningless or wishy-washy verbs

– “DealWithOutput()” (a wishy-washy verb) can be replace by “FormatAndPrintOutput()”

What is most important is that the naming convention should be consistent across the application.

159

Page 161: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 4.5: Coding Conventions

Copyright © 2009 Accenture All Rights Reserved.

4.5_CodingConventions.ppt

25Copyright © 2009 Accenture All Rights Reserved.

Naming Functions : Best Practices• Describe everything the function does

– ComputerReportTotals() = not an adequate name

– ComputerReportTotalsAndSetPrintingReadyVar() = too long and silly

– An average length of 20 to 35 characters

• Establish Conventions for common operations

– Prefix “Get” for input

• e.g GetInputChar()

• Pick a notation style, and use it consistently so that others can read and understand your coding

160

Page 162: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 4.5: Coding Conventions

Copyright © 2009 Accenture All Rights Reserved.

4.5_CodingConventions.ppt

26Copyright © 2009 Accenture All Rights Reserved.

Arrays : Best Practices• Make sure that all array indexes are within the bounds of

the array

int index=11;

int array[10];

printf(“%d”,array[index]);

• Arrays are of sequential structures• Check the end points of arrays

Make sure that all array indexes are within the bounds of the array : Array elements can be accessed randomly; the problem arises when a program tries to access an array element that’s out of bounds. This then results in unexpected errors.Think of arrays as sequential structures : Although, we can access array elements randomly this results in undisciplined, error prone and hard to prove correct correctcodes.Check the end points of arrays : check the end points of arrays, make sure the code is not making an off-by-one error.

161

Page 163: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 4.5: Coding Conventions

Copyright © 2009 Accenture All Rights Reserved.

4.5_CodingConventions.ppt

27Copyright © 2009 Accenture All Rights Reserved.

Arrays : Best Practices(continued)• If an array is multidimensional, make sure its subscripts are

used in the correct orderArray[i,j];

Array[j,i];

• Watch out for index cross talk– While we are using nested loops, its easy to mis-type Array[ j ]

when we mean Array[ i ]. Switching loop indexes is called “index cross talk”

• Throw in an extra element at the end of an array – If the array access is off by one and you write beyond the end

of an array, it can cause a serious error

If an array is multidimensional, make sure its subscripts are used in the correct order : Common & easy mistakes are giving indexes in wrong order.Watch out for index cross talk : While we are using nested loops, its easy to write Array[j] when we mean Array[i]. Switching loop indexes is called “index cross talk”Throw in an extra element at the end of an array : This is off-by-one error. If the array access is off by one and you write beyond the end of an array, it can cause a serious error

162

Page 164: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 4.5: Coding Conventions

Copyright © 2009 Accenture All Rights Reserved.

4.5_CodingConventions.ppt

28Copyright © 2009 Accenture All Rights Reserved.

Best Practices : Pointers• If the pointer operations are isolated in functions - Isolate

pointer operations in routines• If the pointer references valid, or could the pointer be

dangling - check pointer before using them• If the code checks pointer for validity before using them -

Check the variable referenced by the pointer before using it.

• If the variable that the pointer references checked for validity before its used

If the pointer operations are isolated in functions - Isolate pointer operations in routines : Suppose we are using a linked list in several places in a program. Rather than traversing the list manually each place its used, write access routines such as NextLink(), PreviousLink(), etc. By minimizing the number of places in which pointer are accessed we minimize the possibility if making careless mistakes that spread throughout the code and may take forever to find it. Writing functions for pointer allocation is another way to centralize the control over dataIf the pointer references valid, or could the pointer be dangling - check pointer before using them : Before using a pointer in a critical part of the code, make sure the memory location it points to is reasonable. Example : If we expect memory locations to be between StartData & EndData, we should view a pointer that points before StartData or After EndData suspiciously. We have to determine the values of StartData & EndData. This can be done automatically if you use pointers through access routines rather than manipulating them directly.If the code checks pointer for validity before using them - Check the variable referenced by the pointer before using it.If the variable that the pointer references checked for validity before its used

163

Page 165: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 4.5: Coding Conventions

Copyright © 2009 Accenture All Rights Reserved.

4.5_CodingConventions.ppt

29Copyright © 2009 Accenture All Rights Reserved.

Best Practices : Pointers (contd..)(1 of 2)• If the use of tag fields to check for corrupted memory is

done• If explicitly redundancies are added• Set pointer to NULL after freeing or disposing of them• If the code uses all the pointer variables needed for the

sake of readability - use extra pointer variable for clarity. Simplify complicated pointer expressions

• Are pointers used only as a last resort, when no other method is available? – Use nonpointer techniques

If the use of tag fields to check for corrupted memory is done : A tag field is field you add to a structure solely for the purpose of error checking. When you allocate a variable, put the value that should remain unchanged into its tag field. When you use the structure, check the tag field's value. If the tag field doesn’t have the expected value, the data has been corrupted. One should use the tag variable before disposing of the variable. A corrupted tag would then tell you that sometime during the life of that variable its contents were corrupted. The more often you check the tag field, however the close to the root of the problem you will detect the corruption.

If explicitly redundancies are added : It is an alternative to use of tag field, i.e. use a certain fields twice. If the data in the redundant field doest match you know memory has been corrupted. This can result in a lot of overhead if you manipulate pointer directly. If you isolate pointer operations in routine, however it adds duplicate code in only a few places.

164

Page 166: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 4.5: Coding Conventions

Copyright © 2009 Accenture All Rights Reserved.

4.5_CodingConventions.ppt

30Copyright © 2009 Accenture All Rights Reserved.

Best Practices : Pointers (contd..)(2 of 2)• If the use of tag fields to check for corrupted memory is

done• If explicitly redundancies are added• Set pointer to NULL after freeing or disposing of them• If the code uses all the pointer variables needed for the

sake of readability - use extra pointer variable for clarity. Simplify complicated pointer expressions

• Are pointers used only as a last resort, when no other method is available? – Use nonpointer techniques

Set pointer to NULL after freeing or disposing of them : Dangling pointers is a common type of pointer error-using a pointer that had been freed. Pointer errors are hard to detect as the error doesn’t produce any symptoms. By setting pointers to NULL after freeing them, we don’t change the fact that we can read data pointed to by a dangling pointer. But we do ensure that writing data to a dangling pointer produces and error. It will probably be an ugly, nasty and disaster error but at least we can find it instead of someone else finding it.

If the code uses all the pointer variables needed for the sake of readability - use extra pointer variable for clarity. Simplify complicated pointer expressions : Don’t skimp on pointer variables. A variable shouldn’t be used for more than one purpose. This is especially true in case of pointer variables.

Are pointers used only as a last resort, when no other method is available? – Use nonpointer techniques : Pointers are harder than average to understand, they are error prone, and they tend to require machine-dependent, importable code. If you can think of an alternative to using a pointer that works reasonably well, save yourself a few headaches and use it instead.

165

Page 167: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 4.5: Coding Conventions

Copyright © 2009 Accenture All Rights Reserved.

4.5_CodingConventions.ppt

31Copyright © 2009 Accenture All Rights Reserved.

Key Points• Learn the traditional formats for naming variables, methods

and other components of coding in C.• Notice the guidelines on indentation and comments. • Remember that you will be working on projects in teams,

and following these conventions and standards will help to make your work much more “readable” for the other members of your team.

• Avoid declaring or assigning values of more than one variable per line of code.

166

Page 168: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 5: Searching and Sorting

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

5_SearchingAndSorting.ppt

Copyright © 2009 Accenture All Rights Reserved. Accenture, its logo, and Accenture High Performance Delivered are trademarks of Accenture.

Module 5 – Searching and Sorting

Programming Techniques

2Copyright © 2009 Accenture All Rights Reserved.

Contents• Introduction to searching techniques• Types of Searching• Introduction to sorting techniques• Types of Sorting• Introducing the concept of analysis of algorithms

167

Page 169: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 5: Searching and Sorting

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

5_SearchingAndSorting.ppt

3Copyright © 2009 Accenture All Rights Reserved.

Objectives

At the end of this section, you should be able to:• Different Types of search methods

– Linear search– Binary search

• Different Types of Sort Methods– Selection sort– Bubble sort

• Analysis of algorithms

4Copyright © 2009 Accenture All Rights Reserved.

Search Concept• Searching is Locating a particular data item in a list of data

elements is known as searching.• Search takes a problem as input and returns a solution to

the problem• It is the process of locating data like a word, a file etc• There are different Types of search- Few of them are

– Linear Search– Binary Search

168

Page 170: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 5: Searching and Sorting

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

5_SearchingAndSorting.ppt

5Copyright © 2009 Accenture All Rights Reserved.

Linear Search• One of the Famous Searching Techniques• Linear search also as sequential search• In Linear search each item is verified one at a time, in

sequence, until a matching result is found. • It also means check item starting at the beginning of the

data and checking each item in turn until either the desired item is found or the end of the data is reached.

6Copyright © 2009 Accenture All Rights Reserved.

Linear Search Algorithm1. Initialize the index to start of array.2.Repeat through step 4 n times (n - number of elements

in the array)3.Compare search element with current index element.4.If equal add 1 to the index of the element and then

return the value5.Return -1 (indicates the element was not found)

169

Page 171: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 5: Searching and Sorting

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

5_SearchingAndSorting.ppt

7Copyright © 2009 Accenture All Rights Reserved.

Binary Search• Binary Search - Searches a sorted array by repeatedly

dividing the search interval in half. • Binary search finds a particular value in a sorted array, by

"ruling out" half of the data at each step.• Important point to be noted Before Using Binary Search

– Requires the input array to be sorted.– Should not be used when array involves lots of insertions and

deletions.• It is faster than Linear search – since it follows divide and

conquer rule

Binary search is a technique for quickly locating an item in a sequential list. The desired key is compared to the data in the middle of the list. The half that contains the data is then compared in the middle, and so on, either until the key is located or a small enough group is isolated to be sequentially searched.

170

Page 172: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 5: Searching and Sorting

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

5_SearchingAndSorting.ppt

8Copyright © 2009 Accenture All Rights Reserved.

Binary Search Algorithm1. Initialize Low to the index of the first element.2. Initialize High to the index of the last element.3. Repeat through step 6 while Low <= High4. Middle=(Low+High)/25. If search element is equal to the middle element then

add 1 to the Index of middle element and return the value

6. If search element is less than middle elementHigh=Middle-1elseLow=Middle+1

7. return -1 (indicates element not found)

9Copyright © 2009 Accenture All Rights Reserved.

Search Concepts - Activity• Tasks

– Task1: Implement Linear Search algorithm.– Task2: Implement Binary Search algorithm.

• Input Documents– Module 4_activities.doc

20 minutes

171

Page 173: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 5: Searching and Sorting

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

5_SearchingAndSorting.ppt

10Copyright © 2009 Accenture All Rights Reserved.

Sort Concept• Sorting is the process of arranging data items in a

particular order (Ascending or descending).• Sorting is a feature in which the elements of a list are put in

certain order• There are different Types of search- Few of them are

– Selection sort– Bubble sort

172

Page 174: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 5: Searching and Sorting

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

5_SearchingAndSorting.ppt

11Copyright © 2009 Accenture All Rights Reserved.

Selection Sort• In Selection sort it selects the smallest unsorted item

remaining in the list, and then swapping it with the item in the next position to be filled.

• It Beginning with the first element in the array, a search is performed to locate the element which has the smallest key. When the element is found it is interchanged with the first element. This process is continued for all the elements in the array.

• It is mainly used with small list of elements

Selection sort, starts by comparing the entire list for the lowest item and moves it to the 1st position. It then compares the rest of the list for the next-lowest item and places it in the 2nd position and so on until all items are in the required order. Selection sorts perform numerous comparisons, but fewer data movements than other methods.

173

Page 175: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 5: Searching and Sorting

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

5_SearchingAndSorting.ppt

12Copyright © 2009 Accenture All Rights Reserved.

Selection Sort Algorithm1. Repeat thru steps 5 a total of n-1 times.2. Record the number portion of the vector already used.3. Repeat step 4 for the elements in the unsorted portion of

the vector.4. Record location of smallest elements in unsorted vector5. Exchange first element in unsorted vector with smallest

element.

13Copyright © 2009 Accenture All Rights Reserved.

Example - Selection sort

58585858585858

74949494949494

5

94747474363636

42424242424211

36363636747474

23232323232323

11111111111142

64321

Pass NumberOriginal Array

174

Page 176: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 5: Searching and Sorting

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

5_SearchingAndSorting.ppt

14Copyright © 2009 Accenture All Rights Reserved.

Bubble Sort• In bubble sort instead of finding the smallest element and

then exchanging, it compares and exchanges with the adjacent element.

• It starts by comparing the first item to the second, the second to the third and so on until it finds one item out of order. It then swaps the two items and starts over.

• Is used for Sequencing small list.

15Copyright © 2009 Accenture All Rights Reserved.

Bubble Sort Algorithm1. Repeat through step 4 a total of n-1 times.2. Repeat step 3 for elements in unsorted

portion of the vector.3. If the current element in the vector > next element in the

vector then exchange the elements.4. If no exchanges were made then return

else reduce the size of the unsorted vector by one.

175

Page 177: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 5: Searching and Sorting

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

5_SearchingAndSorting.ppt

16Copyright © 2009 Accenture All Rights Reserved.

Example- Bubble Sort

656565651123

747474747411

5

585858112342

424211234258

231123425865

112342586574

4321Pass NumberOriginal

Array

17Copyright © 2009 Accenture All Rights Reserved.

Sort Concepts - Activity• Tasks

– Task1: Implement Sort algorithm– Task2: Implement Linear Search algorithm

• Input Documents– Module 4_activities.doc

20 minutes

176

Page 178: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module 5: Searching and Sorting

IDCGRF001-ACopyright © 2009 Accenture All Rights Reserved.

5_SearchingAndSorting.ppt

18Copyright © 2009 Accenture All Rights Reserved.

Analysis of algorithms• Space Complexity

– Indicates how much extra memory the algorithm needs • Time Complexity

– Indicates how fast the algorithm runs

19Copyright © 2009 Accenture All Rights Reserved.

Key Points• Searching is Locating a particular data item in a list of data

elements is known as searching.• Few of the Searching types are Linear search & • Binary search• Sorting is the process of arranging data items in a

particular order (Ascending or descending).• Few of the types of Sorting Techniques are Selection sort

& Bubble sort• Analysis of algorithms

177

Page 179: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module1: Fundamental Programming Concepts

IDCGRF001-A Module1_activities.doc © 2009 Accenture. All Rights Reserved.

Exercise 01 – Activities to practice to Algorithm, Flow chart and Testing

Estimated Completion Time: 30 minutes

Overview During Activity 1 you will practice simple logic formulation. The activity helps in understanding the working of algorithm, flowchart and testing.

Instructions

Activity 1.0 Write an algorithm, flow chart & test cases to find the sum of first 50 integers (It uses Iterational algorithm technique.)

Activity 1.1 Write an algorithm, flow chart & test cases to search an element in a table of N values (Uses iterative and selection algorithm technique)

Activity 1.2 Write an algorithm, flowchart & test cases to find the sum of N even numbers (Uses iterative algorithm technique)

Activity 1.3 Write an algorithm, flowchart & test cases to find a Fibonacci series

(Fibonacci series is of the form 0,1,1,2,3,5…………………………Generate the

series up to N terms)

Activity 1.4 Write an algorithm and flowchart & test cases to find the maximum &

minimum among three numbers entered from the keyboard. (Use selection

technique.)

1

Page 180: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module1: Fundamental Programming Concepts

IDCGRF001-A Module1_activities.doc © 2009 Accenture. All Rights Reserved.

Exercise 02 – Activity for Top down approach

Estimated Completion Time: 20 minutes

Overview Activity 2 gives you an idea about application of top-down approach

Instructions Design the Payroll System using Top-down approach.

Hints 1. Remember motivation comes from within. Take responsibility for your own learning. 2. Take notes from each presentation and activity. 3. If you don’t understand something, ask questions. 4. Participate in course discussions. 5. Practice what you’ve learned to keep your skills sharp.

1.

2

Page 181: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module2: Introduction to C and Functions

IDCGRF001-A Module2_activities.doc © 2009 Accenture. All Rights Reserved.

Exercise 03 – Activity on different control structures Estimated Completion Time: 60 minutes

Overview Activity 3 gives you an idea about application of top-down approach

Instructions Activity 3.0 Write a C program to find Factorial of a given number. Activity 3.1 Write a C program to find sum of 10 positive numbers Activity 3.2 Write a menu driven program, to find the Addition, Subtraction, Division & multiplication of the 2 given numbers Activity 3.3 Given the number of hours an employee worked and the hourly wage, compute the employee’s weekly pay. Count any hour over 40 as overtime. Consider every 1 hr overtime as 1hr 30 mins (1 hr OT = 1hr 30 min). Activity 3.4 Write a program to add an 8% sales tax to any commodity purchases and round the price accordingly. Activity 3.5 Write a program to convert the month number to the month name Activity 3.6 Write a program that calculates how much money a person earns over a period of time (entered by user), if he is working on the following salary pattern: 100 Rs: 1st week 150 Rs: 2nd week 200 Rs: 3rd week 250 Rs: 4th week

3

Page 182: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module2: Introduction to C and Functions

IDCGRF001-A Module2_activities.doc © 2009 Accenture. All Rights Reserved.

Activity 3.7 Chuckie Lucky won a million Rs, which he places in an account that earns 8% a year. On the last day of each year, Chuckie withdraws Rs 100,000. Write a program that finds out how many years it takes for Chuckie to empty his account. Activity 3.8 Amit invests Rs. 1000 at 10% simple interest. (That is, every year, the investment earns an interest equal to 10% of the original investment). Anand invests Rs1000 at 5% interest compounded annually. (That is, interest is 5% of the current balance, including previous addition of interest.) Write a program that finds how many years it takes for the value of Anand's investment to exceed the value of Amit's investment. Also show the two values at that time. Activity 3.9 The ABC Mail Order Grocery sells artichokes for Rs. 2.25 per kg, beets for Rs. 5.65 per kg, and carrots for Rs. 10.89 per kg. They give a 5% discount for orders of Rs. 1000 or more prior to adding shipping costs. They charge Rs. 3.50 shipping and handling for any order of 20 kg or under, Rs. 7.00 shipping and handling for orders over 20 kg and under 25 kg, and Rs. 10.50 plus Rs. 1.00 per kg for shipments of 25 kg or more. Create following menu to take user input: ---------------------------------------------------------------------------------------------------- Grocery Menu A: To enter quantity of artichokes desired in kgs. B: To enter quantity of beets desired in kgs. C: To enter quantity of carrots desired in kgs. D: To Quit The user has to enter one of the above characters (A, B, C or D) to enter appropriate information. Use switch statement in a loop to achieve this. The program then should compute the total charges, the discount if any, the shipping charges, and the grand total. The program then should display all the purchase information: the cost per kg, the quantity ordered, the total cost of the order, the discount, the shipping charge, and the grand total of all the charges.

4

Page 183: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module2: Introduction to C and Functions

IDCGRF001-A Module2_activities.doc © 2009 Accenture. All Rights Reserved.

Exercise 04 – Activity on functions Estimated Completion Time: 60 minutes

Overview Activity 4 helps you to have hands on experience in using functions in C programming.

Instructions Activity 4.1

Write a C program using function which accepts date of birth and the current date and provides the age in years- month-day format

Activity 4.2 Using functions, write a menu driven program, which offers a list of items & their price per unit where certain items have a discount of 10% if the quantity purchased is more than 25 units. Write a program to calculate the total expenses, if quantity demanded is entered through keyboard.

Activity 4.3 Using functions, write a menu driven program which generates a salary slip. Allow user o view the Total earning, deduction: deduction scheme

Activity 4.4 The Kelvin scale, commonly used in science, is a scale in which 0 represents absolute zero, the lower limit to possible temperatures. Here is the formula for converting Celsius to Kelvin: Kelvin = Celsius + 273.16. Write a program that requests the user to enter a Fahrenheit temperature. The program should read the temperature as a type double number and pass it as an argument to a user-supplied function called Temperatures(). This function should calculate the Celsius equivalent and the Kelvin equivalent and display all three temperatures with a precision of two places to the right of the decimal. It should identify each value with the temperature scale it represents. Here is the formula for converting Fahrenheit to Celsius: Celsius = 1.8 * Fahrenheit + 32.0. The Temperatures () function should use const to create symbolic representations of the three constants that appear in the conversions. The main () function should use a loop to allow the user to enter temperatures repeatedly, stopping when a q or other non-numeric value is entered.

Activity 4.5 A teacher generates the results by aggregating the marks in 6 subjects and then assigns the letter grades using table 3.1. Further, using the modifiers listed in table 3.2 he also sets a + or - qualifiers after the letter

5

Page 184: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module2: Introduction to C and Functions

IDCGRF001-A Module2_activities.doc © 2009 Accenture. All Rights Reserved.

grade, based on the last digit of the score. For example, 81=B-, 94=A, and 68=D+. Note: An F is only an F. There is no F+ or F-. Using functions write a program to generate the grade in the above mentioned pattern, also allow the user to enter values repeatedly.

Table 4. 1

Aggregate Percentage Last Digit

0-60 F

61-70 D

71-80 C

81-90 B

91-100 A

Table 4. 2

Last digit Modifier

1-3 -

4-7 <blank>

8-0 +

Activity 4.6 Using recursive function Write a c program to find the Fibonacci series of

N numbers

6

Page 185: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module2: Introduction to C and Functions

IDCGRF001-A Module2_activities.doc © 2009 Accenture. All Rights Reserved.

Hints 1. Remember motivation comes from within. Take responsibility for your own learning. 2. Take notes from each presentation and activity. 3. If you don’t understand something, ask questions. 4. Participate in course discussions. 5. Practice what you’ve learned to keep your skills sharp.

7

Page 186: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module3: Arrays, Pointers And Structures

IDCGRF001-A Module3_activities.doc © 2009 Accenture. All Rights Reserved.

Exercise 05 – Activity on Arrays

Estimated Completion Time: 30 minutes

Overview Activity 5 will give you hands on experience in using arrays in C.

Instructions

Activity 5.0 Find whether the entered character is lower case or upper case character

Activity 5.1 Write a program to accept a 4 digit number and print the individual digits in a string format. (The number 7500 will be printed as “Seven Five Zero Zero”)

Activity 5.2 Write a program to merge two arrays into third array.

Activity 5.3 Write a function that returns the maximum value of an array of numbers.

Activity 5.4 Write a program to left rotate all the elements of an array by one position

Activity 5.5 Write a mailing list program. This program will read, write, sort, edit and print mailing labels.

Activity 5.6 Write a program to record maximum temperature in 5 cities during a month for 5 days. Provide highest and lowest temperature for each corresponding city over the month.

Activity 5.7 Write a function that scans a string for the character "-" and replaces it with "_"

Activity 5.8 Using if else statements, write a program that reads input up to #, replaces each period with an exclamation mark, replaces each exclamation mark initially present with two exclamation marks, and reports at the end the number of substitutions it has made.

8

Page 187: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module3: Arrays, Pointers And Structures

IDCGRF001-A Module3_activities.doc © 2009 Accenture. All Rights Reserved.

Activity 5.9 Write a function that scans the English text stored in an array and determines the number of words in it.

9

Page 188: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module3: Arrays, Pointers And Structures

IDCGRF001-A Module3_activities.doc © 2009 Accenture. All Rights Reserved.

Exercise 06 – Activity on Pointers

Estimated Completion Time: 30 minutes

Overview Activity 6 will give you hands on experience in using pointers in C.

Instructions

Activity 6.0 The ABC Mail Order Grocery sells artichokes for Rs2.25 per kg, beets for Rs5.65 per kg, and carrots for Rs10.89 per kg. They give a 5% discount for orders of Rs1000 or more prior to adding shipping costs. They charge Rs3.50 shipping and handling for any order of 20 kg or under, Rs7.00 shipping and handling for orders over 20 kg and under 25 kg, and Rs10.50 plus Rs1.00 per kg for shipments of 25 kg or more. Write a program that uses a switch statement in a loop such that a response of a lets the user enter the kg of artichokes desired, b the kg of beets, c the kg of carrots, and q allows the user to exit the ordering process. The program then should compute the total charges, the discount, if any, the shipping charges, and the grand total. The program then should display all the purchase information: the cost per kg, the kg ordered, and the cost for that order for each vegetable, the total cost of the order, the discount, if there is one, the shipping charge, and the grand total of all the charges.

Activity 6.1 Write a program that requests the hours worked in a week and then prints the gross pay, the taxes, and the net pay. Assume the following:

a. Basic pay rate = Rs500.00/hr (Example)

b. Overtime (in excess of 40 hours) = time and a half

c. Tax rate 15% of the first Rs3000

20% of the next Rs1500

25% of the rest

10

Page 189: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module3: Arrays, Pointers And Structures

IDCGRF001-A Module3_activities.doc © 2009 Accenture. All Rights Reserved.

The program will present a menu of pay rates from which to choose. The beginning of a run should look something like this: *********************************************************** Enter the number corresponding to the desired pay rate or action: 1) Rs200/hr 2) Rs300/hr 3) Rs400/hr 4) Rs500/hr 5) Quit *********************************************************** If choices 1 through 4 are selected, the program should request the hours worked. The program should recycle until 5 are entered. If something other than choices 1 through 5 is entered, the program should remind the user what the proper choices are and then recycle. (HINTS: Use #defined constants for the various earning rates and tax rates. Use a switch to select the pay rate.)

11

Page 190: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module3: Arrays, Pointers And Structures

IDCGRF001-A Module3_activities.doc © 2009 Accenture. All Rights Reserved.

Exercise 07 – Activity on Structures And Unions

Estimated Completion Time: 30 minutes

Overview Activity 7 will give you hands on experience in using Structures and Unions in C.

Instructions

Activity 7.0 Using structures create a program that searches for Customer details (name, accountNo, accountType, balance) based on the customer id.

Activity 7.1 Write a program using structure to accept and display employee details.(use nested structure for salary(basic, da, hra, pf).

Hints 1. Remember motivation comes from within. Take responsibility for your own learning. 2. Take notes from each presentation and activity. 3. If you don’t understand something, ask questions. 4. Participate in course discussions. 5. Practice what you’ve learned to keep your skills sharp.

1.

12

Page 191: Programming Techniques_PG(New 2009) (1)

Programming Techniques Module4: Searching and Sorting

IDCGRF001-A Module4_activities.doc © 2009 Accenture. All Rights Reserved.

Exercise 08 – Activity on Searching And Sorting

Estimated Completion Time: 30 minutes

Overview During this activity you will implement all the algorithms that were discussed in the module.

Instructions

Activity 8.0 Write a program to search an element in a list using:

1. Sequential Search 2. Binary search

Note: Elements should be in sorted order for Binary search

(Use the algorithms discussed in the session).

Activity 8.1 Write a program to sort a given list of numbers using:

1. Bubble sort 2. Selection sort

(Use the algorithms discussed in the session).

Hints 1. Remember motivation comes from within. Take responsibility for your own learning. 2. Take notes from each presentation and activity. 3. If you don’t understand something, ask questions. 4. Participate in course discussions. 5. Practice what you’ve learned to keep your skills sharp.

1.

13

Page 192: Programming Techniques_PG(New 2009) (1)

Programming Techniques Case Study 1

Course Code IDCGRF001-A Page 1 of 5 © Accenture 2009 All Rights Reserved

CASE STUDY 1 - PARTICIPANT GUIDE

Page 193: Programming Techniques_PG(New 2009) (1)

Programming Techniques Case Study 1

Course Code IDCGRF001-A Page 2 of 5 © Accenture 2009 All Rights Reserved

Case Study 1: Diet Menu Card for a Fitness Center

Introduction:

In US, the nation’s rate of overweight and obesity continues to rise up from 46%

to almost 55% of all the US adults during the last decade alone. This increase is

the result of all-too-familiar cause’s sedentary lifestyles and high-fat diets

containing too many calories. The Fitness & yoU Health Care Center (FUHCC) ,

a health care center, has helped people live healthier and fuller lives through

weight loss, disease management and lifestyle change. At FUHCC, our

professional & caring staff provides thorough evaluation, education and activities

which ensure the improved quality of life. FUHCC’s comfortable surroundings

and supporting culture ensures the client gets an opportunity to practice the

lifestyle changes that will allow him/her to lead a healthier life. He/her will also

get support & company of the fellow participants who are facing similar

experiences and issues related to weight loss, disease managements and

preventive healthcare. During the course, FUHCC cafeteria provides a

prescribed diet plan which ensures the daily nutritional requirements of a person

are met. FUHCC is not offering any magic cure – but an opportunity to take

control of your life with positive long-term effect for the whole lifetime.

Page 194: Programming Techniques_PG(New 2009) (1)

Programming Techniques Case Study 1

Course Code IDCGRF001-A Page 3 of 5 © Accenture 2009 All Rights Reserved

Objective:

FUHCC cafeteria wants to establish an automated system that can provide a list

of eatables with their corresponding charges. This system will allow the user to

select the combination of foods that will satisfy all the daily nutritional

requirements depending on his/her financial capacity, in case the combination

selected by the user doesn’t fulfill the daily nutritional requirements the system

needs to notify the user about it, should allow the user to enter his scale/budget

and offer him the appropriate combination of food that suits the nutritional

requirements as well as his budget. The goal of the system is to find out the

cheapest combination of foods that will satisfy all the daily nutritional

requirements of a person.

Guidelines:

The problem narrated here is formulated as a linear program where the objective

is to minimize cost and meet constraints, which require that nutritional needs be

satisfied. The constraints will include regulating the number of calories and

amounts of vitamins, minerals, fats, sodium and cholesterol in the diet.

The mathematical formulation of the problem is simple; however the challenge is

when you realize that people do not actually choose their menus by solving the

model i.e. our nutritional requirements can be met yet our concerns for taste and

variety go unheeded. For example, one would never drink gallons of milk nor

include a few plates of Spaghetti without Sauce in our meals; however, such

"optimal" menus have been created using this model.

Page 195: Programming Techniques_PG(New 2009) (1)

Programming Techniques Case Study 1

Course Code IDCGRF001-A Page 4 of 5 © Accenture 2009 All Rights Reserved

Example for the formulation of the Problem:

Minimize the "cost of the menu" subject to the nutrition requirements:

• Eat enough but not too much of Vitamin A/ Vitamin B/ Vitamin C/etc

• Eat at least a certain minimum number of servings of Beef/Pizza/Oranges/etc

but not more than the maximum number of servings of Beef/Pizza/Oranges/etc

For example:

In case of the mathematical formulation of the problem, we may define the

variables as:

X(scrambled eggs) = servings of scrambled eggs in the menu

X(oranges) = servings of oranges in the menu

Cost(scrambled eggs) = cost per serving of scrambled eggs

Min (scrambled eggs) = minimum number of servings to eat

Max (scrambled eggs) = maximum number of servings to eat

Cost(oranges) = cost per serving of oranges

Min (oranges) = minimum number of servings to eat

Max (oranges) = maximum number of servings to eat

A(scrambled eggs) = amount of Vitamin A in one serving of scrambled eggs

A(oranges) = amount of Vitamin A in one serving of oranges

B(scrambled eggs) = amount of Vitamin B in one serving of scrambled eggs

Page 196: Programming Techniques_PG(New 2009) (1)

Programming Techniques Case Study 1

Course Code IDCGRF001-A Page 5 of 5 © Accenture 2009 All Rights Reserved

C(oranges) = amount of Vitamin C in one serving of oranges

Min(A) = minimum amount of Vitamin A required

Max(A) = maximum amount of Vitamin A required

Min(C) = minimum amount of Vitamin C required

Max(C) = maximum amount of Vitamin C required

With the above notation we can write the model as,

Minimize:

Cost(scrambled eggs) * x(scrambled eggs) + . . . + cost(oranges) * x(oranges)

Subject to:

min(A) < max(oranges) x(oranges) min(oranges)max(scrambled

eggs)x(scrambled eggs) min(scrambled eggs)max(C) * C(oranges) +

C(scrambled eggs) min(C) max(A) A(oranges)

Page 197: Programming Techniques_PG(New 2009) (1)

Programming Techniques Case Study 1: Values

Foods Price in Rs. /Serving Serving Size Calories Cholesterol mg Total_Fat g Sodium mg Carbohydrates g Dietary_Fiber g Protein g Vit_A IU Vit_C IU Calcium mg Iron mg

Banana 25.00 1 Fruit,Wo/Skn&Seeds 104.9 0 0.5 1.1 26.7 2.7 1.2 92.3 10.4 6.8 0.4

Grapes 20.00 10 Fruits,Wo/Rf 15.1 0 0.1 0.5 4.1 0.2 0.2 24 1 3.4 0.1

Carrots,Raw 11.00 1/2 Cup Shredded 23.7 0 0.1 19.2 5.6 1.6 0.6 15471 5.1 14.9 0.3

Oranges 20.00 1 Frt,2-5/8 Diam 61.6 0 0.2 0 15.4 3.1 1.2 268.6 69.7 52.4 0.1

Celery, Raw 20.00 1 Stalk 6.4 0 0.1 34.8 1.5 0.7 0.3 53.6 2.8 16 0.2

Potatoes, Baked 20.00 1/2 Cup 171.5 0 0.2 15.2 39.9 3.2 3.7 0 15.6 22.7 4.3

Peppers, Sweet, Raw 43.00 1 Pepper 20 0 0.1 1.5 4.8 1.3 0.7 467.7 66.1 6.7 0.3

Frozen Broccoli 76.00 10 Oz Pkg 73.8 0 0.8 68.2 13.6 8.5 8 5867.4 160.2 159 2.3

Tofu 31.00 1/4 block 88.2 0 5.5 8.1 2.2 1.4 9.4 98.6 0.1 121.8 6.2

Apple,Raw,W/Skin 34.00 1 Fruit,3/Lb,Wo/Rf 81.4 0 0.5 0 21 3.7 0.3 73.1 7.9 9.7 0.2

Tomato,Red,Ripe,Raw 56.00 1 Tomato, 2-3/5 In 25.8 0 0.4 11.1 5.7 1.4 1 766.3 23.5 6.2 0.6

Frozen Corn 20.00 1/2 Cup 72.2 0 0.6 2.5 17.1 2 2.5 106.6 5.2 3.3 0.3

Spaghetti W/ Sauce 65.00 1 1/2 Cup 358.2 0 12.3 1237.1 58.3 11.6 8.2 3055.2 27.9 80.2 2.3

Wheat Bread 41.00 1 Sl 65 0 1 134.5 12.4 1.3 2.2 0 0 10.8 0.7

White Bread 38.00 1 Sl 65 0 1 132.5 11.8 1.1 2.3 0 0 26.2 0.8

Kiwifruit,Raw,Fresh 49.00 1 Med Frt,Wo/Skin 46.4 0 0.3 3.8 11.3 2.6 0.8 133 74.5 19.8 0.3

Lettuce,Iceberg,Raw 37.00 1 Leaf 2.6 0 0 1.8 0.4 0.3 0.2 66 0.8 3.8 0.1

Bagels 64.00 1 Oz 78 0 0.5 151.4 15.1 0.6 3 0 0 21 1

Chocolate Chip Cookies 20.00 1 Cookie 78.1 5.1 4.5 57.8 9.3 0 0.9 101.8 0 6.2 0.4

Oatmeal Cookies 27.00 1 Cookie 81 0 3.3 68.9 12.4 0.6 1.1 2.9 0.1 6.7 0.5

White Tuna in Water 140.00 3 Oz 115.6 35.7 2.1 333.2 0 0 22.7 68 0 3.4 0.5

Cheddar Cheese 42.00 1 Oz 112.7 29.4 9.3 173.7 0.4 0 7 296.5 0 202 0.2

Apple Pie 30.00 1 Oz 67.2 0 3.1 75.4 9.6 0.5 0.5 35.2 0.9 3.1 0.1

Butter,Regular 32.00 1 Pat 35.8 10.9 4.1 41.3 0 0 0 152.9 0 1.2 0

3.3% Fat,Whole Milk 25.00 1 C 149.9 33.2 8.1 119.6 11.4 0 8 307.4 2.3 291.3 0.1

2% Lowfat Milk 30.00 1 C 121.2 18.3 4.7 121.8 11.7 0 8.1 500.2 2.3 296.7 0.1

Skim Milk 32.00 1 C 85.5 4.4 0.4 126.2 11.9 0 8.4 499.8 2.4 302.3 0.1

Complete nutritional value & Price of the foods

Course Code # IDCGRF001-A © Accenture 2007 All Rights Reserved

Page 1 of 7

Page 198: Programming Techniques_PG(New 2009) (1)

Programming Techniques Case Study 1: Values

Poached Eggs 14.00 Lrg Egg 74.5 211.5 5 140 0.6 0 6.2 316 0 24.5 0.7

Scrambled Eggs 20.00 1 Egg 99.6 211.2 7.3 168 1.3 0 6.7 409.2 0.1 42.6 0.7

Roasted Chicken 79.00 1 lb chicken 277.4 129.9 10.8 125.6 0 0 42.2 77.4 0 21.9 1.8

Peanut Butter 17.00 2 Tbsp 188.5 0 16 155.5 6.9 2.1 7.7 0 0 13.1 0.6

Bologna,Turkey 36.00 1 Oz 56.4 28.1 4.3 248.9 0.3 0 3.9 0 0 23.8 0.4

Frankfurter, Beef 48.00 1 Frankfurter 141.8 27.4 12.8 461.7 0.8 0 5.4 0 10.8 9 0.6

Ham,Sliced,Extralean 41.00 1 Sl,6-1/4x4x1/16 In 37.1 13.3 1.4 405.1 0.3 0 5.5 0 7.4 2 0.2

Kielbasa,Prk 38.00 1 Sl,6x3-3/4x1/16 In 80.6 17.4 7.1 279.8 0.6 0 3.4 0 5.5 11.4 0.4

Cap'N Crunch 20.00 1 Oz 119.6 0 2.6 213.3 23 0.5 1.4 40.6 0 4.8 7.5

Cheerios 19.00 1 Oz 111 0 1.8 307.6 19.6 2 4.3 1252.2 15.1 48.6 4.5

Corn Flks, Kellogg'S 20.00 1 Oz 110.5 0 0.1 290.5 24.5 0.7 2.3 1252.2 15.1 0.9 1.8

Raisin Brn, Kellg'S 23.00 1.3 Oz 115.1 0 0.7 204.4 27.9 4 4 1250.2 0 12.9 16.8

Rice Krispies 27.00 1 Oz 112.2 0 0.2 340.8 24.8 0.4 1.9 1252.2 15.1 4 1.8

Special K 28.00 1 Oz 110.8 0 0.1 265.5 21.3 0.7 5.6 1252.2 15.1 8.2 4.5

Oatmeal 18.00 1 C 145.1 0 2.3 2.3 25.3 4 6.1 37.4 0 18.7 1.6

Malt-O-Meal,Choc 16.00 1 C 607.2 0 1.5 16.5 128.2 0 17.3 0 0 23.1 47.2

Hamburger W/Toppings 132.00 1 Burger 275 42.8 10.2 563.9 32.7 0 13.6 126.3 2.6 51.4 2.5

Taco 32.00 1 Small Taco 369.4 56.4 20.6 802 26.7 0 20.7 855 2.2 220.6 2.4

Couscous 60.00 1/2 Cup 100.8 0 0.1 4.5 20.9 1.3 3.4 0 0 7.2 0.3

Hotdog, Plain 123.00 1 Hotdog 242.1 44.1 14.5 670.3 18 0 10.4 0 0.1 23.5 2.3

Macaroni,Ckd 60.00 1/2 Cup 98.7 0 0.5 0.7 19.8 0.9 3.3 0 0 4.9 1

White Rice 20.00 1/2 Cup 102.7 0 0.2 0.8 22.3 0.3 2.1 0 0 7.9 0.9

Sardines in Oil 139.00 2 Sardines 49.9 34.1 2.7 121.2 0 0 5.9 53.8 0 91.7 0.7

Pizza W/Pepperoni 132.00 1 Slice 181 14.2 7 267 19.9 0 10.1 281.9 1.6 64.6 0.9

Pork 137.00 4 Oz 710.8 105.1 72.2 38.4 0 0 13.8 14.7 0 59.9 0.4

Popcorn,Air-Popped 15.00 1 Oz 108.3 0 1.2 1.1 22.1 4.3 3.4 55.6 0 2.8 0.8

Pretzels 30.00 1 Oz 108 0 1 486.2 22.5 0.9 2.6 0 0 10.2 1.2

Chicknoodl Soup 70.00 1 C (8 Fl Oz) 150.1 12.3 4.6 1862.2 18.7 1.5 7.9 1308.7 0 27.1 1.5

Potato Chips,Bbqflvr 15.00 1 Oz 139.2 0 9.2 212.6 15 1.2 2.2 61.5 9.6 14.2 0.5

Splt Pea&Hamsoup 100.00 1 C (8 Fl Oz) 184.8 7.2 4 964.8 26.8 4.1 11.1 4872 7 33.6 2.1

Tortilla Chip 40.00 1 Oz 142 0 7.4 149.7 17.8 1.8 2 55.6 0 43.7 0.4

Vegetbeef Soup 100.00 1 C (8 Fl Oz) 158.1 10 3.8 1915.1 20.4 4 11.2 3785.1 4.8 32.6 2.2

New E Clamchwd,W/Mlk 78.00 1 C (8 Fl Oz) 163.7 22.3 6.6 992 16.6 1.5 9.5 163.7 3.5 186 1.5

Neweng Clamchwd 75.00 1 C (8 Fl Oz) 175.7 10 5 1864.9 21.8 1.5 10.9 20.1 4.8 82.8 2.8

Beanbacn Soup,W/Watr 67.00 1 C (8 Fl Oz) 172 2.5 5.9 951.3 22.8 8.6 7.9 888 1.5 81 2

Tomato Soup 30.00 1 C (8 Fl Oz) 170.7 0 3.8 1744.4 33.2 1 4.1 1393 133 27.6 3.5

Crm Mshrm Soup,W/Mlk 62.00 1 C (8 Fl Oz) 203.4 19.8 13.6 1076.3 15 0.5 6.1 153.8 2.2 178.6 0.6

Course Code # IDCGRF001-A © Accenture 2007 All Rights Reserved

Page 1 of 7

Page 199: Programming Techniques_PG(New 2009) (1)

Programming Techniques Case Study 2

Course Code IDCGRF001-A Page 1 of 4 © Accenture 2009 All Rights Reserved

CASE STUDY 2 - PARTICIPANT GUIDE

Page 200: Programming Techniques_PG(New 2009) (1)

Programming Techniques Case Study 2

Course Code IDCGRF001-A Page 2 of 4 © Accenture 2009 All Rights Reserved

Case Study 2: Optimal Utilization of Fabric Reel

Introduction:

The Abhyankar Cotton Mills (Est. : 1956) was renamed as Abhyankar Denims &

Exports Ltd in the late 90’s and is a leading global player in the textile industry.

With the experienced promoters, the company is spreading its wings all over the

globe at a very fast pace. The Abhyankar’s are involved in the marketing of

denim for over 35 years and involved in the textile trade for more than 50 years.

Abhyankar’s enterprising & flexible manufacturing process enables them to

quickly adapt to the dynamism in the market trends and produce novel designs

and weaves in the shortest turnaround time. Due to this their customers get the

unbeatable advantage of tapping into the markets as the demands peak. The

Company offers the widest possible variety of weaves and widths, thus saving

their clients precious time and efforts of sourcing material from multiple sources.

The company aims at minimizing the waste in the whole process of providing a

variety of fabric widths to the client and also believes in “A Rupee saved is a

Rupee earned”. Therefore the fabric cutting division is equally important as the

manufacturing unit.

Page 201: Programming Techniques_PG(New 2009) (1)

Programming Techniques Case Study 2

Course Code IDCGRF001-A Page 3 of 4 © Accenture 2009 All Rights Reserved

Objective:

The Abhyankar Groups wants to automate the process of cutting the fabric stock.

They are targeting at a system which cuts the reel so that the least amount of

leftover is wasted where a number of reels of fabric of fixed width waiting to be

cut, yet different manufacturers want different numbers of rolls of various-sized

widths.

Guidelines:

The problem narrated here is formulated as a linear program where the objective

is to minimize the number of reels that are cut. The constraint in the problem is,

we should cut enough reels with certain patterns to fulfill the orders that we

received.

For example:

Suppose, if each reel size is of 2000 inches and have the following requirement,

we need to prepare the number of patterns & their combination which will

minimize number of reels used and ultimately minimize the wastage incurred.

Quantity Ordered Order Width (inches)

25 50

610 46

395 20

211 60

The mathematical formulation of the problem is simple.

Minimize the “number of fabric reels” subject to the various width patterns

For example, in case of the mathematical formulation of the problem, we may define the variables as:

x = the number of each pattern to cut

Page 202: Programming Techniques_PG(New 2009) (1)

Programming Techniques Case Study 2

Course Code IDCGRF001-A Page 4 of 4 © Accenture 2009 All Rights Reserved

j = one of the patterns

Aij = the number of pieces cut of the ith order width

Therefore,

xj = the number of times the jth pattern will be used

And, Aij*xj must be greater than or equal to the required number of pieces for

order width j - this is the constraint.