Sie sind auf Seite 1von 202

Programming Techniques Course Map Day 1 9:00 - 9:15 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 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 5:15 - 5:30 5:30 - 5:45 5:45 - 6:00 Day 1 Summary Day 2 Summary Day 3 Summary Day 4 Summary Module 3.2:Functions Module 5:Searcing and Sorting Day 5 Summary Sr Manager talk with ASEs Module 2.2:Programming Life Cycle Module3.1:Introdu ction to C (basic constructs, Keywords, literals, LUNCH Module 4.2:Pointers Module 2.1:Fundamental Programming Concepts Module1:Course Introduction Module 4.1:Introduction to Arrays Coding, Coding, Testing Testing & & Documentation of Case study Documentation of Case study 2 1. Day 2 Morning Review Day 3 Day 4 Day 5

Morning Review Morning Review

Module 4.3:Memory Management LUNCH LUNCH LUNCH LUNCH

Module 3.1(contd..): Module Declaring and 4.4:Introduction to defining Structures variables,control structures,Best Practices) Design and Design and Documentation documentation Module 4.5:Coding of Case study 1 of Case study 2 Conventions

Review and Feed back of Case study 1 & 2

Programming Techniques Module 1: Course Overview

1_Course Overview.ppt

Programming Techniques
Module 1: Course Overview

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

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

Copyright 2009 Accenture All Rights Reserved.

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

Programming Techniques Module 1: Course Overview

1_Course Overview.ppt

Welcome
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.

Copyright 2009 Accenture All Rights Reserved.

Objectives
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.

Copyright 2009 Accenture All Rights Reserved.

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

Programming Techniques Module 1: Course Overview

1_Course Overview.ppt

Introductions
Name Your self assessment based on:
Why Im 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
Copyright 2009 Accenture All Rights Reserved.

Expectations of participants
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.

Copyright 2009 Accenture All Rights Reserved.

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

Programming Techniques Module 1: Course Overview

1_Course Overview.ppt

Course Objectives
Introduction to algorithms and its 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

Copyright 2009 Accenture All Rights Reserved.

Course Approach
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

Copyright 2009 Accenture All Rights Reserved.

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

Programming Techniques Module 1: Course Overview

1_Course Overview.ppt

Course Approach (Cont.)


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
Dont just listen to discussions, interact! If in doubt, ask questions to clarify. Spot problems and suggest alternatives or workarounds.

Copyright 2009 Accenture All Rights Reserved.

Course Approach (Cont.)


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

Be resourceful
Dont ask for answers or solutions, find them! The course environment provides all the necessary tools and materials to learn, utilize them well.

Copyright 2009 Accenture All Rights Reserved.

10

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

Programming Techniques Module 1: Course Overview

1_Course Overview.ppt

Course Approach - Learn By Doing


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.
Copyright 2009 Accenture All Rights Reserved.

11

Course Approach - Tiers of Support


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.
Copyright 2009 Accenture All Rights Reserved.

12

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

Programming Techniques Module 1: Course Overview

1_Course Overview.ppt

Course Map
Day 1 Day 2

Module 1: Course Introduction Module 2.1: Fundamental Programming Concepts Module 2.2: Programming Life Cycle

Module 4.1: Introduction to Arrays Module 4.2: Pointers Module 4.3: Memory Management

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


Lunch Lunch

Module 3.1(contd..): (Declaring and Defining Variables, Control Structures, Best Practices) Module 3.2: Functions
Copyright 2009 Accenture All Rights Reserved.

Module 4.4: Introduction to Structures Module 4.5: Coding Conventions Module 5: Searching and Sorting
13

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.
Copyright 2009 Accenture All Rights Reserved.

14

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

Programming Techniques Module 1: Course Overview

1_Course Overview.ppt

Ground Rules (Cont.)


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
Copyright 2009 Accenture All Rights Reserved.

15

Training Resources
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.
16

Copyright 2009 Accenture All Rights Reserved.

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

Programming Techniques Module 1: Course Overview

1_Course Overview.ppt

Questions/ Comments
What questions or comments do you have?

Copyright 2009 Accenture All Rights Reserved.

17

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

Programming Techniques Module 2: Fundamental Programming Concepts

2.1_FundamentalProgrammingConcepts.ppt

Programming Techniques
Module 2.1: Fundamental Programming Concepts

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

Course Code #IDCGRF001-A

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

Copyright 2009 Accenture All Rights Reserved.

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

10

Programming Techniques Module 2: Fundamental Programming Concepts

2.1_FundamentalProgrammingConcepts.ppt

Objective
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

Copyright 2009 Accenture All Rights Reserved.

What is an Algorithm
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.
Copyright 2009 Accenture All Rights Reserved.

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

11

Programming Techniques Module 2: Fundamental Programming Concepts

2.1_FundamentalProgrammingConcepts.ppt

Benefits of Algorithm
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

Copyright 2009 Accenture All Rights Reserved.

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

12

Programming Techniques Module 2: Fundamental Programming Concepts

2.1_FundamentalProgrammingConcepts.ppt

Analyzing An Algorithm(1 of 2)
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.
Copyright 2009 Accenture All Rights Reserved.

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 algorithms 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.

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

13

Programming Techniques Module 2: Fundamental Programming Concepts

2.1_FundamentalProgrammingConcepts.ppt

Analyzing An Algorithm(2 of 2)
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.
Copyright 2009 Accenture All Rights Reserved.

Content Continued The 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 important One can also think of a hybrid approach while analyzing the algorithms, where the form of the function describing the algorithms 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.
IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.
14

Programming Techniques Module 2: Fundamental Programming Concepts

2.1_FundamentalProgrammingConcepts.ppt

Algorithm Complexities
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

Copyright 2009 Accenture All Rights Reserved.

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.

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

15

Programming Techniques Module 2: Fundamental Programming Concepts

2.1_FundamentalProgrammingConcepts.ppt

Structure of an Algorithm
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
Copyright 2009 Accenture All Rights Reserved.

Structure of an Algorithm - Example 1


Example of an algorithm to find the sum of two numbers
Algorithm Starting point

num1, num2 are the variables declared


1. 2. 3. 4. 5. Begin Input num1,num2 Sum=num1+num2 Print Sum End

Input is used to perform read values to num1 & num2 print is used to print the output (result)

End of Algorithm
Copyright 2009 Accenture All Rights Reserved.

10

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

16

Programming Techniques Module 2: Fundamental Programming Concepts

2.1_FundamentalProgrammingConcepts.ppt

Algorithm concepts
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

Copyright 2009 Accenture All Rights Reserved.

11

Sequential Algorithm Example 2


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
12

Implementation of Sequential Algorithm Method


Copyright 2009 Accenture All Rights Reserved.

Output:

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

17

Programming Techniques Module 2: Fundamental Programming Concepts

2.1_FundamentalProgrammingConcepts.ppt

Single Alternative Algorithm Example 3


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
Implementation of single Alternative algorithm
Copyright 2009 Accenture All Rights Reserved.

Output:

Enter Marks of 3 subjects 60 70 80 Passed


13

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

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

18

Programming Techniques Module 2: Fundamental Programming Concepts

2.1_FundamentalProgrammingConcepts.ppt

Multiple Alternative algorithm Example 4


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. 2. 3. 4. Begin Print Enter Marks of 3 subjects Input marks1, marks2,marks3 Avg=marks1+marks2+marks3)/3 If (Avg >= 50) Then Print Passed Else Print Failed End

5.

Implementation of Multiple Alternative algorithm

Output:

Enter Marks of 3 subjects 40 30 30 Failed


14

Copyright 2009 Accenture All Rights Reserved.

Algorithm Iteration Example 5


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
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
Copyright 2009 Accenture All Rights Reserved.

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 15

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

19

Programming Techniques Module 2: Fundamental Programming Concepts

2.1_FundamentalProgrammingConcepts.ppt

Flowcharts
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.

Copyright 2009 Accenture All Rights Reserved.

16

Flowchart depictions
Each symbol depicts a Start End points process The start point, end points, Processing Logic inputs, outputs, etc are represented by a graphical image Input/Output Any flow chart should Decisions have
Start in the beginning End to the end of the flow chart Depending on the requirement, rest of the symbols are used
Copyright 2009 Accenture All Rights Reserved.

Connectors Flow Line Loops


17

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

20

Programming Techniques Module 2: Fundamental Programming Concepts

2.1_FundamentalProgrammingConcepts.ppt

Flowchart Example 1
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.
Start Enter m1,m2,m3 Avg=m1+m2+m3/3

Avg>50 Fail pass

end
Copyright 2009 Accenture All Rights Reserved.

18

Advantages and Disadvantages


Advantage
Communication Effective analysis Proper documentation

Disadvantage
Complex logic Alterations and modifications will be difficult The essentials of what is done can easily be lost in the technical details of how it is done

Efficient Coding Proper Debugging


Copyright 2009 Accenture All Rights Reserved.

19

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

21

Programming Techniques Module 2: Fundamental Programming Concepts

2.1_FundamentalProgrammingConcepts.ppt

Testing
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'

Copyright 2009 Accenture All Rights Reserved.

20

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.

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

22

Programming Techniques Module 2: Fundamental Programming Concepts

2.1_FundamentalProgrammingConcepts.ppt

Unit Testing
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.

Copyright 2009 Accenture All Rights Reserved.

21

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.

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

23

Programming Techniques Module 2: Fundamental Programming Concepts

2.1_FundamentalProgrammingConcepts.ppt

Unit Testing (Cont.)


Entry criteria:
After completion of each class/method, unit testing should be done. Functionality is achieved All requirements tested & verified 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
Copyright 2009 Accenture All Rights Reserved.

Exit criteria:

Result:

22

Test Cases
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
Copyright 2009 Accenture All Rights Reserved.

23

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

24

Programming Techniques Module 2: Fundamental Programming Concepts

2.1_FundamentalProgrammingConcepts.ppt

Test Case - Example


1. Begin 2. Print 4. Repeat Enter number of students step 4 thru step 8, N TIMES 3. Input N 5. Print Enter Marks of 3 subjects 6. Input marks1, marks2, marks3 7. Avg = (marks1+marks2+marks3)/3 8. If (Avg >= 50) Then Print Passed Else Print Failed End-if 9. End
Copyright 2009 Accenture All Rights Reserved.

Enter number of Students 2 Enter Marks of 3 subjects 30 40 50 Failed Enter Marks of 3 subjects 60 60 70 Passed
24

Example-test cases
Step Action / Input Data Number Description 1.001 Enter character Character : X 1.002 1.003 1.004 Enter negative number Number : X Expected Result Invalid input Negative input Invalid input Correct Input, should continue the next stage
25

