Beruflich Dokumente
Kultur Dokumente
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
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
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
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.
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.
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.
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
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
1_Course Overview.ppt
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.
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.
10
1_Course Overview.ppt
11
Level 2 Teammates
Try to resolve the problem with your teammates. Consult entire team, investigate, work together to solve the problem.
Level 4 Faculty
Try to resolve problem with your faculty members.
Copyright 2009 Accenture All Rights Reserved.
12
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(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.
14
1_Course Overview.ppt
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
1_Course Overview.ppt
Questions/ Comments
What questions or comments do you have?
17
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.
Contents
Algorithm Benefits of Algorithm Approaches to Algorithm Efficiency of Algorithm Structure of Algorithm Flowchart Benefits of Flowchart Concept of Testing Unit Testing
10
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
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.
11
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
12
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.
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.
13
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.
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
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
Time Complexity - Is the amount of computer time it needs to run to completion. Suppose the space is fixed for one algorithm then only run time will be considered for obtaining the complexity of the algorithm. Space Complexity - Is the amount of memory it needs to run to completion. The space needed by a program is the sum of space for the code, space for variables, space for constants, space needed by components variables whose size is dependent on the particular problem and the stack space used by recursive procedures.
15
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.
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
16
2.1_FundamentalProgrammingConcepts.ppt
Algorithm concepts
There are three types of algorithm concepts
Sequential
Modules are executed in some sequence/ in a linear fashion
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
11
Output:
17
2.1_FundamentalProgrammingConcepts.ppt
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:
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?
18
2.1_FundamentalProgrammingConcepts.ppt
5.
Output:
Enter number of Students 2 Enter Marks of 3 subjects 30 40 50 Failed Enter Marks of 3 subjects 60 60 70 Passed 15
19
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.
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.
20
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
end
Copyright 2009 Accenture All Rights Reserved.
18
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
19
21
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'
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.
22
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.
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.
23
2.1_FundamentalProgrammingConcepts.ppt
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
24
2.1_FundamentalProgrammingConcepts.ppt
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
25
2.1_FundamentalProgrammingConcepts.ppt
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.
27
26
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
27
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
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
28
2.2_ProgrammingLifeCycle.ppt
WHAT
Requirements Gathering, Problem definition
HOW
Analysis & Design
DO IT
Build
TEST
Testing
USE
5
29
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.
A stub is a dummy module, which imitates the functionality of the real module. For example, say, we have to code a function which receives an employee number as the input and returns the details of that employee after doing a database look up. A stub of this function would be a function with the same name and same number of arguments. But, instead of doing a database lookup, the stub may return the dummy details of an employee after receiving employee number.
30
2.2_ProgrammingLifeCycle.ppt
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.
31
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
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.
11
32
2.2_ProgrammingLifeCycle.ppt
Pseudo code
Linking Linking
Libraries
Executable File
12
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
13
33
2.2_ProgrammingLifeCycle.ppt
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.
14
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
15
34
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
16
Input Documents
Module 1_activities.doc
Exercise 2
20 minutes
Copyright 2009 Accenture All Rights Reserved.
17
35
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.
Contents
Introduction to C programming Basic Constructs of C Keywords Identifiers Literals Declaring and Defining Variables Control Structures Best Practices
36
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
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
37
3.1_IntroductionToC.ppt
Compiler
Object file
Assembly language statements
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
38
3.1_IntroductionToC.ppt
39
3.1_IntroductionToC.ppt
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.
10
40
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
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
12
41
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.
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 \ \ \\
14
42
3.1_IntroductionToC.ppt
15
1.40129846432481707e-45 4.94065645841246544e324
16
43
3.1_IntroductionToC.ppt
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
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
18
44
3.1_IntroductionToC.ppt
Product ;
identifier name
19
MEMORY
age
17
initialization/assignment
age = 17;
Identifier name value
Stack
20
45
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:
21
46
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.
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');
47
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, );
23
The arguments list must be the addresses of the variables being read or pointers to those variables.
48
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
24
Unformatted functions - since these functions dont give us the liberty to use format specifiers they are called unformatted function
49
3.1_IntroductionToC.ppt
Operators
Unary operators Arithmetic operators Relational operators Conditional operator Logical operator Assignment operators Evaluation order
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
--
Increment & decrement operators can only be applied to variables. Expression (i+j)++ is illegal.
Copyright 2009 Accenture All Rights Reserved.
26
50
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.
/ %
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
28
51
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
52
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
32
53
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
Flow controls
if-else() statement switch() statement while() statement do-while() statement for() statement break statement continue statement
34
54
3.1_IntroductionToC.ppt
2.
Selection
3. Iteration
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
55
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
38
56
3.1_IntroductionToC.ppt
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:
/* }
statements
Output:
Example:
Timer: Timer: Timer: Timer: Timer: Timer: Timer: Timer: Timer: Timer:
10 9 8 7 6 5 4 3 2 1
40
57
3.1_IntroductionToC.ppt
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
58
3.1_IntroductionToC.ppt
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
59
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);
46
60
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); }
Use of break with while loop: #include<stdio.h> main() { int cnt; cnt=0; while (cnt<=10) { printf(Use of Break statement); cnt++; if (cnt==5) break; printf( Still using Break statement); } printf (End of program ); }
61
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
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.
49
62
3.1_IntroductionToC.ppt
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
63
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.
Contents
Introduction to Functions Function definition Accessing functions Declaring Function Function communication Formal and actual arguments Scope of variables Parameter passing Recursive functions
64
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
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.
65
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
Pick a notation style, and use it consistently so that others can read and understand your coding
Copyright 2009 Accenture All Rights Reserved.
66
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.
67
3.2_Functions.ppt
Function name
int Cube (int Number) { int Cbe; Cbe = Number*Number*Number; return (Cbe); }
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
10
68
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.
11
Data type specifier indicates the type of data returned by the function Example :
12
69
3.2_Functions.ppt
To call A Function
Function Call :
result=function_name(Argument1, ,ArgumentN);
Example :
ValidDate=Validate_Date(Day, Month,Year);
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.
14
70
3.2_Functions.ppt
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
16
71
3.2_Functions.ppt
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
18
72
3.2_Functions.ppt
Disadvantages
Information cannot be transferred back to the calling portion of the program via arguments.
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
20
73
3.2_Functions.ppt
21
22
74
3.2_Functions.ppt
Use of functions
Advantages
Writing modular programs Reusability Easy testing & debugging Easy program modification
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
75
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?
26
76
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
IDCGRF001-A
Copyright 2009 Accenture All Rights Reserved.
77
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
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
IDCGRF001-A
Copyright 2009 Accenture All Rights Reserved.
78
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.
IDCGRF001-A
Copyright 2009 Accenture All Rights Reserved.
79
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
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
4.1_IntroductionToArrays.ppt
n element array a:
a[0], a[1], a[2] a[n-1]
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
4.1_IntroductionToArrays.ppt
Creating an Array
There are three steps to creating an array: #include <stdio.h>
1. Declaration 2. Construction 3. Initialization
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
IDCGRF001-A
Copyright 2009 Accenture All Rights Reserved.
82
4.1_IntroductionToArrays.ppt
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
4.1_IntroductionToArrays.ppt
Output:
printf(enter elements of the array); for(i=0; i<SIZE; i++) scanf(%d,&num[i]);
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 };
12
IDCGRF001-A
Copyright 2009 Accenture All Rights Reserved.
84
4.1_IntroductionToArrays.ppt
Output to screen
Example:
printf(%s,charstr1);
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.
14
IDCGRF001-A
Copyright 2009 Accenture All Rights Reserved.
85
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()
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); }
16
IDCGRF001-A
Copyright 2009 Accenture All Rights Reserved.
86
4.1_IntroductionToArrays.ppt
strlen(string) strcat(str1,str2)
strcmp(str1,str2)
strcpy(str1,str2)
Returns str1
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
4.1_IntroductionToArrays.ppt
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
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 ]
19
IDCGRF001-A
Copyright 2009 Accenture All Rights Reserved.
88
4.1_IntroductionToArrays.ppt
20
IDCGRF001-A
Copyright 2009 Accenture All Rights Reserved.
89
4.1_IntroductionToArrays.ppt
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
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
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.
92
4.2_Pointers.ppt
Contents
Introduction to Pointers Pointer Declaration Pointer Operators Arrays and Pointers Pointer Manipulations
93
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
94
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
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
95
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
C uses pointers in three different ways: C uses pointers to create dynamic data structures -- data structures built up from blocks of memory allocated from the heap at run-time. C uses pointers to handle variable parameters passed to functions. Pointers in C provide an alternative way to access information stored in arrays. Pointer techniques are especially valuable when you work with strings. There is an intimate link between arrays and pointers in C. In some cases, programmers also use pointers because they make the code slightly more efficient.
96
4.2_Pointers.ppt
countPtr
Indirection (*)
Referencing the value in memory a pointer points to
Notes: Pointers point to memory addresses, regardless of what value is stored there. To access the value at the address to which they are pointing, programmers utilize the indirection operator (*). Explain with a sample code how to declare the pointer variable and how to access value stored in.
97
4.2_Pointers.ppt
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.
98
4.2_Pointers.ppt
Notes: Always initialize a pointer to an address, to 0 or to null. A pointer initialized to nothing is very dangerous in a program. A pointer initialized to a null or 0 at least points to a specific memory location, or a specific entity allocated as blank. Note: An uninitialized pointer will not be guaranteed to be null. It will have Garbage. This scenario will lead to the Dangling Pointer. That's why all pointers MUST be initialized to 0 or NULL, else they will become WILD.
99
4.2_Pointers.ppt
yPtr
y 5 500000
y 5
Notes: The & operator returns the address of the location where the information is stored in memory, and does not return the value stored there.
100
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)
The Dereference pointer (the operand of *) must be an lvalue (not a constant) * and & are inverses they cancel each other out:
*&myVar == myVar and &*yPtr == yPtr
Note: * returns a value, or can be used to change a value stored in memory & returns a memory address
101
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.
Data Table Name i j ptr Type int int int * Description integer variable integer variable integer pointer variable Value 5 10
102
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
103
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
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
104
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
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
105
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
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)
106
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
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
107
4.2_Pointers.ppt
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
108
4.2_Pointers.ppt
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
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
109
4.2_Pointers.ppt
Example for pointer arithmetic. int main() { int j = 10; double k = 3.14; int *intPtr = &j ; double *doublePtr = &k ; printf( Int Value and Int memory location are %d, %d \n, j, intPtr); printf( Double Value and Double memory location are %d %d \n ,k, doublePtr ); ++intPtr; ++doublePtr; //Value of j remains the same but memory to which intPtr is pointing is changed. printf( Int Value and Int memory location are %d, %d \n, j, intPtr); //Value of k remains the same but memory to which doublePtr is pointing is changed. printf( Double Value and Double memory location are %d %d \n ,k, doublePtr ); } Why pointer arithmetic is meaningless unless performed on pointer to an array ? - When we declare int a = 10; int *aPtr = &a; - Now when we do ++aPtr; there is no valid memory allocated to this new location. And we will be pointing to a JUNK. - But when we have int array[5]; int *arrayPtr = &a[0]; - Now when we do ++arrayPtr; this pointer will now point to &a[1]. So, there is meaning to pointer arithmetic only when we are using it with arrays.
110
4.2_Pointers.ppt
Subtracting pointers
Returns number of elements between two addresses
vPtr2 = v[ 2 ]; vPtr = v[ 0 ]; vPtr2 - vPtr is 2
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 ? ? ? ?
111
4.2_Pointers.ppt
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
112
4.2_Pointers.ppt
113
4.2_Pointers.ppt
114
4.2_Pointers.ppt
115
4.2_Pointers.ppt
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.
116
4.2_Pointers.ppt
i=3
i=5
The program segment on the left is demonstrating pass by value, i.e. the value, actually a copy, of the variable i is passed as argument to function f(). The other program shows you pass by reference. The address of the variable i is passed to f() instead, thus allowing us to modify the content stored in the variable.
117
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
118
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
119
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
120
4.3_MemoryManagement.ppt
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. */ }
121
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.
122
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.
123
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
124
4.3_MemoryManagement.ppt
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 */
125
4.3_MemoryManagement.ppt
11
12
126
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*/
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.
127
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!
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.
128
4.3_MemoryManagement.ppt
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
129
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
130
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
131
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.
132
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
133
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
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.
134
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
Union allows the same portion of memory to be shared by different data types, since they share the same memory location. Its declaration is similar to structures, but the functionality is different. Unions allocate only enough memory to accommodate the largest data member. Unions are mainly used when only one data member needs to be chosen to store a value or access the value which is already stored. A union is most useful when it is combined together with structures since it allows one piece of data to be accessed at a time. Example: In real world if a person wants to have a new banking account they have to provide all the personal details with either the company ID or the social security number. All the compulsory fields are part of a structure. Company id and social security number can be stored in a union and accessed.
135
4.4_IntroductionToStructures.ppt
136
4.4_IntroductionToStructures.ppt
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.
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.
137
4.4_IntroductionToStructures.ppt
Unions
uses union keyword to define a union Allocates memory only to the largest element of the union
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.
138
4.4_IntroductionToStructures.ppt
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
12
139
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
140
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
141
4.5_CodingConventions.ppt
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
4.5_CodingConventions.ppt
For example:
int foo, fooarray[]; /* WRONG! */
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
4.5_CodingConventions.ppt
144
4.5_CodingConventions.ppt
145
4.5_CodingConventions.ppt
10
11
146
4.5_CodingConventions.ppt
Variable Assignments
Avoid assigning several variables to the same value in a single statement. It is hard to read.
Example:
choice = empcode = 'c'; /* AVOID*/
12
147
4.5_CodingConventions.ppt
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
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
4.5_CodingConventions.ppt
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
4.5_CodingConventions.ppt
Good Practice
15
150
4.5_CodingConventions.ppt
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
4.5_CodingConventions.ppt
17
152
4.5_CodingConventions.ppt
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
4.5_CodingConventions.ppt
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
4.5_CodingConventions.ppt
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
4.5_CodingConventions.ppt
21
Check if the duplication of code can be avoided with some other technique.
156
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; }
22
157
4.5_CodingConventions.ppt
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
4.5_CodingConventions.ppt
It should be long enough to be descriptive For a function name, use a description of the return value:
NextCutomerId(), CurrentPenColor(),.
FormatAndPrintOutput()
Copyright 2009 Accenture All Rights Reserved.
24
What is most important is that the naming convention should be consistent across the application.
159
4.5_CodingConventions.ppt
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
4.5_CodingConventions.ppt
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
4.5_CodingConventions.ppt
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
4.5_CodingConventions.ppt
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
4.5_CodingConventions.ppt
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
4.5_CodingConventions.ppt
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
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.
31
166
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
167
5_SearchingAndSorting.ppt
Objectives
At the end of this section, you should be able to:
Different Types of search methods
Linear search Binary search
Analysis of algorithms
Search Concept
Searching is Locating a particular data item in a list of data elements is known as searching. Search takes a problem as input and returns a solution to the problem It is the process of locating data like a word, a file etc There are different Types of search- Few of them are
Linear Search Binary Search
168
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.
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)
169
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
Binary search is a technique for quickly locating an item in a sequential list. The desired key is compared to the data in the middle of the list. The half that contains the data is then compared in the middle, and so on, either until the key is located or a small enough group is isolated to be sequentially searched.
170
5_SearchingAndSorting.ppt
Input Documents
Module 4_activities.doc
20 minutes
Copyright 2009 Accenture All Rights Reserved.
171
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
10
172
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
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.
173
5_SearchingAndSorting.ppt
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.
12
174
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.
14
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.
15
175
5_SearchingAndSorting.ppt
Input Documents
Module 4_activities.doc
20 minutes
Copyright 2009 Accenture All Rights Reserved.
17
176
5_SearchingAndSorting.ppt
Analysis of algorithms
Space Complexity
Indicates how much extra memory the algorithm needs
Time Complexity
Indicates how fast the algorithm runs
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
19
177
Programming Techniques
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.)
Module1_activities.doc
1
Programming Techniques
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.
Module1_activities.doc
2
Programming Techniques
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
Module2_activities.doc
3
Programming Techniques
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.
Module2_activities.doc
4
Programming Techniques
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
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
F D C B A
Table 4. 2
Last digit
Modifier
<blank> +
Activity 4.6 Using recursive function Write a c program to find the Fibonacci series of N numbers
Module2_activities.doc
6
Programming Techniques
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.
Module2_activities.doc
7
Programming Techniques
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
Activity 5.9 Write a function that scans the English text stored in an array and determines the number of words in it.
Module3_activities.doc
9
Programming Techniques
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
Module3_activities.doc
10
Programming Techniques
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
Module3_activities.doc
11
Programming Techniques
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.
Module3_activities.doc
12
Programming Techniques
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.
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
Page 1 of 5
Programming Techniques
Case Study 1
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.
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.
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
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)
Page 5 of 5
Programming Techniques
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
Programming Techniques
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
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
Page 1 of 4
Programming Techniques
Case Study 2
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.
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.
Page 4 of 4