Enter a special Special character character : X Enter number Number : X

Copyright 2009 Accenture All Rights Reserved.

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

25

Programming Techniques Module 2: Fundamental Programming Concepts

2.1_FundamentalProgrammingConcepts.ppt

Algorithm, Flowchart & Unit Testing - Activity


Tasks
Hands on using Algorithms, Flowcharts and Unit Testing

Input Documents
Module 1_activities.doc
Exercise 1

30 minutes
Copyright 2009 Accenture All Rights Reserved.

26

Key Points
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.

Copyright 2009 Accenture All Rights Reserved.

27

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

26

Programming Techniques Module 2.2: Programming Life Cycle

2.2_ProgrammingLifeCycle.ppt

Programming Techniques
Module 2.2: Programming Life Cycle

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

Contents
Programming Programming Life Cycle Types of Programming Design
Top-Down Approach Bottom-Up Approach Linear Programming Structured Programming

Copyright 2009 Accenture All Rights Reserved.

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

27

Programming Techniques Module 2.2: Programming Life Cycle

2.2_ProgrammingLifeCycle.ppt

Objectives
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

Copyright 2009 Accenture All Rights Reserved.

Programming
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

Copyright 2009 Accenture All Rights Reserved.

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

28

Programming Techniques Module 2.2: Programming Life Cycle

2.2_ProgrammingLifeCycle.ppt

Program Development Life cycle

WHAT
Requirements Gathering, Problem definition

HOW
Analysis & Design

DO IT
Build

TEST
Testing

Deploy & Maintain


Copyright 2009 Accenture All Rights Reserved.

USE
5

Program Design Approaches


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

Copyright 2009 Accenture All Rights Reserved.

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

29

Programming Techniques Module 2.2: Programming Life Cycle

2.2_ProgrammingLifeCycle.ppt

Top-Down Design
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 subprograms are written. To do this, actual sub programs are replaced with stubs.

Copyright 2009 Accenture All Rights Reserved.

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.

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

30

Programming Techniques Module 2.2: Programming Life Cycle

2.2_ProgrammingLifeCycle.ppt

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..

Copyright 2009 Accenture All Rights Reserved.

Bottom-Up Design
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.
Copyright 2009 Accenture All Rights Reserved.

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

31

Programming Techniques Module 2.2: Programming Life Cycle

2.2_ProgrammingLifeCycle.ppt

Linear Programming
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

Copyright 2009 Accenture All Rights Reserved.

10

Structured Programming
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.

Copyright 2009 Accenture All Rights Reserved.

11

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

32

Programming Techniques Module 2.2: Programming Life Cycle

2.2_ProgrammingLifeCycle.ppt

Program life cycle


Req. Req. Gathering Gathering Algorithm Algorithm Test Plan Test Plan Coding Coding Compilation Compilation

Pseudo code

Source Code + Test Script Object code

Linking Linking

Libraries

Debugging / Debugging / Testing Testing

Executable File

Copyright 2009 Accenture All Rights Reserved.

12

Program life cycle (Cont.)


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

Copyright 2009 Accenture All Rights Reserved.

13

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

33

Programming Techniques Module 2.2: Programming Life Cycle

2.2_ProgrammingLifeCycle.ppt

Program life cycle (Cont.)


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.

Copyright 2009 Accenture All Rights Reserved.

14

Program life cycle (Cont.)


Library
It is a catalogue of previously developed objects. They contain procedures for input, output, math, etc. A user can create their own 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

Copyright 2009 Accenture All Rights Reserved.

15

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

34

Programming Techniques Module 2.2: Programming Life Cycle

2.2_ProgrammingLifeCycle.ppt

Key points
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

Copyright 2009 Accenture All Rights Reserved.

16

Program design - Activity


Tasks
Hands on using Top down approach

Input Documents
Module 1_activities.doc
Exercise 2

20 minutes
Copyright 2009 Accenture All Rights Reserved.

17

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

35

Programming Techniques Module 3.1: Introduction to C

3.1_IntroductionToC.ppt

Programming Techniques
Module 3.1: Introduction to C

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

Course Code #IDCGRF001-A

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

Copyright 2009 Accenture All Rights Reserved.

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

36

Programming Techniques Module 3.1: Introduction to C

3.1_IntroductionToC.ppt

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

Copyright 2009 Accenture All Rights Reserved.

C Programming
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

Copyright 2009 Accenture All Rights Reserved.

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

37

Programming Techniques Module 3.1: Introduction to C

3.1_IntroductionToC.ppt

How does C work?


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
Source Code
# include <stdio.h> int main() { printf ( Hello World!); return 0; }

Compiler

Object file
Assembly language statements

Linkers Links library files and object files

Forms executable file to run on the operating system


Copyright 2009 Accenture All Rights Reserved.

C Source File Structure


/***************************************************** * hello.c -- program to print out "Hello World". * * Not an especially earth-shattering program. * * * Preprocessors * Author: @AuthorName * The sentence beginning with # is a * * preprocessor directive. * Date : 06-03-06 * Here stdio.h is known as a header * * file. It includes standard input * Purpose: Demonstration of a simple and output header file in to the program. * * * program * Usage: * * Runs the program and the message appears. * *****************************************************/ C programs consist of functions #include <stdio.h> A function should always be followed by a pair of parentheses () int main() { /* Say Hello to world */ printf("Hello World\n"); return (0); }
Copyright 2009 Accenture All Rights Reserved.

Functions

main ()

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

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

38

Programming Techniques Module 3.1: Introduction to C

3.1_IntroductionToC.ppt

C Source File Structure (Cont.)


/***************************************************** * 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. * * * Braces * Usage: * Braces are used for * grouping * Runs the program and the message appears. statements or blocks of code. The left brace ( { ) indicates the *****************************************************/ #include <stdio.h> beginning of a function or a class, which contains the variables and methods needed. The left brace also indicates the int main() beginning of a method body. { /* Say Hello to world */ For every left brace that opens a printf("Hello World\n"); class or method you need a return (0); corresponding right brace ( } ) to } close the class or method. A right brace always closes its Copyright 2009 Accenture All Rights Reserved. nearest left brace

C Source File Structure (Cont.)


/***************************************************** * hello.c -- program to print out "Hello World". * * Not an especially earth-shattering program. * * * * Author: @AuthorName * printf() * * printf() is the standard output * Date : 06-03-06 * function of the C program ( the * * * Purpose: Demonstration of a simple display screen). program. * printf is included in the stdio.h * * header file. * * Usage: * Runs the program and the message appears. * *****************************************************/ return (0) #include <stdio.h> return instructs the function to end and return the code that follows the instruction. int main() In this case return (0); { return will end main() and will return 0 to the system console, /* Say Hello to world */ which is an integer value. printf("Hello World\n"); return (0); }
Copyright 2009 Accenture All Rights Reserved.

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

39

Programming Techniques Module 3.1: Introduction to C

3.1_IntroductionToC.ppt

File Extensions & Program Execution


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
Copyright 2009 Accenture All Rights Reserved.

Tips for C program


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.

Copyright 2009 Accenture All Rights Reserved.

10

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

40

Programming Techniques Module 3.1: Introduction to C

3.1_IntroductionToC.ppt

C key words
auto break case char const continue default do double else enum extern float far for goto if int long near register return short signed static struct switch typedef union unsigned void while
11

Copyright 2009 Accenture All Rights Reserved.

Identifiers
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

Incorrect 3strikes Write&Print switch

Correct strikes3 Write_Print Switch

printMe is not the same as PrintMe

Copyright 2009 Accenture All Rights Reserved.

12

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

41

Programming Techniques Module 3.1: Introduction to C

3.1_IntroductionToC.ppt

Identifiers (cond)
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.

Copyright 2009 Accenture All Rights Reserved.

13

Literals
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
Type character integer floating-point escape sequences Examples & Values a \uFFFF' \777 123 123L O123 Ox123 123.5 123.5D 123.5F 123.5e+6 \n \t \b \f \r \ \ \\

Copyright 2009 Accenture All Rights Reserved.

14

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

42

Programming Techniques Module 3.1: Introduction to C

3.1_IntroductionToC.ppt

Variable and Data Types


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

Copyright 2009 Accenture All Rights Reserved.

15

Primitive data types


Primitive data types represent atomic values and are built-in to C
Type char int float double Bits 8 16 32 64 -32,768 Lowest Value '\u0000' [0] [-215] Highest Value '\uffff' [27-1] +32,767 [215-1] 3.40282346638528860e+38 1.79769313486231570e+308

1.40129846432481707e-45 4.94065645841246544e324

Copyright 2009 Accenture All Rights Reserved.

16

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

43

Programming Techniques Module 3.1: Introduction to C

3.1_IntroductionToC.ppt

Primitive Data Types (contd)


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
Type
short int unsigned short int unsigned int int long int signed char unsigned char 2 2 4 4 4 1 1

Bytes
0 -> +65,535

Range
-32,768 -> +32,767 0 -> +4,294,967,295 -2,147,483,648 -> +2,147,483,647 -2,147,483,648 -> +2,147,483,647 -128 -> +127 0 -> +255
17

Copyright 2009 Accenture All Rights Reserved.

User Defined Data Types


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

Copyright 2009 Accenture All Rights Reserved.

18

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

44

Programming Techniques Module 3.1: Introduction to C

3.1_IntroductionToC.ppt

Variable Declaration & initialization


Declaring a variable with primitive data type int age = 21;
primitive identifier initial name value type

Declaring a variable with user defined data type struct Item


Structure data type

Product ;
identifier name
19

Copyright 2009 Accenture All Rights Reserved.

Primitive Type Declaration


declaration int age;
allot space to memory

MEMORY

type Identifier name

age

17

initialization/assignment

age = 17;
Identifier name value

Stack

Copyright 2009 Accenture All Rights Reserved.

20

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

45

Programming Techniques Module 3.1: Introduction to C

3.1_IntroductionToC.ppt

Naming Variables
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

Copyright 2009 Accenture All Rights Reserved.

21

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

46

Programming Techniques Module 3.1: Introduction to C

3.1_IntroductionToC.ppt

printf ()
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>);
Example:

int x=5; float y=12.6; printf (this is a test\n); printf (x=%d y=%f, x, y);
Copyright 2009 Accenture All Rights Reserved.

Output:
This is a test X=5 y=12.6

22

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');

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

47

Programming Techniques Module 3.1: Introduction to C

3.1_IntroductionToC.ppt

scanf()
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>);
Example: int x; float y; printf (Enter the values:); scanf (%d %f, &x, &y, );

& specifies the Address

Copyright 2009 Accenture All Rights Reserved.

23

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

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

48

Programming Techniques Module 3.1: Introduction to C

3.1_IntroductionToC.ppt

Unformatted Functions
getchar()- To accept a character at a time putchar()- To print a character at a time
Example to write a program that copies its input to its output one character at a time
Sample Code
int c; While ((c=getchar())!=EOF) { putchar(c); }

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

Copyright 2009 Accenture All Rights Reserved.

24

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

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

49

Programming Techniques Module 3.1: Introduction to C

3.1_IntroductionToC.ppt

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

Copyright 2009 Accenture All Rights Reserved.

25

Unary Operators
Unary operators use only one operand
Example:
n=10; x=n++; x=++n; means means set x to 10. set x to 11.
+ ++

Increment by 1, can be prefix or postfix Decrement by 1, can be prefix or postfix Positive sign Negative sign

--

In both the cases n becomes 11.

Increment & decrement operators can only be applied to variables. Expression (i+j)++ is illegal.
Copyright 2009 Accenture All Rights Reserved.

26

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

50

Programming Techniques Module 3.1: Introduction to C

3.1_IntroductionToC.ppt

Arithmetic operators
Arithmetic operators are used for basic mathematical operations
+ *
Sample code 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);
Copyright 2009 Accenture All Rights Reserved.

Add Subtract Multiply Divide Modulo, remainder

/ %

calculating... 25 5 150 1 5
27

Relational operators
Relational operators are used to compare values < <= > >= == != Less than Less than or equal to Greater than Greater than or equal to Equals Not equals

Copyright 2009 Accenture All Rights Reserved.

28

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

51

Programming Techniques Module 3.1: Introduction to C

3.1_IntroductionToC.ppt

Conditional operators
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
Syntax: condition ? exp1 : exp2; Sample code:
int x=5,y=6; printf (The maximum is = %d ,x > y ? x : y);
Copyright 2009 Accenture All Rights Reserved.

The maximum is = 6

29

Logical operators
Logical Operators are used to Combine 2 (or) more Relational Expressions, to check more complicated conditions. ! inverts a boolean value && || evaluate operands conditionally
! && || NOT AND OR

Truth Table
Op1 false false true true Op2 false true false true !Op1 true true false false Op1 && Op2 false false false true Op1 || Op2 false true true true
30

Copyright 2009 Accenture All Rights Reserved.

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

52

Programming Techniques Module 3.1: Introduction to C

3.1_IntroductionToC.ppt

Assignment operators
Assignment operators are used to set the value of a variable
= += -= *= /= %= &= |= ^= Assign Add and assign Subtract and assign Multiply and assign Divide and assign Modulo and assign AND and assign OR and assign XOR and assign
31

Copyright 2009 Accenture All Rights Reserved.

Assignment operators (Cont.)


Sample code
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; Sample output: pritnf ("Tax: %f " , vatAmount); Gross Sales: 240.0 /* compute discount*/ Tax: 24.0 discRate /= 100; Discount: 39.6 discAmount = salesAmount * discRate; Please pay: 224.4 salesAmount -= discAmount; printf ("Discount: %f" , discAmount); printf ("Please pay: %f, salesAmount);
Copyright 2009 Accenture All Rights Reserved.

32

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

53

Programming Techniques Module 3.1: Introduction to C

3.1_IntroductionToC.ppt

Evaluation order
Evaluation order of operators in C is as follows:
Level 1 2 Unary Arithmetic Operators ++, --, +, -, ( ), Logical not (!)
*, /, % (Equal precedence from left to right) +, - (Equal precedence from left to right)

3 4 5 6

Comparison Logical Conditional Assignment

<, <=, >, >=, ==, != &&, || ?: =, +=, -=, *=, /=


33

Copyright 2009 Accenture All Rights Reserved.

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

Copyright 2009 Accenture All Rights Reserved.

34

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

54

Programming Techniques Module 3.1: Introduction to C

3.1_IntroductionToC.ppt

Types of flow control


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

Copyright 2009 Accenture All Rights Reserved.

35

if-else
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 */ } Copyright 2009 Accenture All Rights Reserved.

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..."); }
36

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

55

Programming Techniques Module 3.1: Introduction to C

3.1_IntroductionToC.ppt

switch()
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 break is encountered default is executed if none of the other cases match the exp char sex='M'; Syntax:
switch (exp) { case val: /* statements here*/ case val: /* statements here*/ default: /* statements here*/ }
Copyright 2009 Accenture All Rights Reserved.

Example:

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!"); }

37

Loops
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 dowhile for

Copyright 2009 Accenture All Rights Reserved.

38

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

56

Programming Techniques Module 3.1: Introduction to C

3.1_IntroductionToC.ppt

Guidelines to use Loops


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
Copyright 2009 Accenture All Rights Reserved.

39

while()
while() performs statements repeatedly while condition remains true
while (condition) {
Syntax:

/* braces optional*/ here*/

/* }

statements

Output:

Example:

int ctr=10; while (ctr > 0) { pritnf("Timer: %d" , ctr-); }

Copyright 2009 Accenture All Rights Reserved.

Timer: Timer: Timer: Timer: Timer: Timer: Timer: Timer: Timer: Timer:

10 9 8 7 6 5 4 3 2 1

40

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

57

Programming Techniques Module 3.1: Introduction to C

3.1_IntroductionToC.ppt

Facts about while()


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

Copyright 2009 Accenture All Rights Reserved.

41

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

Syntax:

Output:
do /* statements here*/ while (condition);

Example:

int ctr=0; do printf("Timer: %d" , ctr++); while (ctr < 10); /* next statement*/
Copyright 2009 Accenture All Rights Reserved.

Timer: Timer: Timer: Timer: Timer: Timer: Timer: Timer: Timer: Timer:

0 1 2 3 4 5 6 7 8 9
42

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

58

Programming Techniques Module 3.1: Introduction to C

3.1_IntroductionToC.ppt

Facts about do-while()


Flexible Location of the test for completion :
At the End : The body isn't necessarily executed at least once

Copyright 2009 Accenture All Rights Reserved.

43

for()
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*/ }
44

Copyright 2009 Accenture All Rights Reserved.

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

59

Programming Techniques Module 3.1: Introduction to C

3.1_IntroductionToC.ppt

for() (Cont.)
A good choice when you need to loop that executes a specified number of times Use it for simple activities which dont require internal loop controls.
Output
The The The The The The The The The The number number number number number number number number number number is is is is is is is is is is 1 2 3 4 5 6 7 8 9 10
45

Example
for( i=1; i<=10; i++) printf( the number is %d:, i);

Copyright 2009 Accenture All Rights Reserved.

while vs. for ()


Use a while loop, if there is a condition under which execution has to jump out of a loop Dont 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 dont require internal loop
controls.

Copyright 2009 Accenture All Rights Reserved.

46

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

60

Programming Techniques Module 3.1: Introduction to C

3.1_IntroductionToC.ppt

break
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() statements
Syntax
break;

Output
i=0 i=1 i=2 i=3 i=4 i=5 i=6 i=7 I is greater than 7
47

Example

for(i=0; i<=10; i++) { if (i>7) { printf( I is greater than 7); break; } else printf(i=%d,i); }

Copyright 2009 Accenture All Rights Reserved.

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 ); }

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

61

Programming Techniques Module 3.1: Introduction to C

3.1_IntroductionToC.ppt

continue
continue is used inside loops to start a new iteration
Syntax:

continue; for(i=1; i<=10; i++) { printf(i=%d,i); continue; printf(it will never get printed); }
Output

Example

i=1 i=2 i=3 i=4 i=5 i=6 i=7 i=8 i=9 i=10

Copyright 2009 Accenture All Rights Reserved.

48

Key points
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 ifs 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.

Copyright 2009 Accenture All Rights Reserved.

49

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

62

Programming Techniques Module 3.1: Introduction to C

3.1_IntroductionToC.ppt

Key points (Cont.)


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 thats 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.
Copyright 2009 Accenture All Rights Reserved.

50

C basics - Activity
Tasks
Hands on using basic concepts of C

Input Documents
Module 2_activities.doc
Exercise 3

60 minutes
Copyright 2009 Accenture All Rights Reserved.

51

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

63

Programming Techniques Module 3.2: Functions

3.2_Functions.ppt

Programming Techniques
Module 3.2: Functions

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

Course Code #IDCGRF001-A

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

Copyright 2009 Accenture All Rights Reserved.

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

64

Programming Techniques Module 3.2: Functions

3.2_Functions.ppt

Objectives
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

Copyright 2009 Accenture All Rights Reserved.

Functions
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 Copyright 2009 Accenture All Rights Reserved. scratch.

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

65

Programming Techniques Module 3.2: Functions

3.2_Functions.ppt

Naming Functions
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

Copyright 2009 Accenture All Rights Reserved.

Naming Functions (Cont.)


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
Copyright 2009 Accenture All Rights Reserved.

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

66

Programming Techniques Module 3.2: Functions

3.2_Functions.ppt

Defining a Function
A return type specifier specifies the type of data returned by the function Return_type name ( data type parameter1, data type parameter2, .....) The name is the identifier of A statement is the function { the function's // statements - A function is called by its body name } Braces { } surround the Each input parameter consists of a data type specifier followed block of a by an identifier/name statement Input 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
Copyright 2009 Accenture All Rights Reserved.

Example to Defining a Function


Sample code defining a function
Function Name
int Validate_Date (int d,int m, int y) { /* Logic of Date Validation comes here*/ : : return(flag); }

Integer type parameters or arguments

Return type use of return keyword


Copyright 2009 Accenture All Rights Reserved.

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

67

Programming Techniques Module 3.2: Functions

3.2_Functions.ppt

Example to write a function


Example of a function to find the cube of an integer

Function name
int Cube (int Number) { int Cbe; Cbe = Number*Number*Number; return (Cbe); }

Arguments Return Type

Copyright 2009 Accenture All Rights Reserved.

Accessing functions
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

Copyright 2009 Accenture All Rights Reserved.

10

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

68

Programming Techniques Module 3.2: Functions

3.2_Functions.ppt

Declaring a Function
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.

Copyright 2009 Accenture All Rights Reserved.

11

Declaring a Function (Cont.)


Name of the function ; Indicates end of declaration

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

Data type specifier indicates the type of data returned by the function Example :

Data type of the parameters or arguments

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

Copyright 2009 Accenture All Rights Reserved.

12

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

69

Programming Techniques Module 3.2: Functions

3.2_Functions.ppt

To call A Function
Function Call :
result=function_name(Argument1, ,ArgumentN);

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

Copyright 2009 Accenture All Rights Reserved.

13

Function Communication
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.

Copyright 2009 Accenture All Rights Reserved.

14

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

70

Programming Techniques Module 3.2: Functions

3.2_Functions.ppt

Formal & Actual Arguments


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

Copyright 2009 Accenture All Rights Reserved.

15

Scope of Variables
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

Copyright 2009 Accenture All Rights Reserved.

16

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

71

Programming Techniques Module 3.2: Functions

3.2_Functions.ppt

Global & local variables


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 functions 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
Copyright 2009 Accenture All Rights Reserved.

17

Parameter passing: Pass by value


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.

Copyright 2009 Accenture All Rights Reserved.

18

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

72

Programming Techniques Module 3.2: Functions

3.2_Functions.ppt

Advantages and Disadvantages


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 of the program via arguments.

Copyright 2009 Accenture All Rights Reserved.

19

Recursive Function
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

Copyright 2009 Accenture All Rights Reserved.

20

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

73

Programming Techniques Module 3.2: Functions

3.2_Functions.ppt

Recursive Function (Cont.)


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

Copyright 2009 Accenture All Rights Reserved.

21

Tips for using recursive functions


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 routines depth of recursion within the limits imposed by the size of the programs stack? Check if recursion the best way to implement the routine Dont use recursion for simple iteration

Copyright 2009 Accenture All Rights Reserved.

22

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

74

Programming Techniques Module 3.2: Functions

3.2_Functions.ppt

Use of functions
Advantages
Writing modular programs Reusability Easy testing & debugging Easy program modification

To handle the complexity of design


Divide & conquer Reusability of code

Copyright 2009 Accenture All Rights Reserved.

23

Key points
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
24

Copyright 2009 Accenture All Rights Reserved.

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

75

Programming Techniques Module 3.2: Functions

3.2_Functions.ppt

Functions - Activity
Tasks
Hands on using functions in C

Input Documents
Module 2_activities.doc
Exercise 4

60 minutes
Copyright 2009 Accenture All Rights Reserved.

25

Questions/ Comments
What questions or comments do you have?

Copyright 2009 Accenture All Rights Reserved.

26

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

76

Programming Techniques Module 4.1: Introduction to Arrays

4.1_IntroductionToArrays.ppt

Programming Techniques
Module 4.1 - Introduction to Arrays

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

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

Copyright 2009 Accenture All Rights Reserved.

IDCGRF001-A
Copyright 2009 Accenture All Rights Reserved.

77

Programming Techniques Module 4.1: Introduction to Arrays

4.1_IntroductionToArrays.ppt

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

Copyright 2009 Accenture All Rights Reserved.

What is an Array ?
An array is simply a sequence of A one-dimensional array Values either objects or primitives, all of the same type and packaged together under one identifier 0 0 0 0 name.
int numbers[4];
Object type Identifier name Indexing operator

int numbers [ 4 ] Indices

Copyright 2009 Accenture All Rights Reserved.

IDCGRF001-A
Copyright 2009 Accenture All Rights Reserved.

78

Programming Techniques Module 4.1: Introduction to Arrays

4.1_IntroductionToArrays.ppt

Why Arrays
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.

Copyright 2009 Accenture All Rights Reserved.

IDCGRF001-A
Copyright 2009 Accenture All Rights Reserved.

79

Programming Techniques Module 4.1: Introduction to Arrays

4.1_IntroductionToArrays.ppt

Arrays Mechanism
Array:
Consecutive group of memory locations Same name and type
Name of array (Note that all elements of this array have the same name: a )
a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9] a[10] a[11]
24 -5

To refer to a particular element, specify:


The array name The position number It is known as Index or Subscript

Position number of the element within array a

Copyright 2009 Accenture All Rights Reserved.

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.

IDCGRF001-A
Copyright 2009 Accenture All Rights Reserved.

80

Programming Techniques Module 4.1: Introduction to Arrays

4.1_IntroductionToArrays.ppt

Arrays Mechanism (continued)


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]);

Copyright 2009 Accenture All Rights Reserved.

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].

IDCGRF001-A
Copyright 2009 Accenture All Rights Reserved.

81

Programming Techniques Module 4.1: Introduction to Arrays

4.1_IntroductionToArrays.ppt

Creating an Array
There are three steps to creating an array: #include <stdio.h>
1. Declaration 2. Construction 3. Initialization

void main() { int scores[3]; scores[0] = 10; scores[1] = 7; scores[2] = 9; }


8

Copyright 2009 Accenture All Rights Reserved.

Using Arrays
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};

Copyright 2009 Accenture All Rights Reserved.

IDCGRF001-A
Copyright 2009 Accenture All Rights Reserved.

82

Programming Techniques Module 4.1: Introduction to Arrays

4.1_IntroductionToArrays.ppt

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 */ }

Copyright 2009 Accenture All Rights Reserved.

10

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 [] );

IDCGRF001-A
Copyright 2009 Accenture All Rights Reserved.

83

Programming Techniques Module 4.1: Introduction to Arrays

4.1_IntroductionToArrays.ppt

Example Using Array


/* illustrate use of arrays*/ #include<stdio.h> #define SIZE 5 void main(){ int num[5],i;

Output:
printf(enter elements of the array); for(i=0; i<SIZE; i++) scanf(%d,&num[i]);

Enter elements of the array 1 2 3 4 5 1 2 3 4 5

for(i=0; i<SIZE; i++) printf(%d,num[i]); }


Copyright 2009 Accenture All Rights Reserved.

11

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

Copyright 2009 Accenture All Rights Reserved.

12

IDCGRF001-A
Copyright 2009 Accenture All Rights Reserved.

84

Programming Techniques Module 4.1: Introduction to Arrays

4.1_IntroductionToArrays.ppt

Character Arrays (continued)


Input from keyboard
Example:
charStr1[ 10 ]; scanf(%s,charStr1);

Takes user input

Output to screen
Example:
printf(%s,charstr1);

Copyright 2009 Accenture All Rights Reserved.

13

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.

Copyright 2009 Accenture All Rights Reserved.

14

IDCGRF001-A
Copyright 2009 Accenture All Rights Reserved.

85

Programming Techniques Module 4.1: Introduction to Arrays

4.1_IntroductionToArrays.ppt

Input/Output of Strings
String Functions Description
Unformatted input function. can read multiple word in a string (read sentences). Good for space management.

gets()
Input String

scanf() puts()
Output String

Formatted input function. can read only single word at a time. Unformatted output function. Prints the string and puts the cursor on the next line. Formatted output function. New line char (\n) is required to move to the next line.

printf()

Copyright 2009 Accenture All Rights Reserved.

15

String - Example
Sample Code
/*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); }

Sample Output Enter the first name: John Greetings John

Copyright 2009 Accenture All Rights Reserved.

16

IDCGRF001-A
Copyright 2009 Accenture All Rights Reserved.

86

Programming Techniques Module 4.1: Introduction to Arrays

4.1_IntroductionToArrays.ppt

String Library Functions (continued)


String Library Function Description

strlen(string) strcat(str1,str2)

Returns an integer Returns str1

strcmp(str1,str2)

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

strcpy(str1,str2)

Returns str1

Copyright 2009 Accenture All Rights Reserved.

17

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 str1 3. 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

IDCGRF001-A
Copyright 2009 Accenture All Rights Reserved.

87

Programming Techniques Module 4.1: Introduction to Arrays

4.1_IntroductionToArrays.ppt

Example- Using String Functions


void 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=11 } Output
The Target string is=programming The concatenated string is=programming techniques Output of comparing strings is=0

Copyright 2009 Accenture All Rights Reserved.

18

Multi-Dimensional Arrays
Multi-dimensional arrays with rows and columns
Like matrices, specify row then column
Column 0 Column 1
Column 1

Column 2
Column 2

Column 3
Column 3

Row 0 Row 1 Row 2

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

Column 0

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

Column subscript Array name Row subscript

Copyright 2009 Accenture All Rights Reserved.

19

IDCGRF001-A
Copyright 2009 Accenture All Rights Reserved.

88

Programming Techniques Module 4.1: Introduction to Arrays

4.1_IntroductionToArrays.ppt

Multi-Dimensional Arrays (continued)


Initializing:
1 2 4

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

Initializers grouped by row in braces


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

Copyright 2009 Accenture All Rights Reserved.

20

IDCGRF001-A
Copyright 2009 Accenture All Rights Reserved.

89

Programming Techniques Module 4.1: Introduction to Arrays

4.1_IntroductionToArrays.ppt

Advantages of Multidimensional Array


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* []

Copyright 2009 Accenture All Rights Reserved.

21

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.

IDCGRF001-A
Copyright 2009 Accenture All Rights Reserved.

90

Programming Techniques Module 4.1: Introduction to Arrays

4.1_IntroductionToArrays.ppt

Array - Activity
Tasks
Hands on using arrays in C

Input Documents
Module 3_activities.doc

30 minutes
Copyright 2009 Accenture All Rights Reserved.

22

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]
Copyright 2009 Accenture All Rights Reserved.

23

IDCGRF001-A
Copyright 2009 Accenture All Rights Reserved.

91

Programming Techniques Module 4.2: Pointers

4.2_Pointers.ppt

Programming Techniques
Module 4.2 - Pointers

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

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

92

Programming Techniques Module 4.2: Pointers

4.2_Pointers.ppt

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

Copyright 2009 Accenture All Rights Reserved.

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

93

Programming Techniques Module 4.2: Pointers

4.2_Pointers.ppt

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

Copyright 2009 Accenture All Rights Reserved.

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

94

Programming Techniques Module 4.2: Pointers

4.2_Pointers.ppt

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

Copyright 2009 Accenture All Rights Reserved.

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 master Can Simulate call-by-reference Has close relationship with arrays and strings

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

95

Programming Techniques Module 4.2: Pointers

4.2_Pointers.ppt

Pointers
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

Copyright 2009 Accenture All Rights Reserved.

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.

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

96

Programming Techniques Module 4.2: Pointers

4.2_Pointers.ppt

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)
count

countPtr

Indirection (*)
Referencing the value in memory a pointer points to

Copyright 2009 Accenture All Rights Reserved.

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.

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

97

Programming Techniques Module 4.2: Pointers

4.2_Pointers.ppt

Pointer Variable Declaration (continued)


Pointer declarations

* indicates variable is a pointer


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

Each declared pointer requires its own asterisk


int *Ptr1, *Ptr2;

Copyright 2009 Accenture All Rights Reserved.

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 its own * preceding its name.

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

98

Programming Techniques Module 4.2: Pointers

4.2_Pointers.ppt

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!

Copyright 2009 Accenture All Rights Reserved.

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.

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

99

Programming Techniques Module 4.2: Pointers

4.2_Pointers.ppt

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 500000

yptr 600000 600000

y 5

address of y is value of yptr


Copyright 2009 Accenture All Rights Reserved.

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

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

100

Programming Techniques Module 4.2: Pointers

4.2_Pointers.ppt

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

Copyright 2009 Accenture All Rights Reserved.

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

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

101

Programming Techniques Module 4.2: Pointers

4.2_Pointers.ppt

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;
Copyright 2009 Accenture All Rights Reserved.

Data Table Name i j Type int int Description integer variable integer variable Value 5 10

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;
Copyright 2009 Accenture All Rights Reserved.

/* declare a pointer-to-integer variable */

Data Table Name i j ptr Type int int int * Description integer variable integer variable integer pointer variable Value 5 10

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

102

Programming Techniques Module 4.2: Pointers

4.2_Pointers.ppt

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;
Copyright 2009 Accenture All Rights Reserved.

Data Table Name i j ptr pptr Type int int int * int ** Description integer variable integer variable integer pointer variable integer pointer pointer variable Value 5 10

Double Indirection

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; Data Table ptr = &j; Name Type Description **pptr = 9; i int integer variable *pptr = &i; j int integer variable *ptr = -2;
ptr int * integer pointer variable pptr *ptr
Copyright 2009 Accenture All Rights Reserved.

Value 5 10 address of i

int ** int

integer pointer pointer variable de-reference of ptr 5

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

103

Programming Techniques Module 4.2: Pointers

4.2_Pointers.ppt

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; Data Table ptr = &j; Name Type Description **pptr = 9; i int integer variable *pptr = &i; j int integer variable *ptr = -2; ptr int * integer pointer variable
pptr *pptr int ** int * integer pointer pointer variable de-reference of pptr

Value 5 10 address of i address of ptr value of ptr (address of i)

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;

Data Table Name i j ptr pptr *ptr Type int int int * int ** int Description integer variable integer variable integer pointer variable integer pointer pointer variable de-reference of ptr Value 3 10 address of i address of ptr 3

Copyright 2009 Accenture All Rights Reserved.

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

104

Programming Techniques Module 4.2: Pointers

4.2_Pointers.ppt

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;

Data Table Name i j ptr pptr **pptr Type int int int * int ** int Description integer variable integer variable integer pointer variable integer pointer pointer variable de-reference of de-reference of pptr Value 7 10 address of i address of ptr 7

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;

Data Table Name i j ptr pptr *ptr Type int int int * int ** int Description integer variable integer variable integer pointer variable integer pointer pointer variable de-reference of ptr Value 7 10 address of j address of ptr 10

Copyright 2009 Accenture All Rights Reserved.

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

105

Programming Techniques Module 4.2: Pointers

4.2_Pointers.ppt

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;

Data Table Name i j ptr pptr **pptr Type int int int * int ** int Description integer variable integer variable integer pointer variable integer pointer pointer variable de-reference of de-reference of pptr Value 7 9 address of j address of ptr 9

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;

Data Table Name i j ptr pptr *pptr Type int int int * int ** int * Description integer variable integer variable integer pointer variable integer pointer pointer variable de-reference of pptr Value 7 9 address of i address of ptr value of ptr (address of i)

Copyright 2009 Accenture All Rights Reserved.

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

106

Programming Techniques Module 4.2: Pointers

4.2_Pointers.ppt

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;

Data Table Name i j ptr pptr *ptr Type int int int * int ** int Description integer variable integer variable integer pointer variable integer pointer pointer variable de-reference of ptr Value -2 9 address of i address of ptr -2

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 ]

Copyright 2009 Accenture All Rights Reserved.

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

107

Programming Techniques Module 4.2: Pointers

4.2_Pointers.ppt

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 of Pointers (continued)


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

Copyright 2009 Accenture All Rights Reserved.

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

108

Programming Techniques Module 4.2: Pointers

4.2_Pointers.ppt

Arrays of Pointers (continued)


Arrays can contain pointers
suit array has a fixed size, but strings can be of any size

suit[0] suit[1] suit[2]

H D C S

e i l p

a a u a

r m b d

t o s e

s n \0 s

\0 d s \0

suit[3]

\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

Copyright 2009 Accenture All Rights Reserved.

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

109

Programming Techniques Module 4.2: Pointers

4.2_Pointers.ppt

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

Copyright 2009 Accenture All Rights Reserved.

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.

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

110

Programming Techniques Module 4.2: Pointers

4.2_Pointers.ppt

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;
Copyright 2009 Accenture All Rights Reserved.

Data Table Name a[0] a[1] a[2] a[3] ptr *ptr Type float float float float float * float Description float array element (variable) float array element (variable) float array element (variable) float array element (variable) float pointer variable de-reference of float pointer variable ? Value ? ? ? ?

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

111

Programming Techniques Module 4.2: Pointers

4.2_Pointers.ppt

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;
Data Table Name a[0] a[1] a[2] a[3] ptr *ptr Type float float float float float * float Description float array element (variable) float array element (variable) float array element (variable) float array element (variable) float pointer variable de-reference of float pointer variable Value ? ? ? ? address of a[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;

Data Table Name a[0] a[1] a[2] a[3] ptr *ptr Type float float float float float * float Description float array element (variable) float array element (variable) float array element (variable) float array element (variable) float pointer variable de-reference of float pointer variable Value ? ? 3.14 ? address of a[2] 3.14

Copyright 2009 Accenture All Rights Reserved.

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

112

Programming Techniques Module 4.2: Pointers

4.2_Pointers.ppt

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;
Data Table Name a[0] a[1] a[2] a[3] ptr *ptr Type float float float float float * float Description float array element (variable) float array element (variable) float array element (variable) float array element (variable) float pointer variable de-reference of float pointer variable Value ? ? 3.14 ? address of a[3] ?

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;
Data Table Name a[0] a[1] a[2] a[3] ptr *ptr Type float float float float float * float Description float array element (variable) float array element (variable) float array element (variable) float array element (variable) float pointer variable de-reference of float pointer variable Value ? ? 3.14 9.0 address of a[3] 9.0

Copyright 2009 Accenture All Rights Reserved.

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

113

Programming Techniques Module 4.2: Pointers

4.2_Pointers.ppt

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;
Data Table Name a[0] a[1] a[2] a[3] ptr *ptr Type float float float float float * float Description float array element (variable) float array element (variable) float array element (variable) float array element (variable) float pointer variable de-reference of float pointer variable Value ? ? 3.14 9.0 address of a[0] ?

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;
Data Table Name a[0] a[1] a[2] a[3] ptr *ptr Type float float float float float * float Description float array element (variable) float array element (variable) float array element (variable) float array element (variable) float pointer variable de-reference of float pointer variable Value 6.0 ? 3.14 9.0 address of a[0] 6.0

Copyright 2009 Accenture All Rights Reserved.

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

114

Programming Techniques Module 4.2: Pointers

4.2_Pointers.ppt

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;
Data Table Name a[0] a[1] a[2] a[3] ptr *ptr Type float float float float float * float Description float array element (variable) float array element (variable) float array element (variable) float array element (variable) float pointer variable de-reference of float pointer variable Value 6.0 ? 3.14 9.0 address of a[2] 3.14

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;
Data Table Name a[0] a[1] a[2] a[3] ptr *ptr Type float float float float float * float Description float array element (variable) float array element (variable) float array element (variable) float array element (variable) float pointer variable de-reference of float pointer variable Value 6.0 ? 7.0 9.0 address of a[2] 7.0

Copyright 2009 Accenture All Rights Reserved.

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

115

Programming Techniques Module 4.2: Pointers

4.2_Pointers.ppt

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;

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

*ptr = 7.0;
Copyright 2009 Accenture All Rights Reserved.

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

116

Programming Techniques Module 4.2: Pointers

4.2_Pointers.ppt

Pointers and functions


Modify behavior in argument passing Pass By reference method
void f(int j) { j = 5; } void g() { int i = 3; f(i); } } } void g() { int i = 3; f(&i); void f(int *ptr) { *ptr = 5;

i=3

i=5

Copyright 2009 Accenture All Rights Reserved.

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.

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

117

Programming Techniques Module 4.2: Pointers

4.2_Pointers.ppt

Pointers - Activity
Tasks
Hands on using pointers in C

Input Documents
Module 3_activities.doc

30 minutes
Copyright 2009 Accenture All Rights Reserved.

Key Points
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

Copyright 2009 Accenture All Rights Reserved.

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

118

Programming Techniques Module 4.3: Memory Management

4.3_MemoryManagement.ppt

Programming Techniques
Module 4.3 Memory Management

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

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

Copyright 2009 Accenture All Rights Reserved.

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

119

Programming Techniques Module 4.3: Memory Management

4.3_MemoryManagement.ppt

Objectives
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

Copyright 2009 Accenture All Rights Reserved.

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

120

Programming Techniques Module 4.3: Memory Management

4.3_MemoryManagement.ppt

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

Copyright 2009 Accenture All Rights Reserved.

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. Its 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. */ }

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

121

Programming Techniques Module 4.3: Memory Management

4.3_MemoryManagement.ppt

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 are created 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 cant access these Variables.

On each entry into a function or a block, a fresh set of that function or blocks automatic objects is created. The default value of automatic variables is indeterminate.
Copyright 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

Copyright 2009 Accenture All Rights Reserved.

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

122

Programming Techniques Module 4.3: Memory Management

4.3_MemoryManagement.ppt

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.

Copyright 2009 Accenture All Rights Reserved.

Static Storage (continued )


The following reside in static memory:
Global objects Static variables in functions

Copyright 2009 Accenture All Rights Reserved.

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

123

Programming Techniques Module 4.3: Memory Management

4.3_MemoryManagement.ppt

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

Copyright 2009 Accenture All Rights Reserved.

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

124

Programming Techniques Module 4.3: Memory Management

4.3_MemoryManagement.ppt

Dynamic Memory Allocation


The malloc function is the basic function used to allocate memory on the heap in C. Its prototype is void *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.

Copyright 2009 Accenture All Rights Reserved.

10

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); } /* allocation succeeded */ /* We couldn't allocate any memory, so exit */

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

125

Programming Techniques Module 4.3: Memory Management

4.3_MemoryManagement.ppt

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

Copyright 2009 Accenture All Rights Reserved.

11

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.

Copyright 2009 Accenture All Rights Reserved.

12

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

126

Programming Techniques Module 4.3: Memory Management

4.3_MemoryManagement.ppt

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*/

Copyright 2009 Accenture All Rights Reserved.

13

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.

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

127

Programming Techniques Module 4.3: Memory Management

4.3_MemoryManagement.ppt

Dangling Pointer
A dangling pointer is created when you delete the pointers 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!

Copyright 2009 Accenture All Rights Reserved.

14

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.

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

128

Programming Techniques Module 4.3: Memory Management

4.3_MemoryManagement.ppt

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 developers duty to return it back. As there is no built-in garbage collector, C programmers must be very careful with dynamic memory.

Copyright 2009 Accenture All Rights Reserved.

15

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

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

129

Programming Techniques Module 4.3: Memory Management

4.3_MemoryManagement.ppt

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
Copyright 2009 Accenture All Rights Reserved.

16

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

130

Programming Techniques Module 4.4: Introduction to Structures and Unions

4.4_IntroductionToStructures.ppt

Programming Techniques
Module 4.4: Introduction To Structures And Unions

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

Contents
Defining Structures Declaring Structures Defining Unions Declaring Unions

Copyright 2009 Accenture All Rights Reserved.

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

131

Programming Techniques Module 4.4: Introduction to Structures and Unions

4.4_IntroductionToStructures.ppt

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.

Copyright 2009 Accenture All Rights Reserved.

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

132

Programming Techniques Module 4.4: Introduction to Structures and Unions

4.4_IntroductionToStructures.ppt

Structures
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.
Copyright 2009 Accenture All Rights Reserved.

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

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

133

Programming Techniques Module 4.4: Introduction to Structures and Unions

4.4_IntroductionToStructures.ppt

Structures (continued)
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

Copyright 2009 Accenture All Rights Reserved.

Defining and Declaring a Structure


Structure template defining structure
struct Person { /* Beginning of structure template*/ int Age; int Height, Weight; char Name[50]; } Member; /* End of structure template*/ main() {

Structure variable Declaring a variable

Use of .(dot) operator: Assigning value to an element of a structure variable Reading value to an element of a structure variable
Copyright 2009 Accenture All Rights Reserved.

struct Person Father; Father. Age=50; scanf(%d,&member.Height); /* Continues the program */ }


6

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

134

Programming Techniques Module 4.4: Introduction to Structures and Unions

4.4_IntroductionToStructures.ppt

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

Copyright 2009 Accenture All Rights Reserved.

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.

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

135

Programming Techniques Module 4.4: Introduction to Structures and Unions

4.4_IntroductionToStructures.ppt

Defining and Declaring a Union


Union template defining union union PersonalData { /* Beginning of union template */ char socialSecurityNumber[15]; char empID[10]; } Member; */ main() { Use of .(dot) operator: Assigning value to an element of a union variable Reading value to an element of a union variable
Copyright 2009 Accenture All Rights Reserved.

/* End of Union template Union Variable Declaring a Variable

union PersonData Person; Person.empID=1020345; scanf(%s,Member.empID); }


8

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

136

Programming Techniques Module 4.4: Introduction to Structures and Unions

4.4_IntroductionToStructures.ppt

Defining and Declaring a Union (continued)


Name of the new data type
union PersonalData { // Beginning of union template

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

char socialSecurityNumber[15]; char empID[10]; } Member; template main() { // End of Union

Only one element can hold a value A variable of union type can hold one value of any type declared in the union
Copyright 2009 Accenture All Rights Reserved.

union PersonData Person; Person.empID=1020345; // Continue the program }

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 structures Example : 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.

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

137

Programming Techniques Module 4.4: Introduction to Structures and Unions

4.4_IntroductionToStructures.ppt

Difference - Structure and Union


Structures
uses struct keyword to define a structure Memory is separately allocated for each data member of the structure

Unions
uses union keyword to define a union Allocates memory only to the largest element of the union

Copyright 2009 Accenture All Rights Reserved.

10

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.

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

138

Programming Techniques Module 4.4: Introduction to Structures and Unions

4.4_IntroductionToStructures.ppt

Structures & Unions - Activity


Tasks
Hands on using Structures and Unions in C

Input Documents
Module 3_activities.doc

30 minutes
Copyright 2009 Accenture All Rights Reserved.

11

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

Copyright 2009 Accenture All Rights Reserved.

12

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

139

Programming Techniques Module 4.5: Coding Conventions

4.5_CodingConventions.ppt

Programming Techniques
4.5 Coding Conventions

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

Contents
Coding Conventions Variable Declaration Best Practices
Naming Variables Statements if-else switch() while() break & continue Naming Functions Arrays

Caution when using Loops


Copyright 2009 Accenture All Rights Reserved.

140

Copyright 2009 Accenture All Rights Reserved.

Programming Techniques Module 4.5: Coding Conventions

4.5_CodingConventions.ppt

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

Copyright 2009 Accenture All Rights Reserved.

141

Copyright 2009 Accenture All Rights Reserved.

Programming Techniques Module 4.5: Coding Conventions

4.5_CodingConventions.ppt

Coding Conventions: Best Practices


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
4

Copyright 2009 Accenture All Rights Reserved.

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

Copyright 2009 Accenture All Rights Reserved.

Programming Techniques Module 4.5: Coding Conventions

4.5_CodingConventions.ppt

Variable Declaration: Best Practices


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! */
5

Copyright 2009 Accenture All Rights Reserved.

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

Copyright 2009 Accenture All Rights Reserved.

Programming Techniques Module 4.5: Coding Conventions

4.5_CodingConventions.ppt

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

Copyright 2009 Accenture All Rights Reserved.

Naming Variables : Best practices(continued)


Variable name should fully and accurately describe what the variable represents
char 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*/

Copyright 2009 Accenture All Rights Reserved.

144

Copyright 2009 Accenture All Rights Reserved.

Programming Techniques Module 4.5: Coding Conventions

4.5_CodingConventions.ppt

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 names
char 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*/
Copyright 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. Dont misspell the names while abbreviating and ensure abbreviation is not making names completely arbitrary. Ensure, the abbreviation doesnt 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*/
Copyright 2009 Accenture All Rights Reserved.

145

Copyright 2009 Accenture All Rights Reserved.

Programming Techniques Module 4.5: Coding Conventions

4.5_CodingConventions.ppt

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*/

Copyright 2009 Accenture All Rights Reserved.

10

Statements - Best Practices


Statements
Each line should contain only one statement. Example:
argv++; /* Correct */ argc--; /* Correct */ argv++; argc--; /* AVOID! */

Copyright 2009 Accenture All Rights Reserved.

11

146

Copyright 2009 Accenture All Rights Reserved.

Programming Techniques Module 4.5: Coding Conventions

4.5_CodingConventions.ppt

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*/

Copyright 2009 Accenture All Rights Reserved.

12

147

Copyright 2009 Accenture All Rights Reserved.

Programming Techniques Module 4.5: Coding Conventions

4.5_CodingConventions.ppt

if else : Best Practices


Check if all conditions are covered. Ensure the tests branch correctly on equality
if (average<60) grade='C'; else if (average<70 && average>60) grade='B';

Dont 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

Copyright 2009 Accenture All Rights Reserved.

13

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 conditions Is 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

Copyright 2009 Accenture All Rights Reserved.

Programming Techniques Module 4.5: Coding Conventions

4.5_CodingConventions.ppt

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
Copyright 2009 Accenture All Rights Reserved.

14

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=DataSummaryError else { PrintSummary(SummarData) SaveSummaryData(SummaryData, Status) if (Status= =Error) ErrorType=SummarySaveError else { UpdateAllAccounts(); EraseUndoFile(); ErrorType=None; } else { ErrorType=FileReadError; }

149

Copyright 2009 Accenture All Rights Reserved.

Programming Techniques Module 4.5: Coding Conventions

4.5_CodingConventions.ppt

if else : Best Practices(continued)


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; }
Copyright 2009 Accenture All Rights Reserved.

else { ErrorType=SummarySaveError; } else { ErrorType=DataSummaryError; } else { ErrorType=FileReadError; } else { ErrorType=FileOpenError ; }

Good Practice
15

150

Copyright 2009 Accenture All Rights Reserved.

Programming Techniques Module 4.5: Coding Conventions

4.5_CodingConventions.ppt

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 Dont assign or create variables specially for a switch

Copyright 2009 Accenture All Rights Reserved.

16

Always order cases meaningfully : Keep cases in a sequence Keep the actions for each case simple call other routines if necessary. : dont keep much code with in a switch. Break it into routines and call these routines under each cases Use the default clause to detect and report unexpected cases : Keep the default cause present in a switch statement which will record all the unexpected cases Use break to end each case statement : Use break statement in switch Dont use the dummy variable to be able to use the case statement : Work on actual variables, dont assign or create variables specially for switch

151

Copyright 2009 Accenture All Rights Reserved.

Programming Techniques Module 4.5: Coding Conventions

4.5_CodingConventions.ppt

if else & switch : Best Practices


A switch statement should be used for simple data thats easily categorized. If your data isn't simple, use if-else ifelse.

Copyright 2009 Accenture All Rights Reserved.

17

152

Copyright 2009 Accenture All Rights Reserved.

Programming Techniques Module 4.5: Coding Conventions

4.5_CodingConventions.ppt

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(); else printf (\n Invalid Option);
Copyright 2009 Accenture All Rights Reserved.

Bad Practice

Good Practice

18

A case statement should be used for simple data thats 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

Copyright 2009 Accenture All Rights Reserved.

Programming Techniques Module 4.5: Coding Conventions

4.5_CodingConventions.ppt

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 indexs final value

Copyright 2009 Accenture All Rights Reserved.

19

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

Copyright 2009 Accenture All Rights Reserved.

Programming Techniques Module 4.5: Coding Conventions

4.5_CodingConventions.ppt

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 indexs final value. Avoid empty loop. for (count=0;count<index; count++); // Avoid
Copyright 2009 Accenture All Rights Reserved.

20

Always enter the loop from one location only : Dont jump in a loop with a goto statement Put initialization code directly before the loop & Assure yourself that the loop ends. : Avoid code that depends on the loop indexs final value. Avoid empty loop

155

Copyright 2009 Accenture All Rights Reserved.

Programming Techniques Module 4.5: Coding Conventions

4.5_CodingConventions.ppt

Best Practices : Loop Example : While


An 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; }

Copyright 2009 Accenture All Rights Reserved.

21

Check if the duplication of code can be avoided with some other technique.

156

Copyright 2009 Accenture All Rights Reserved.

Programming Techniques Module 4.5: Coding Conventions

4.5_CodingConventions.ppt

while()
Example to illustrate to avoid the duplication of code :
/* 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; }

Copyright 2009 Accenture All Rights Reserved.

22

The while (TRUE) loop is equivalent to for(;;)

157

Copyright 2009 Accenture All Rights Reserved.

Programming Techniques Module 4.5: Coding Conventions

4.5_CodingConventions.ppt

break & continue : Best Practices


If you cant defend a break or a continue, dont 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

Copyright 2009 Accenture All Rights Reserved.

23

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

Copyright 2009 Accenture All Rights Reserved.

Programming Techniques Module 4.5: Coding Conventions

4.5_CodingConventions.ppt

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()
Copyright 2009 Accenture All Rights Reserved.

24

What is most important is that the naming convention should be consistent across the application.

159

Copyright 2009 Accenture All Rights Reserved.

Programming Techniques Module 4.5: Coding Conventions

4.5_CodingConventions.ppt

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
Copyright 2009 Accenture All Rights Reserved.

25

160

Copyright 2009 Accenture All Rights Reserved.

Programming Techniques Module 4.5: Coding Conventions

4.5_CodingConventions.ppt

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

Copyright 2009 Accenture All Rights Reserved.

26

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 thats 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 correct codes. 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

Copyright 2009 Accenture All Rights Reserved.

Programming Techniques Module 4.5: Coding Conventions

4.5_CodingConventions.ppt

Arrays : Best Practices(continued)


If an array is multidimensional, make sure its subscripts are used in the correct order
Array[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

Copyright 2009 Accenture All Rights Reserved.

27

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

Copyright 2009 Accenture All Rights Reserved.

Programming Techniques Module 4.5: Coding Conventions

4.5_CodingConventions.ppt

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

Copyright 2009 Accenture All Rights Reserved.

28

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 data If 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

Copyright 2009 Accenture All Rights Reserved.

Programming Techniques Module 4.5: Coding Conventions

4.5_CodingConventions.ppt

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

Copyright 2009 Accenture All Rights Reserved.

29

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 doesnt 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

Copyright 2009 Accenture All Rights Reserved.

Programming Techniques Module 4.5: Coding Conventions

4.5_CodingConventions.ppt

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

Copyright 2009 Accenture All Rights Reserved.

30

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 doesnt produce any symptoms. By setting pointers to NULL after freeing them, we dont 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 : Dont skimp on pointer variables. A variable shouldnt 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

Copyright 2009 Accenture All Rights Reserved.

Programming Techniques Module 4.5: Coding Conventions

4.5_CodingConventions.ppt

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.

Copyright 2009 Accenture All Rights Reserved.

31

166

Copyright 2009 Accenture All Rights Reserved.

Programming Techniques Module 5: Searching and Sorting

5_SearchingAndSorting.ppt

Programming Techniques
Module 5 Searching and Sorting

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

Contents
Introduction to searching techniques Types of Searching Introduction to sorting techniques Types of Sorting Introducing the concept of analysis of algorithms

Copyright 2009 Accenture All Rights Reserved.

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

167

Programming Techniques Module 5: Searching and Sorting

5_SearchingAndSorting.ppt

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

Copyright 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

Copyright 2009 Accenture All Rights Reserved.

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

168

Programming Techniques Module 5: Searching and Sorting

5_SearchingAndSorting.ppt

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.

Copyright 2009 Accenture All Rights Reserved.

Linear Search Algorithm


1. 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 value 5.Return -1 (indicates the element was not found)

Copyright 2009 Accenture All Rights Reserved.

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

169

Programming Techniques Module 5: Searching and Sorting

5_SearchingAndSorting.ppt

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

Copyright 2009 Accenture All Rights Reserved.

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.

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

170

Programming Techniques Module 5: Searching and Sorting

5_SearchingAndSorting.ppt

Binary Search Algorithm


1. 2. 3. 4. 5. Initialize Low to the index of the first element. Initialize High to the index of the last element. Repeat through step 6 while Low <= High Middle=(Low+High)/2 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 element High=Middle-1 else Low=Middle+1 7. return -1 (indicates element not found)
Copyright 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
Copyright 2009 Accenture All Rights Reserved.

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

171

Programming Techniques Module 5: Searching and Sorting

5_SearchingAndSorting.ppt

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

Copyright 2009 Accenture All Rights Reserved.

10

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

172

Programming Techniques Module 5: Searching and Sorting

5_SearchingAndSorting.ppt

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

Copyright 2009 Accenture All Rights Reserved.

11

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.

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

173

Programming Techniques Module 5: Searching and Sorting

5_SearchingAndSorting.ppt

Selection Sort Algorithm


1. 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 vector 5. Exchange first element in unsorted vector with smallest element.

Copyright 2009 Accenture All Rights Reserved.

12

Example - Selection sort


Original Array 42 23 74 11 58 94 36 Pass Number 1 11 23 74 42 58 94 36 2 11 23 74 42 58 94 36 3 11 23 36 42 58 94 74 4 11 23 36 42 58 94 74 5 11 23 36 42 58 94 74 6 11 23 36 42 58 74 94
13

Copyright 2009 Accenture All Rights Reserved.

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

174

Programming Techniques Module 5: Searching and Sorting

5_SearchingAndSorting.ppt

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.

Copyright 2009 Accenture All Rights Reserved.

14

Bubble Sort Algorithm


1. 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.

Copyright 2009 Accenture All Rights Reserved.

15

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

175

Programming Techniques Module 5: Searching and Sorting

5_SearchingAndSorting.ppt

Example- Bubble Sort


Original Array 74 65 58 42 23 11 Pass Number 1 65 58 42 23 11 74 2 58 42 23 11 65 74 3 42 23 11 58 65 74 4 23 11 42 58 65 74 5 11 23 42 58 65 74
16

Copyright 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
Copyright 2009 Accenture All Rights Reserved.

17

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

176

Programming Techniques Module 5: Searching and Sorting

5_SearchingAndSorting.ppt

Analysis of algorithms
Space Complexity
Indicates how much extra memory the algorithm needs

Time Complexity
Indicates how fast the algorithm runs

Copyright 2009 Accenture All Rights Reserved.

18

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

Copyright 2009 Accenture All Rights Reserved.

19

IDCGRF001-A Copyright 2009 Accenture All Rights Reserved.

177

Programming Techniques

Module1: Fundamental Programming Concepts

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,5Generate 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.)

IDCGRF001-A 2009 Accenture. All Rights Reserved.

Module1_activities.doc
1

Programming Techniques

Module1: Fundamental Programming Concepts

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. 2. 3. 4. 5. Remember motivation comes from within. Take responsibility for your own learning. Take notes from each presentation and activity. If you dont understand something, ask questions. Participate in course discussions. Practice what youve learned to keep your skills sharp.
1.

IDCGRF001-A 2009 Accenture. All Rights Reserved.

Module1_activities.doc
2

Programming Techniques

Module2: Introduction to C and Functions

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 employees 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

IDCGRF001-A 2009 Accenture. All Rights Reserved.

Module2_activities.doc
3

Programming Techniques

Module2: Introduction to C and Functions

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.

IDCGRF001-A 2009 Accenture. All Rights Reserved.

Module2_activities.doc
4

Programming Techniques

Module2: Introduction to C and Functions

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
IDCGRF001-A 2009 Accenture. All Rights Reserved. Module2_activities.doc
5

Programming Techniques

Module2: Introduction to C and Functions

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 61-70 71-80 81-90 91-100

F D C B A

Table 4. 2

Last digit

Modifier

1-3 4-7 8-0

<blank> +

Activity 4.6 Using recursive function Write a c program to find the Fibonacci series of N numbers

IDCGRF001-A 2009 Accenture. All Rights Reserved.

Module2_activities.doc
6

Programming Techniques

Module2: Introduction to C and Functions

Hints
1. 2. 3. 4. 5. Remember motivation comes from within. Take responsibility for your own learning. Take notes from each presentation and activity. If you dont understand something, ask questions. Participate in course discussions. Practice what youve learned to keep your skills sharp.

IDCGRF001-A 2009 Accenture. All Rights Reserved.

Module2_activities.doc
7

Programming Techniques

Module3: Arrays, Pointers And Structures

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.
IDCGRF001-A 2009 Accenture. All Rights Reserved. Module3_activities.doc
8

Programming Techniques

Module3: Arrays, Pointers And Structures

Activity 5.9 Write a function that scans the English text stored in an array and determines the number of words in it.

IDCGRF001-A 2009 Accenture. All Rights Reserved.

Module3_activities.doc
9

Programming Techniques

Module3: Arrays, Pointers And Structures

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

IDCGRF001-A 2009 Accenture. All Rights Reserved.

Module3_activities.doc
10

Programming Techniques

Module3: Arrays, Pointers And Structures

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 3) Rs400/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.) 2) Rs300/hr 4) Rs500/hr

IDCGRF001-A 2009 Accenture. All Rights Reserved.

Module3_activities.doc
11

Programming Techniques

Module3: Arrays, Pointers And Structures

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. 2. 3. 4. 5. Remember motivation comes from within. Take responsibility for your own learning. Take notes from each presentation and activity. If you dont understand something, ask questions. Participate in course discussions. Practice what youve learned to keep your skills sharp.
1.

IDCGRF001-A 2009 Accenture. All Rights Reserved.

Module3_activities.doc
12

Programming Techniques

Module4: Searching and Sorting

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. 2. 3. 4. 5. Remember motivation comes from within. Take responsibility for your own learning. Take notes from each presentation and activity. If you dont understand something, ask questions. Participate in course discussions. Practice what youve learned to keep your skills sharp.
1.

IDCGRF001-A 2009 Accenture. All Rights Reserved.

Module4_activities.doc
13

Programming Techniques

Case Study 1

C A S E S T U D Y 1 - PA R T I C I PA N T G U I D E

Course Code IDCGRF001-A Accenture 2009 All Rights Reserved

Page 1 of 5

Programming Techniques

Case Study 1

Case Study 1: Diet Menu Card for a Fitness Center

Introduction: In US, the nations 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 causes 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. FUHCCs 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.

Course Code IDCGRF001-A Accenture 2009 All Rights Reserved

Page 2 of 5

Programming Techniques

Case Study 1

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 doesnt 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.

Course Code IDCGRF001-A Accenture 2009 All Rights Reserved

Page 3 of 5

Programming Techniques

Case Study 1

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) Min (scrambled eggs) Max (scrambled eggs) = cost per serving of scrambled eggs = minimum number of servings to eat = 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

Course Code IDCGRF001-A Accenture 2009 All Rights Reserved

Page 4 of 5

Programming Techniques

Case Study 1

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) eggs) x(oranges) min(oranges)max(scrambled * C(oranges) +

eggs)x(scrambled

min(scrambled

eggs)max(C)

C(scrambled eggs) min(C) max(A) A(oranges)

Course Code IDCGRF001-A Accenture 2009 All Rights Reserved

Page 5 of 5

Programming Techniques

Case Study 1: Values

Complete nutritional value & Price of the foods Foods Banana Grapes Carrots,Raw Oranges Celery, Raw Potatoes, Baked Peppers, Sweet, Raw Frozen Broccoli Tofu Apple,Raw,W/Skin Tomato,Red,Ripe,Raw Frozen Corn Spaghetti W/ Sauce Wheat Bread White Bread Kiwifruit,Raw,Fresh Lettuce,Iceberg,Raw Bagels Chocolate Chip Cookies Oatmeal Cookies White Tuna in Water Cheddar Cheese Apple Pie Butter,Regular 3.3% Fat,Whole Milk 2% Lowfat Milk Skim Milk Price in Rs. /Serving 25.00 20.00 11.00 20.00 20.00 20.00 43.00 76.00 31.00 34.00 56.00 20.00 65.00 41.00 38.00 49.00 37.00 64.00 20.00 27.00 140.00 42.00 30.00 32.00 25.00 30.00 32.00 Serving Size 1 Fruit,Wo/Skn&Seeds 10 Fruits,Wo/Rf 1/2 Cup Shredded 1 Frt,2-5/8 Diam 1 Stalk 1/2 Cup 1 Pepper 10 Oz Pkg 1/4 block 1 Fruit,3/Lb,Wo/Rf 1 Tomato, 2-3/5 In 1/2 Cup 1 1/2 Cup 1 Sl 1 Sl 1 Med Frt,Wo/Skin 1 Leaf 1 Oz 1 Cookie 1 Cookie 3 Oz 1 Oz 1 Oz 1 Pat 1C 1C 1C Calories 104.9 15.1 23.7 61.6 6.4 171.5 20 73.8 88.2 81.4 25.8 72.2 358.2 65 65 46.4 2.6 78 78.1 81 115.6 112.7 67.2 35.8 149.9 121.2 85.5 Cholesterol mg 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 5.1 0 35.7 29.4 0 10.9 33.2 18.3 4.4 Total_Fat g 0.5 0.1 0.1 0.2 0.1 0.2 0.1 0.8 5.5 0.5 0.4 0.6 12.3 1 1 0.3 0 0.5 4.5 3.3 2.1 9.3 3.1 4.1 8.1 4.7 0.4 Sodium mg 1.1 0.5 19.2 0 34.8 15.2 1.5 68.2 8.1 0 11.1 2.5 1237.1 134.5 132.5 3.8 1.8 151.4 57.8 68.9 333.2 173.7 75.4 41.3 119.6 121.8 126.2 Carbohydrates g 26.7 4.1 5.6 15.4 1.5 39.9 4.8 13.6 2.2 21 5.7 17.1 58.3 12.4 11.8 11.3 0.4 15.1 9.3 12.4 0 0.4 9.6 0 11.4 11.7 11.9 Dietary_Fiber g 2.7 0.2 1.6 3.1 0.7 3.2 1.3 8.5 1.4 3.7 1.4 2 11.6 1.3 1.1 2.6 0.3 0.6 0 0.6 0 0 0.5 0 0 0 0 Protein g 1.2 0.2 0.6 1.2 0.3 3.7 0.7 8 9.4 0.3 1 2.5 8.2 2.2 2.3 0.8 0.2 3 0.9 1.1 22.7 7 0.5 0 8 8.1 8.4 Vit_A IU 92.3 24 15471 268.6 53.6 0 467.7 5867.4 98.6 73.1 766.3 106.6 3055.2 0 0 133 66 0 101.8 2.9 68 296.5 35.2 152.9 307.4 500.2 499.8 Vit_C IU 10.4 1 5.1 69.7 2.8 15.6 66.1 160.2 0.1 7.9 23.5 5.2 27.9 0 0 74.5 0.8 0 0 0.1 0 0 0.9 0 2.3 2.3 2.4 Calcium mg 6.8 3.4 14.9 52.4 16 22.7 6.7 159 121.8 9.7 6.2 3.3 80.2 10.8 26.2 19.8 3.8 21 6.2 6.7 3.4 202 3.1 1.2 291.3 296.7 302.3 Iron mg 0.4 0.1 0.3 0.1 0.2 4.3 0.3 2.3 6.2 0.2 0.6 0.3 2.3 0.7 0.8 0.3 0.1 1 0.4 0.5 0.5 0.2 0.1 0 0.1 0.1 0.1

Course Code # IDCGRF001-A Accenture 2007 All Rights Reserved Page 1 of 7

Programming Techniques

Case Study 1: Values

Poached Eggs Scrambled Eggs Roasted Chicken Peanut Butter Bologna,Turkey Frankfurter, Beef Ham,Sliced,Extralean Kielbasa,Prk Cap'N Crunch Cheerios Corn Flks, Kellogg'S Raisin Brn, Kellg'S Rice Krispies Special K Oatmeal Malt-O-Meal,Choc Hamburger W/Toppings Taco Couscous Hotdog, Plain Macaroni,Ckd White Rice Sardines in Oil Pizza W/Pepperoni Pork Popcorn,Air-Popped Pretzels Chicknoodl Soup Potato Chips,Bbqflvr Splt Pea&Hamsoup Tortilla Chip Vegetbeef Soup New E Clamchwd,W/Mlk Neweng Clamchwd Beanbacn Soup,W/Watr Tomato Soup Crm Mshrm Soup,W/Mlk

14.00 20.00 79.00 17.00 36.00 48.00 41.00 38.00 20.00 19.00 20.00 23.00 27.00 28.00 18.00 16.00 132.00 32.00 60.00 123.00 60.00 20.00 139.00 132.00 137.00 15.00 30.00 70.00 15.00 100.00 40.00 100.00 78.00 75.00 67.00 30.00 62.00

Lrg Egg 1 Egg 1 lb chicken 2 Tbsp 1 Oz 1 Frankfurter 1 Sl,6-1/4x4x1/16 In 1 Sl,6x3-3/4x1/16 In 1 Oz 1 Oz 1 Oz 1.3 Oz 1 Oz 1 Oz 1C 1C 1 Burger 1 Small Taco 1/2 Cup 1 Hotdog 1/2 Cup 1/2 Cup 2 Sardines 1 Slice 4 Oz 1 Oz 1 Oz 1 C (8 Fl Oz) 1 Oz 1 C (8 Fl Oz) 1 Oz 1 C (8 Fl Oz) 1 C (8 Fl Oz) 1 C (8 Fl Oz) 1 C (8 Fl Oz) 1 C (8 Fl Oz) 1 C (8 Fl Oz)

74.5 99.6 277.4 188.5 56.4 141.8 37.1 80.6 119.6 111 110.5 115.1 112.2 110.8 145.1 607.2 275 369.4 100.8 242.1 98.7 102.7 49.9 181 710.8 108.3 108 150.1 139.2 184.8 142 158.1 163.7 175.7 172 170.7 203.4

211.5 211.2 129.9 0 28.1 27.4 13.3 17.4 0 0 0 0 0 0 0 0 42.8 56.4 0 44.1 0 0 34.1 14.2 105.1 0 0 12.3 0 7.2 0 10 22.3 10 2.5 0 19.8

5 7.3 10.8 16 4.3 12.8 1.4 7.1 2.6 1.8 0.1 0.7 0.2 0.1 2.3 1.5 10.2 20.6 0.1 14.5 0.5 0.2 2.7 7 72.2 1.2 1 4.6 9.2 4 7.4 3.8 6.6 5 5.9 3.8 13.6

140 168 125.6 155.5 248.9 461.7 405.1 279.8 213.3 307.6 290.5 204.4 340.8 265.5 2.3 16.5 563.9 802 4.5 670.3 0.7 0.8 121.2 267 38.4 1.1 486.2 1862.2 212.6 964.8 149.7 1915.1 992 1864.9 951.3 1744.4 1076.3

0.6 1.3 0 6.9 0.3 0.8 0.3 0.6 23 19.6 24.5 27.9 24.8 21.3 25.3 128.2 32.7 26.7 20.9 18 19.8 22.3 0 19.9 0 22.1 22.5 18.7 15 26.8 17.8 20.4 16.6 21.8 22.8 33.2 15

0 0 0 2.1 0 0 0 0 0.5 2 0.7 4 0.4 0.7 4 0 0 0 1.3 0 0.9 0.3 0 0 0 4.3 0.9 1.5 1.2 4.1 1.8 4 1.5 1.5 8.6 1 0.5

6.2 6.7 42.2 7.7 3.9 5.4 5.5 3.4 1.4 4.3 2.3 4 1.9 5.6 6.1 17.3 13.6 20.7 3.4 10.4 3.3 2.1 5.9 10.1 13.8 3.4 2.6 7.9 2.2 11.1 2 11.2 9.5 10.9 7.9 4.1 6.1

316 409.2 77.4 0 0 0 0 0 40.6 1252.2 1252.2 1250.2 1252.2 1252.2 37.4 0 126.3 855 0 0 0 0 53.8 281.9 14.7 55.6 0 1308.7 61.5 4872 55.6 3785.1 163.7 20.1 888 1393 153.8

0 0.1 0 0 0 10.8 7.4 5.5 0 15.1 15.1 0 15.1 15.1 0 0 2.6 2.2 0 0.1 0 0 0 1.6 0 0 0 0 9.6 7 0 4.8 3.5 4.8 1.5 133 2.2

24.5 42.6 21.9 13.1 23.8 9 2 11.4 4.8 48.6 0.9 12.9 4 8.2 18.7 23.1 51.4 220.6 7.2 23.5 4.9 7.9 91.7 64.6 59.9 2.8 10.2 27.1 14.2 33.6 43.7 32.6 186 82.8 81 27.6 178.6

0.7 0.7 1.8 0.6 0.4 0.6 0.2 0.4 7.5 4.5 1.8 16.8 1.8 4.5 1.6 47.2 2.5 2.4 0.3 2.3 1 0.9 0.7 0.9 0.4 0.8 1.2 1.5 0.5 2.1 0.4 2.2 1.5 2.8 2 3.5 0.6

Course Code # IDCGRF001-A Accenture 2007 All Rights Reserved Page 1 of 7

Programming Techniques

Case Study 2

C A S E S T U D Y 2 - PA R T I C I PA N T G U I D E

Course Code IDCGRF001-A Accenture 2009 All Rights Reserved

Page 1 of 4

Programming Techniques

Case Study 2

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 90s 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 Abhyankars are involved in the marketing of denim for over 35 years and involved in the textile trade for more than 50 years. Abhyankars 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.

Course Code IDCGRF001-A Accenture 2009 All Rights Reserved

Page 2 of 4

Programming Techniques

Case Study 2

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 25 610 395 211 Order Width (inches) 50 46 20 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
Course Code IDCGRF001-A Accenture 2009 All Rights Reserved Page 3 of 4

Programming Techniques

Case Study 2

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.

Course Code IDCGRF001-A Accenture 2009 All Rights Reserved

Page 4 of 4

Das könnte Ihnen auch gefallen