This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
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.
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.
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
Teaching Method• This is not a lecture course! • Lessons serve only as guideposts and reminders, and are not
expected to be complete classes on these topics• Instructors serve mainly as facilitators and knowledge coaches
Performance Evaluation• Each participant will be evaluated
Participate• Don’t just listen to discussions, interact!• If in doubt, ask questions to clarify.• Spot problems and suggest alternatives or workarounds.
• Algorithm• Benefits of Algorithm• Approaches to Algorithm• Efficiency of Algorithm• Structure of Algorithm • Flowchart• Benefits of Flowchart• Concept of Testing• Unit Testing
Contents
10
Programming Techniques Module 2: Fundamental Programming Concepts
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
• There are different approaches of algorithm in analyzing a problem.
– Empirical (a posteriori) approach• It is a method consisting of programming the competing techniques
and trying them on different instances.
– Theoretical (a priori) approach • It determines mathematically the quantity of resources needed by
each algorithm as a function of the size of the instances.
– Hybrid approach • Combination of Empirical and theoretical approach.
Analyzing An Algorithm(1 of 2)
There are two basic approaches:The empirical (posteriori) approach:The empirical approach to choosing an algorithm consists of programming the competing techniques and trying them on different instances with the help of a computer. The theoretical (priori) approach: The theoretical approach consists of determining mathematically the quantity of resources needed by each algorithm as a function of the size of the instances. The resources of most interest are computing time and storage space, with the former usually being the more critical. We compare the algorithms on the basis of their execution times, an algorithm’s storage requirements. The size of an instance corresponds formally to the number of bits needed to represent the instance on a computer, using some precisely defined and reasonably compact coding scheme. (The word “size” to mean any integer that in some way measures the number of components in an instance.) E.g. when we talk about sorting, we usually measure the size of an instance by the number of items to be sorted, ignoring the fact that each of these items may take more than once bit to represent on a computer. Similarly, when we talk about graphs, we usually measure the size of an instance by the number of nodes or edges (or both) involved.
13
Programming Techniques Module 2: Fundamental Programming Concepts
• There are different approaches of algorithm in analyzing a problem.
– Empirical (a posteriori) approach• It is a method consisting of programming the competing techniques
and trying them on different instances.
– Theoretical (a priori) approach • It determines mathematically the quantity of resources needed by
each algorithm as a function of the size of the instances.
– Hybrid approach • Combination of Empirical and theoretical approach.
Analyzing An Algorithm(2 of 2)
Content ContinuedThe advantage of the theoretical approach is that it depends on neither the computer being used, nor the programming language, nor even the skill of the programmer. It saves both the time that would have been spent needlessly programming an inefficient algorithm and the machine that would have been wasted testing it. More significantly it allows us to study the efficiency of an algorithm when used on instances of any size. This is often not the case with the empirical approach, where practical consideration my force us to test our algorithms only on a small number of arbitrarily chosen instances of moderate size. Since it is often the case that newly discovered algorithm begins to perform better than its predecessor only when they are both used on large instances, this last point is particularly importantOne can also think of a hybrid approach while analyzing the algorithms, where the form of the function describing the algorithm’s efficiency is determined theoretically, and then any required numerical parameters are determined empirically for a particular program and machine, usually by some kind of regression. Using this approach we can predict the time an actual implementation will take to solve an instance much larger than those used in the tests. Beware however of making such an extrapolation solely on the basis of a small number of empirical test, ignoring all theoretical considerations. Predictions made without theoretical support are likely to be very imprecise, if not plain wrong.
14
Programming Techniques Module 2: Fundamental Programming Concepts
• Complexities are the parameters to capture the challenges or complications
• Few of the algorithm complexities are captured based on:– Time Complexity
• Is the amount of computer time it needs to run to completion
– Space Complexity• Is the amount of memory it needs to run to completion
Algorithm Complexities
Time Complexity - Is the amount of computer time it needs to run to completion. Suppose the space is fixed for one algorithm then only run time will be considered for obtaining the complexity of the algorithm.
Space Complexity - Is the amount of memory it needs to run to completion. The space needed by a program is the sum of space for the code, space for variables, space for constants, space needed by components variables whose size is dependent on the particular problem and the stack space used by recursive procedures.
15
Programming Techniques Module 2: Fundamental Programming Concepts
Example of an algorithm to read marks of three subjects. Find the average scored by the student, and print pass if the score is more than 50
1. Begin
2. Print “Enter Marks of 3 subjects”
3. Input Marks1, Marks2, Marks3
4. Avg = (marks1+marks2+marks3)/3
5. If (Avg >= 50) Then Print “Passed”
6. End
Enter Marks of 3 subjects
60
70
80
Passed
Output:Implementation of single Alternative algorithm
Single Alternative Algorithm – Example 3
1. The example calculates the Total2. Finds the average of it3. Verifies if the Average score is more than 50, if it is More than 50 Prints resultsThink about the following question:What will be the out come if the marks is less than 50?
18
Programming Techniques Module 2: Fundamental Programming Concepts
Example of an algorithm to read marks of three subjects. Find the average scored by the student, and print “Pass” if the score is more than 50 otherwise print “Fail”
Example of an algorithm to read marks of three subjects. Find the average scored by the student, and print “Pass” if the score is more than 50 otherwise print “Fail” for N number of Students
Algorithm Iteration – Example 5
19
Programming Techniques Module 2: Fundamental Programming Concepts
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”.
• Testing is a process used to help identify the correctness, completeness and quality of developed computer software.
• Testing is the process of running a system with the intention of finding errors
• It enhances the integrity of a system by detecting deviations in design and errors in the system.
• It aims at detecting error-prone areas, which helps in the prevention of errors in a system.
• Testing also adds value to the product by conforming to the user requirements.
• It is Oriented to 'detection'
Testing
Content:The purpose of testing is to discover errors. Testing is the process of trying to discover every conceivable fault or weakness in a work product. Software testing is a process used to identify the correctness, completeness and quality of developed computer software. Actually, testing can never establish the correctness of computer software, as this can only be done by formal verification (and only when there is no mistake in the formal verification process). It can only find defects, not prove that there are none.
22
Programming Techniques Module 2: Fundamental Programming Concepts
• A unit test is a method of testing the correctness of a particular module of source code.
• Unit testing is also known as Component/ Module/ Program Testing.
• It is the most 'micro' scale of testing.
• The goal of unit testing is to isolate each part of the program and show that the individual parts are correct
• Most thorough look at detail.
Unit Testing
Content:In computer programming, a unit test is a procedure used to verify that a particular module of source code is working properly. The idea about unit tests is to write test cases for all functions and methods so that whenever a change causes a regression, it can be quickly identified and fixed. Ideally, each test case is separate from the others; constructs such as mock objects can assist in separating unit tests. This type of testing is mostly done by the developers and not by end-users.
The goal of unit testing is to isolate each part of the program and show that the individual parts are correct. Unit testing provides a strict, written contract that the piece of code must satisfy. As a result, it affords several benefits.Unit testing is done by the programmer as it requires detailed knowledge of the internal program design and code.
23
Programming Techniques Module 2: Fundamental Programming Concepts
Entry criteria:• After completion of each class/method, unit testing should
be done.
Exit criteria: • Functionality is achieved• All requirements tested & verifiedResult:• No Incorrect data, or data recorded in the wrong field,
account or database • No side-effects or bugs remain vis-à-vis functionality • No errors in calculations, formulas or rounding• No data corruption errors
• Test case is a set of test inputs, execution conditions, and expected results developed for a particular objective, such as to exercise a particular program path or to verify compliance with a specific requirement
• Test cases are written for each unit in the main program
• A program will execute all the test cases and record the results in a document called test file.
• Test cases will have Description, inputs, expected outcomes
Test Cases
24
Programming Techniques Module 2: Fundamental Programming Concepts
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
• A program is an algorithm expressed in a programming language
• Programming is an act of creating software or some other set of instructions for a computer
• Computer programming is the craft of implementing one or more interrelated algorithms using a particular programming language to produce a concrete computer program
Programming
28
Programming Techniques Module 2.2: Programming Life Cycle
• Based on the fact that large problem become more manageable if they are divided into a number of smaller and simpler tasks which can be tackled separately.
• Top – down design approach is performed in a special way. • The main program is written first. It is tested before sub-
programs are written. • To do this, actual sub programs are replaced with stubs.
Top-Down Design
A stub is a dummy module, which imitates the functionality of the real module.
For example, say, we have to code a function which receives an employee number as the input and returns the details of that employee after doing a database look up. A stub of this function would be a function with the same name and same number of arguments. But, instead of doing a database lookup, the stub may return the dummy details of an employee after receiving employee number.
30
Programming Techniques Module 2.2: Programming Life Cycle
• The stubs tests to see if the data is passed correctly. After the main program is written and checked, each module is written and tested in turn.
• If the modules run properly, then it is tested with the main program. If the module and the main run properly then the next module is written and checked and so on..
• Write the most basic subroutines in the hierarchy first and then use them to make more sophisticated subroutines
• The pure bottom-up approach is generally not recommended because it is difficult to anticipate which low subroutines will be needed for any particular program
• In this approach it is usually assumed that the basic routines created will be generic enough to be used more than once
• This approach is designed to generate reusable code
• This is more like a basic instruction in the programming language than a large scale program component.
Bottom-Up Design
31
Programming Techniques Module 2.2: Programming Life Cycle
• Introduction to C programming• Basic Constructs of C• Keywords• Identifiers• Literals• Declaring and Defining Variables• Control Structures• Best Practices
Contents
36
Programming TechniquesModule 3.1: Introduction to C
• C is Structured Programming Language• The C programming language is a standardized
programming language developed by Ken Thompson and Dennis Ritchie
• It was developed in early 1970s • It is one of the most widely used programming languages • It is praised for its efficiency, and is the most popular
programming language for writing system software
C Programming
37
Programming TechniquesModule 3.1: Introduction to C
/****************************************************** hello.c -- program to print out "Hello World". ** Not an especially earth-shattering program. ** ** Author: @AuthorName ** ** Date : 06-03-06 ** ** Purpose: Demonstration of a simple program. ** ** Usage: ** Runs the program and the message appears. *
/* Say Hello to world */printf("Hello World\n");return (0);
}
The sentence beginning with # is a preprocessor directive.Here stdio.h is known as a header file. It includes standard input and output header file in to the program
Preprocessors
The main() function is the point from where the C program begins execution. Any C program to be executed should have a main() function.
main ()
C programs consist of functionsA function should always be followed by a pair of parentheses ()
Functions
C Source File Structure
38
Programming TechniquesModule 3.1: Introduction to C
/****************************************************** hello.c -- program to print out "Hello World". ** Not an especially earth-shattering program. ** ** Author: @AuthorName ** ** Date : 06-03-06 ** ** Purpose: Demonstration of a simple program. ** ** Usage: ** Runs the program and the message appears. *
/* Say Hello to world */printf("Hello World\n");return (0);
}
Braces are used for grouping statements or blocks of code.The left brace ( { ) indicates the beginning of a function or a class, which contains the variables and methods needed. The left brace also indicates the beginning of a method body.For every left brace that opens a class or method you need a corresponding right brace ( } ) to close the class or method.A right brace always closes its nearest left brace
/****************************************************** hello.c -- program to print out "Hello World". ** Not an especially earth-shattering program. ** ** Author: @AuthorName ** ** Date : 06-03-06 ** ** Purpose: Demonstration of a simple program. ** ** Usage: ** Runs the program and the message appears. *
/* Say Hello to world */printf("Hello World\n");return (0);
}
printf() is the standard output function of the C program ( the display screen).printf is included in the stdio.h header file.
printf()
return instructs the function to end and return the code that follows the instruction. In this case return (0); return will end main() and will return 0 to the system console, which is an integer value.
return (0)
C Source File Structure (Cont.)
39
Programming TechniquesModule 3.1: Introduction to C
• if-else performs statements based on two conditions• Condition should result to a boolean expression• If condition is true, the statements following if are
executed• If condition is false, the statements following else are
executed• Can be nested to allow more conditions
Syntax: if (condition) { /* braces
optional*/
/* statement required*/
}
else { /* else clause is optional*/
/* statement required */
}
Example:int age=10;
if (age < 10) {printf("You're just a kid.");
} else if (age < 20){pritnf("You're a teenager.");
} else {pritnf("You're probably
old...");}
if-else
55
Programming TechniquesModule 3.1: Introduction to C
• Loop is an informal term that refers to any kind of iterative control structure –any structure that causes a program to repeatedly execute a block of code based on specific condition.
• Types of loops– while– do…while– for
Loops
56
Programming TechniquesModule 3.1: Introduction to C
• for() performs statements repeatedly based on a condition
• Init is a list of either declarations or expressions, evaluated first and only once
• Condition is evaluated before each iteration• Exp is a list of expressions, evaluated after each iteration• All entries inside () are optional, for(;;) is an infinite
loop
Syntax: for (init; condition; exp) { /* braces optional*/
/* statements here*/
}
for()
59
Programming TechniquesModule 3.1: Introduction to C
• The main() method is the start of execution of a C program
• Identifiers are case-sensitive• C keywords cannot be used as identifiers• Use unary, arithmetic operators for basic mathematical
operations• Use assignment operators to assign values to variables• if() and switch() are used for branching statements• Pay attention to the order of if’s and else's, especially if
they process a lot of errors. Make sure the nominal case is clear.
• Order if-then-else chains and cases in case statements for maximum readability.
Key points
62
Programming TechniquesModule 3.1: Introduction to C
• Use the default clause in a case statement or the last else in a chain of if-else if- else to trap errors
• All control constructs are not created equal. Choose the control construct that’s most appropriate for each sections of code.
• while(), do-while() and for() are used for iterating statements
• Techniques for keeping loops simple include avoiding exotic kinds of loops, minimizing nesting, making entries and exits clear, and keeping housekeeping code in one place.
• Think the loop through carefully to verify that it operates normally under each case and terminates under all possible conditions.
• Introduction to Functions• Function definition• Accessing functions• Declaring Function• Function communication• Formal and actual arguments• Scope of variables• Parameter passing• Recursive functions
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
• A C program is a collection of one (or) more functions, with a special function main() from where the Execution starts.
• Functions are the building blocks of a C program• Functions consist of sets of statements• Several functions can be grouped together as a single unit
to form a function• Functions break large computing task into smaller ones.• Function is a unit of program code, as per some syntax, to
perform specific and well defined task • Benefits of Functions
– Functions break large computing task into smaller ones, and enable people to build on what others have done instead of starting over from scratch.
Return_type name ( data type parameter1, data type parameter2, .....)
{ // statements
}
A return type specifier specifies the type of data returned by the function
• A statement is the function's body
• Braces { } surround the block of a statement
Each input parameter consists of a data type specifier followed by an identifier/nameInput Parameters:• Are declared like a regular variable• Are separated by commas( , )• Can be used only within a function• Allow Parameter to pass to the function
when the function is called• Are optional• Are also called arguments
• 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
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
• To refer to a particular element, specify: – The array name – The position number
• It is known as Index or Subscript
Arrays Mechanism
a[6]
a[11]
a[10]
a[9]
a[8]
a[7]
Position number of the element within array a
a[0]
a[1]
a[2]
a[3]
a[5]
a[4]
Name of array (Note that all elements of this array have the same name: a )
24
-5
An array is a collection of variables of the same type that are referred to through a common name. A specific element in an array is accessed by an index or subscript.All array elements are stored at contiguous memory location.
80
Programming Techniques Module 4.1: Introduction to Arrays
Passing Arrays To Functions• An array can be passed to a function as an argument.• While declaring a one dimensional array as a formal
argument, the array name is written with empty square brackets, the size of the array is not specified.– Example:
• void add ( int a[ ] ) {/* function definition */
}
Contents:When declaring function prototypes, if argument names are not included in function declaration, then an empty square brackets must be specified after argument data type.Example:
void add ( int [] );
83
Programming Techniques Module 4.1: Introduction to Arrays
Returns 0 if equal, otherwise numeric difference between first non-matching char.
strcmp(str1,str2)
DescriptionString Library Function
The library functions processes strings as complete entities, thus strings can be concatenated, compared and copied.
1. strlen(string) - returns length of the string an integer value.2. strcat(str1,str2) – appends str2 to str1 and returns str13. strcmp(str1,str2) – compares the two strings and if both strings are same
the returns 0 otherwise the numeric difference between the ASCII values of the first non-matching characters
4. strcpy(str1,str2) – copies str2 to str1 and returns str1
87
Programming Techniques Module 4.1: Introduction to Arrays
char source1[]=”programming”; /*initialize two strings*/char source2[]=”techniques”;char target1[20],target2[20];int len1,diff1,diff2;len1=strlen(source1); /* use of strlen function*/strcpy(target1,source1); /*use of string copy function*/strcat(source1,source2); /* use strcat function to concatenate strings*/diff2=strcmp(source2,”techniques”);/* use string compare function to compare two strings*/
printf(”the length of source1 =%d”,len1);/*prints the length*/printf(“the target string is = %s”,target1); printf(“the concatenated string is =%s”,source1); /*prints the concatenated string*/printf(“output of comparing the strings is = %d %d”,diff2);
} The length of the source1=11The Target string is=programmingThe concatenated string is=programming techniquesOutput of comparing strings is=0
• Useful when replicating matrix-like data storage– They make data access easier for any data that can be
represented in a matrix format
• Useful when we want to store entire sentences as a character string– We can declare char [][]or char* []
Advantages of Multidimensional Array
Applications of Two multidimensional array:-A matrix can be represented in a two-dimensional Array.-In a Chess-Board each square on a board can be represented in a 2D matrix.-An entire statement can be stored in a two-dimensional character array.
90
Programming Techniques Module 4.1: Introduction to Arrays
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
• A pointer is a variable which holds the address of an other variable of the same type. Pointer can also be defined as a programming language data type whose value refers directly to ("points to") another value stored elsewhere in the computer memory using its address
• A Pointer is a data element whose value is an address • Pointers are
– Powerful, but can be difficult to master– Simulate call-by-reference– Has close relationship with arrays and strings
Pointer is a variable containing the address of a byte in memory.
Pointers are play a key role in C, so if you want to use the C language fully you have to have a very good understanding of pointers. They have to become comfortable for you. The goal of this section and the next several that follow is to help you build a complete understanding of pointers and how C uses them.
A pointer is a programming language data type whose value refers directly to ("points to") another value stored elsewhere in the computer memory using its address
A Pointer is a data element whose value is an address.
Pointers :are Powerful, but can be difficult to masterCan Simulate call-by-reference Has close relationship with arrays and strings
• Why Pointers ?– At times, they are the only way to express a computation, and
partly because they usually lead to more compact and efficient code than can be obtained in other ways. If implemented with discipline, pointers can also be used to achieve clarity and simplicity
• Why not pointers?– Harder than average to understand– Error prone– Tend to be machine dependent– Not portable code
Pointers
C uses pointers in three different ways:
C uses pointers to create dynamic data structures -- data structures built up from blocks of memory allocated from the heap at run-time. C uses pointers to handle variable parameters passed to functions. Pointers in C provide an alternative way to access information stored in arrays.Pointer techniques are especially valuable when you work with strings. There is an intimate link between arrays and pointers in C. In some cases, programmers also use pointers because they make the code slightly more efficient.
– Contain memory addresses as their values – Normal variables contain a specific value
(direct reference)– Pointers contain the memory address
of a variable that has a specific value (indirect reference)
• Indirection (*)– Referencing the value in memory a pointer
points to
count
7
7
countPtr
Notes:Pointers point to memory addresses, regardless of what value is stored there.
To access the value at the address to which they are pointing, programmers utilize the indirection operator (*).Explain with a sample code how to declare the pointer variable and how to access value stored in.
– Declares a pointer to an int; a pointer of type int *
– Each declared pointer requires its own asterisk– int *Ptr1, *Ptr2;
Notes:A common programmer convention that pointers are named with an initial p. Following this convention the pointer to the variable named myAge would be named pmyAge, and the pointer to variable named bigStorage would be pbigStorage.
When declaring variables, one can list the type (i.e., int) and then list variable names, and all of the listed variables will be of the type int. However, when declaring pointers, each listed pointer needs to have it’s own * preceding it’s name.
Pointer Variable Declaration (continued)• Can declare pointers to any data type• Pointer initialization
– Always initialize pointers to 0, NULL, or an address• 0 or NULL points to a “specific nothing”• Un-initialized pointers are called “wild pointers” and
are very dangerous in a program– They can cause serious errors!
Notes:Always initialize a pointer to an address, to 0 or to null. A pointer initialized to nothing is very dangerous in a program. A pointer initialized to a null or 0 at least points to a specific memory location, or a specific entity allocated as blank.
Note: An uninitialized pointer will not be guaranteed to be null. It will have Garbage. This scenario will lead to the Dangling Pointer. That's why all pointers MUST be initialized to 0 or NULL, else they will become WILD.
• Arrays can contain pointers– Commonly used to store an array of strings
• char *suit[4] = {"Hearts", "Diamonds", "Clubs", "Spades" };– Each element of a suit is a pointer to a char * (a string)– The strings are not in the array; only pointers to the strings
– Increment/decrement pointer (++ or --)– Add/subtract an integer to/from a pointer (+ or +=, - or -=)– Pointers may be subtracted from each other– Pointer arithmetic is meaningless unless performed on a
pointer to an array
Example for pointer arithmetic.
int main(){
int j = 10;double k = 3.14;int *intPtr = &j ;double *doublePtr = &k ;
printf( “Int Value and Int memory location are %d, %d \n“, j, intPtr);printf( “Double Value and Double memory location are %d %d \n“ ,k, doublePtr );
++intPtr; ++doublePtr;
//Value of j remains the same but memory to which intPtr is pointing is changed.printf( “Int Value and Int memory location are %d, %d \n“, j, intPtr);//Value of k remains the same but memory to which doublePtr is pointing is changed.printf( “Double Value and Double memory location are %d %d \n“ ,k, doublePtr );
}
Why pointer arithmetic is meaningless unless performed on pointer to an array ?- When we declare int a = 10; int *aPtr = &a;- Now when we do ++aPtr; – there is no valid memory allocated to this new location. And we will be
pointing to a JUNK.
- But when we have int array[5]; int *arrayPtr = &a[0];- Now when we do ++arrayPtr; this pointer will now point to &a[1]. So, there is meaning to pointer
• Modify behavior in argument passing• Pass By reference method
Pointers and functions
void f(int j)
{
j = 5;
}
void g()
{
int i = 3;
f(i);
}
void f(int *ptr)
{
*ptr = 5;
}
void g()
{
int i = 3;
f(&i);
}
i = 3 i = 5
The program segment on the left is demonstrating “pass by value”, i.e. the value, actually a copy, of the variable i is passed as argument to function f(). The other program shows you “pass by reference”. The address of the variable i is passed to f() instead, thus allowing us to modify the content stored in the variable.
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
Memory and Memory Management• C supports the following types of memory:
– Automatic Storage– Static Storage– Free Store (Dynamic Storage)
• The storage defers in terms of variable initialization and lifetime
Examples:
1. Automatic Storage.void myFunction(){
auto int x = 5; // x is the automatic variable.int y = 10; // y is also an automatic variable by definition./*The scope of x and y is confined to the myFunction() block. They are created when program enters the
function and destroyed when program leaves this function. So, their storage is temporary.*/
}2. Static Storage.
void myFunction(){
static int s = 5; // s is a static variable./*The scope of the s is confined to this function, but the life time is the entire life of the program. ie when
program starts running the first starts running, ALL static variable will be assigned the memory. It’s different from the auto variable when the memory is created only when program enters the function. The memory will be only be freed when program terminates.
*/}
3. Dynamic Storage.void myFunction(){
int *ptr = malloc(sizeof( int));/*The dynamic memory is the most confusing and the most difficult to master. This memory will be
created WHENEVER the program enters the for-loop, but it will not be destroyed in this case. This memory is accessible outside this function also, if we can return the ptr.
Dynamic Memory Allocation• The malloc function is the basic function used to allocate
memory on the heap in C. Its prototype isvoid *malloc(size_t size) which allocates size bytes of memory. If the allocation succeeds, a pointer to the block of memory is returned. malloc returns a void pointer (void *), which indicates that it is a pointer to a region of unknown data type. This pointer is typically cast to a more specific pointer type by the programmer before being used.
• Allocates single block of memory.• Default value is some garbage value.
The standard method of creating an array of ten integers on the stack:int array[10];
But if we want to allocate the array dynamically we should write:#include <stdlib.h> int *ptr = malloc(sizeof(int) * 10); /* Allocates space for an array
with 10 elements of type int */if (ptr == NULL){exit(1); /* We couldn't allocate any memory, so exit */}/* allocation succeeded */
Dynamic Memory Allocation (continued)• Memory allocated via malloc is persistent: it will continue to
exist until the program terminates or the memory is explicitly de-allocated by the programmer (that is, the block is said to be "freed"). This is achieved by use of the free function. Its prototype is
• void free (void *pointer) which releases the block of memory pointed to by pointer.
• Free de-allocates (i.e., releases) memory from the free store– The memory can then be reused by the system to allocate
Memory Leak• A memory leak is an error condition that is created when
an object is left on the heap with no pointer variable containing its address.
void myFunction()
{
int *arrayPtr = malloc (sizeof(int)*100);
// use the Array for the while
} // arrayPtr goes out of Scope
/*The actual allocated memory for the array is still left on the heap*/
The term “memory leak” is one of those strange programmer jokes. In a memory leak, the memory is being “used,” but there is no way of using or accessing the information stored at that memory location. The memory is then unavailable to actually be utilized. Thus it is as if memory has “leaked out of the computer”because it cannot be utilized by the program.
Dangling Pointer• A dangling pointer is created when you delete the pointer’s
stored information and then try to use the pointer. The pointer no longer points to valid storage and may corrupt the program's data.
float *floatPtr = malloc(sizeof(float));
*floatPtr = 3.14;
.
.
free (floatPtr); //now flatPtr points nowhere
.
.
*floatPtr = 4.2 //Error!
A dangling pointer is a very serious memory problem that should be avoided if at all possible. It does more than just limit the functioning of the computer – it can actually corrupt the data of the already-run portion of the program.
Dynamic Memory – Points to Note• The problems related to dynamic memory (free store) are
among the most frequent and most difficult to debug.• Always make sure that you have a valid memory pointer or
else it will lead to the well known problem of a segmentation fault/core dump.
• Dynamic memory is taken up by the developer, and it is a developer’s duty to return it back.
• As there is no built-in garbage collector, C programmers must be very careful with dynamic memory.
Garbage is a dump of unused memory Always make sure,
the pointer in linked lists are freed in the right order? -Write routines to keep track of pointer allocations e.g. safe_calloc()If the program allocates a reserve parachute of memory so that it can shut down gracefully if it runs out of memory – Allocate a reserve parachute of memory
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
Programming Techniques Module 4.4: Introduction to Structures and Unions
• C allows the programmer to create user defined data types using fundamental data types
• Structures and unions are user defined data types– They are collections of variables referred to by a single name– The variables can be of different data types
• Structures and Unions provide an easier means of keeping related information together
• Structures are generally used to represent real world entities, which is not possible with the fundamental data types e.g.: To represent a BOOK Entity , we need a combination of– character array to store Name– float variable to store Price– integer variable to store the Version & so on.
Structures
C allows a new data type to be created using existing data types. This is known as a user defined data type. It can be achieved using structures, unions and enumerated lists.
A structure is a collection of values of different data type. It is similar to an array, but the data that it stores is of different data types.
A structure is a collection of related elements, possibly of different data types, having a single referencing name. Each element (member) in a structure is called a field of the structure.
Structures and unions allow joining of simple variables together to form complex structures
133
Programming Techniques Module 4.4: Introduction to Structures and Unions
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
Programming Techniques Module 4.4: Introduction to Structures and Unions
Name of union variables. Multiple variables can be declared in this way
• Only one element can hold a value A variable of union type can hold one value of any type declared in the union
In the above example memory is allocated to socialSecurityNumber since it needs the largest amount of memory compared to all other data members or elements.
One main use of union is when it is used with structuresExample : struct BookDet{
char BookName[50]; char author[50]; union {
float dollars;int Euro;
};}
Since the name of the union is not specified in the above example, it is known as Anonymous Union.
137
Programming Techniques Module 4.4: Introduction to Structures and Unions
Allocates memory only to the largest element of the union
Memory is separately allocated for each data member of the structure
uses union keyword to define a union
uses struct keyword to define a structure
UnionsStructures
Unions allocate only enough memory to accommodate the largest data member.Unions allow a single portion of memory to be shared by different data types, and they all share the same memory location. Its declaration is similar to structures, but the functionality is different.It is mainly used only when one data member will be chosen to store a value or to access the value already stored.
138
Programming Techniques Module 4.4: Introduction to Structures and Unions
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
• Comment Block – The comment block in a header file describes the purpose
and maintenance history of the file. – The comment block in a source file describes the purpose
and maintenance history of the file. – Each function (excluding Get and Set access functions and
Operators) must have a header that includes the following elements: • Name• Description• Parameters• Return• Side Effects
Coding Conventions: Best Practices
Explanation to the function elements are as given below:NAME - Name of the function. DESCRIPTION - Describes the purpose, usage and other important information
concerning this function. Any precondition should be specified here. Note: Do not describe how the function does its job. That's what the source code is for.
PARAMETERS - A list of each of the parameter names and a brief description of that parameter. The name of the parameter should be followed by one of three.
RETURN - The type returned and a brief description of that object. Include any requirement for this return type (e.g., must release the memory).
SIDE EFFECTS - Anything that might happen that would not normally be expected by a user.
Declarations:• One declaration per line is recommended since it
encourages commenting. • Please Note:
– int level; /* indentation level */– int size; /* size of table is preferred over */– int level, size; /*Do not put different types on the same line*/
• For example:– int foo, fooarray[]; /* WRONG! */
• Never put two different types together– char desig; int appraisals[3]; /* WRONG! */
Variable Declaration: Best Practices
The examples above use one space between the type and the identifier.Another acceptable alternative is to use tabs, e.g.:
•int level; // indentation level •int size; // size of table Object currentEntry; •Try to initialize local variables where they're declared. The only reason not to initialize a variable where it's declared is if the initial value depends on some computation occurring first.
if – else : Best Practices• Check if all conditions are covered. Ensure the tests
branch correctly on equalityif (average<60)
grade='C';
else if (average<70 && average>60)
grade='B';
• Don’t avoid the else clause present in code. Ensure the correctness of the else clause i.e. check that the if and else clauses used correctly
Do the if tests branch correctly on equality? : Using > instead of >= or < instead of <= is analogous to making an off-by-one error in accessing an array or computing a loop index. Is the else clause present and documented? : Make sure, you have the else clause to take care of the if conditionsIs the else clause correct? : While testing your code, you might think that the main clause, the if, is all that needs to be tested. Test the else clause also
Are the if and else clauses used correctly – not reversed?Does the normal case follow the if rather than the else? : Put the case you normally expect to process first. This is in line with the general principle of putting code that results from a decision as close as possible to the decision
switch : Best Practices• Always order cases meaningfully• Keep the actions for each case simple – call other routines
if necessary.• Use the default clause to detect and report unexpected
cases• Use break to end each case statement• Don’t assign or create variables specially for a switch
Always order cases meaningfully : Keep cases in a sequenceKeep the actions for each case simple – call other routines if necessary. : don’t keep much code with in a switch. Break it into routines and call these routines under each casesUse the default clause to detect and report unexpected cases : Keep the default cause present in a switch statement which will record all the unexpected casesUse break to end each case statement : Use break statement in switchDon’t use the dummy variable to be able to use the case statement : Work on actual variables, don’t assign or create variables specially for switch
if – else & switch : Best Practices(continued)action = UserCommand[1];
switch(action)
{
case ‘c’: copy();
case ‘d’: delete();
case ‘f’: format();
case ‘h’: help();
default : printf(“\n Invalid Option”);
}
if (strcmp ( UserCommand, “copy”)==0)copy();else if (strcmp ( UserCommand, “delete”)==0)delete();else if (strcmp ( UserCommand, “format”)==0)format();else if (stcmp (UserCommand, “help”)==0)help();elseprintf (“\n Invalid Option”);
Bad Practice
Good Practice
A case statement should be used for simple data that’s easily categorized. If your data isn't simple, use chains of if-then-else's instead. Phony variables are confusing, and you should avoid them.
The variable that controls the case statement is action. In this case, action is created by peeling off the first character of the UserCommand, string, a string that was entered by user. This is a trouble making code. Here, if the user types “copy”the case statement peels off the first “c” and correctly calls the copy(). However, if the user enters “clambake” or “Cement” or “cellulite” etc the case statement peels off the “c” and calls the copy() and the test for an erroneous command in the case statements ‘else’ clause wont work very well because it will miss only erroneous first letter rather than erroneous commands.
Word of Caution• Enter the loop from one location only• Put initialization code directly before the loop• Avoid empty loops• Keep the loop housekeeping chores at either the beginning
or the end of the loop• Assure yourself that the loop ends• Make loop-termination conditions obvious• Avoid code that depends on the loop index’s final value
Example on loop termination condition being obvious:float x = 0.0;for (x=0.1;x != 1.1; x+= 0.1) {
printf("x = %.2f\n", x);}
This code will work with some systems; whereas in some systems it will never terminate. Since the condition checks for inequality and the way the floating variables are treated is different for different systems.This code will work fine if the condition would have been a comparison condition like > or < instead of !.
Loop : Best Practices• Always enter the loop from one location only
goto start;
while (expression)
{
/* statements*/start:
/* statements*/
}
• Put initialization code directly before the loop & Assure yourself that the loop ends.
• Avoid code that depends on the loop index’s final value. Avoid empty loop.
for (count=0;count<index; count++); // Avoid
Always enter the loop from one location only : Dont jump in a loop with a gotostatementPut initialization code directly before the loop & Assure yourself that the loop ends. :
Avoid code that depends on the loop index’s final value. Avoid empty loop.
break & continue : Best Practices• If you cant defend a break or a continue, don’t use it.• Be careful of a loop with a lot of breaks scattered through
it.• Avoid using goto statement • If you use a goto to implement break, go to the statement
immediately following the loop.• Use continue for tests at the beginning of a loop
If you use a goto to implement break, go to the statement immediately following the loop. Ie., do not move back to the beginning of the program
Arrays : Best Practices• Make sure that all array indexes are within the bounds of
the array
int index=11;
int array[10];
printf(“%d”,array[index]);
• Arrays are of sequential structures• Check the end points of arrays
Make sure that all array indexes are within the bounds of the array : Array elements can be accessed randomly; the problem arises when a program tries to access an array element that’s out of bounds. This then results in unexpected errors.Think of arrays as sequential structures : Although, we can access array elements randomly this results in undisciplined, error prone and hard to prove correct correctcodes.Check the end points of arrays : check the end points of arrays, make sure the code is not making an off-by-one error.
Arrays : Best Practices(continued)• If an array is multidimensional, make sure its subscripts are
used in the correct orderArray[i,j];
Array[j,i];
• Watch out for index cross talk– While we are using nested loops, its easy to mis-type Array[ j ]
when we mean Array[ i ]. Switching loop indexes is called “index cross talk”
• Throw in an extra element at the end of an array – If the array access is off by one and you write beyond the end
of an array, it can cause a serious error
If an array is multidimensional, make sure its subscripts are used in the correct order : Common & easy mistakes are giving indexes in wrong order.Watch out for index cross talk : While we are using nested loops, its easy to write Array[j] when we mean Array[i]. Switching loop indexes is called “index cross talk”Throw in an extra element at the end of an array : This is off-by-one error. If the array access is off by one and you write beyond the end of an array, it can cause a serious error
Best Practices : Pointers• If the pointer operations are isolated in functions - Isolate
pointer operations in routines• If the pointer references valid, or could the pointer be
dangling - check pointer before using them• If the code checks pointer for validity before using them -
Check the variable referenced by the pointer before using it.
• If the variable that the pointer references checked for validity before its used
If the pointer operations are isolated in functions - Isolate pointer operations in routines : Suppose we are using a linked list in several places in a program. Rather than traversing the list manually each place its used, write access routines such as NextLink(), PreviousLink(), etc. By minimizing the number of places in which pointer are accessed we minimize the possibility if making careless mistakes that spread throughout the code and may take forever to find it. Writing functions for pointer allocation is another way to centralize the control over dataIf the pointer references valid, or could the pointer be dangling - check pointer before using them : Before using a pointer in a critical part of the code, make sure the memory location it points to is reasonable. Example : If we expect memory locations to be between StartData & EndData, we should view a pointer that points before StartData or After EndData suspiciously. We have to determine the values of StartData & EndData. This can be done automatically if you use pointers through access routines rather than manipulating them directly.If the code checks pointer for validity before using them - Check the variable referenced by the pointer before using it.If the variable that the pointer references checked for validity before its used
Best Practices : Pointers (contd..)(1 of 2)• If the use of tag fields to check for corrupted memory is
done• If explicitly redundancies are added• Set pointer to NULL after freeing or disposing of them• If the code uses all the pointer variables needed for the
sake of readability - use extra pointer variable for clarity. Simplify complicated pointer expressions
• Are pointers used only as a last resort, when no other method is available? – Use nonpointer techniques
If the use of tag fields to check for corrupted memory is done : A tag field is field you add to a structure solely for the purpose of error checking. When you allocate a variable, put the value that should remain unchanged into its tag field. When you use the structure, check the tag field's value. If the tag field doesn’t have the expected value, the data has been corrupted. One should use the tag variable before disposing of the variable. A corrupted tag would then tell you that sometime during the life of that variable its contents were corrupted. The more often you check the tag field, however the close to the root of the problem you will detect the corruption.
If explicitly redundancies are added : It is an alternative to use of tag field, i.e. use a certain fields twice. If the data in the redundant field doest match you know memory has been corrupted. This can result in a lot of overhead if you manipulate pointer directly. If you isolate pointer operations in routine, however it adds duplicate code in only a few places.
Best Practices : Pointers (contd..)(2 of 2)• If the use of tag fields to check for corrupted memory is
done• If explicitly redundancies are added• Set pointer to NULL after freeing or disposing of them• If the code uses all the pointer variables needed for the
sake of readability - use extra pointer variable for clarity. Simplify complicated pointer expressions
• Are pointers used only as a last resort, when no other method is available? – Use nonpointer techniques
Set pointer to NULL after freeing or disposing of them : Dangling pointers is a common type of pointer error-using a pointer that had been freed. Pointer errors are hard to detect as the error doesn’t produce any symptoms. By setting pointers to NULL after freeing them, we don’t change the fact that we can read data pointed to by a dangling pointer. But we do ensure that writing data to a dangling pointer produces and error. It will probably be an ugly, nasty and disaster error but at least we can find it instead of someone else finding it.
If the code uses all the pointer variables needed for the sake of readability - use extra pointer variable for clarity. Simplify complicated pointer expressions : Don’t skimp on pointer variables. A variable shouldn’t be used for more than one purpose. This is especially true in case of pointer variables.
Are pointers used only as a last resort, when no other method is available? – Use nonpointer techniques : Pointers are harder than average to understand, they are error prone, and they tend to require machine-dependent, importable code. If you can think of an alternative to using a pointer that works reasonably well, save yourself a few headaches and use it instead.
Contents• Introduction to searching techniques• Types of Searching• Introduction to sorting techniques• Types of Sorting• Introducing the concept of analysis of algorithms
167
Programming Techniques Module 5: Searching and Sorting
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.
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
Programming Techniques Module 5: Searching and Sorting
Binary Search Algorithm1. Initialize Low to the index of the first element.2. Initialize High to the index of the last element.3. Repeat through step 6 while Low <= High4. Middle=(Low+High)/25. If search element is equal to the middle element then
add 1 to the Index of middle element and return the value
6. If search element is less than middle elementHigh=Middle-1elseLow=Middle+1
Selection Sort• In Selection sort it selects the smallest unsorted item
remaining in the list, and then swapping it with the item in the next position to be filled.
• It Beginning with the first element in the array, a search is performed to locate the element which has the smallest key. When the element is found it is interchanged with the first element. This process is continued for all the elements in the array.
• It is mainly used with small list of elements
Selection sort, starts by comparing the entire list for the lowest item and moves it to the 1st position. It then compares the rest of the list for the next-lowest item and places it in the 2nd position and so on until all items are in the required order. Selection sorts perform numerous comparisons, but fewer data movements than other methods.
173
Programming Techniques Module 5: Searching and Sorting
Selection Sort Algorithm1. Repeat thru steps 5 a total of n-1 times.2. Record the number portion of the vector already used.3. Repeat step 4 for the elements in the unsorted portion of
the vector.4. Record location of smallest elements in unsorted vector5. Exchange first element in unsorted vector with smallest
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.
Exercise 01 – Activities to practice to Algorithm, Flow chart and Testing
Estimated Completion Time: 30 minutes
Overview During Activity 1 you will practice simple logic formulation. The activity helps in understanding the working of algorithm, flowchart and testing.
Instructions
Activity 1.0 Write an algorithm, flow chart & test cases to find the sum of first 50 integers (It uses Iterational algorithm technique.)
Activity 1.1 Write an algorithm, flow chart & test cases to search an element in a table of N values (Uses iterative and selection algorithm technique)
Activity 1.2 Write an algorithm, flowchart & test cases to find the sum of N even numbers (Uses iterative algorithm technique)
Activity 1.3 Write an algorithm, flowchart & test cases to find a Fibonacci series
(Fibonacci series is of the form 0,1,1,2,3,5…………………………Generate the
series up to N terms)
Activity 1.4 Write an algorithm and flowchart & test cases to find the maximum &
minimum among three numbers entered from the keyboard. (Use selection
technique.)
1
Programming Techniques Module1: Fundamental Programming Concepts
Overview Activity 2 gives you an idea about application of top-down approach
Instructions Design the Payroll System using Top-down approach.
Hints 1. Remember motivation comes from within. Take responsibility for your own learning. 2. Take notes from each presentation and activity. 3. If you don’t understand something, ask questions. 4. Participate in course discussions. 5. Practice what you’ve learned to keep your skills sharp.
1.
2
Programming Techniques Module2: Introduction to C and Functions
Exercise 03 – Activity on different control structures Estimated Completion Time: 60 minutes
Overview Activity 3 gives you an idea about application of top-down approach
Instructions Activity 3.0 Write a C program to find Factorial of a given number. Activity 3.1 Write a C program to find sum of 10 positive numbers Activity 3.2 Write a menu driven program, to find the Addition, Subtraction, Division & multiplication of the 2 given numbers Activity 3.3 Given the number of hours an employee worked and the hourly wage, compute the employee’s weekly pay. Count any hour over 40 as overtime. Consider every 1 hr overtime as 1hr 30 mins (1 hr OT = 1hr 30 min). Activity 3.4 Write a program to add an 8% sales tax to any commodity purchases and round the price accordingly. Activity 3.5 Write a program to convert the month number to the month name Activity 3.6 Write a program that calculates how much money a person earns over a period of time (entered by user), if he is working on the following salary pattern: 100 Rs: 1st week 150 Rs: 2nd week 200 Rs: 3rd week 250 Rs: 4th week
3
Programming Techniques Module2: Introduction to C and Functions
Activity 3.7 Chuckie Lucky won a million Rs, which he places in an account that earns 8% a year. On the last day of each year, Chuckie withdraws Rs 100,000. Write a program that finds out how many years it takes for Chuckie to empty his account. Activity 3.8 Amit invests Rs. 1000 at 10% simple interest. (That is, every year, the investment earns an interest equal to 10% of the original investment). Anand invests Rs1000 at 5% interest compounded annually. (That is, interest is 5% of the current balance, including previous addition of interest.) Write a program that finds how many years it takes for the value of Anand's investment to exceed the value of Amit's investment. Also show the two values at that time. Activity 3.9 The ABC Mail Order Grocery sells artichokes for Rs. 2.25 per kg, beets for Rs. 5.65 per kg, and carrots for Rs. 10.89 per kg. They give a 5% discount for orders of Rs. 1000 or more prior to adding shipping costs. They charge Rs. 3.50 shipping and handling for any order of 20 kg or under, Rs. 7.00 shipping and handling for orders over 20 kg and under 25 kg, and Rs. 10.50 plus Rs. 1.00 per kg for shipments of 25 kg or more. Create following menu to take user input: ---------------------------------------------------------------------------------------------------- Grocery Menu A: To enter quantity of artichokes desired in kgs. B: To enter quantity of beets desired in kgs. C: To enter quantity of carrots desired in kgs. D: To Quit The user has to enter one of the above characters (A, B, C or D) to enter appropriate information. Use switch statement in a loop to achieve this. The program then should compute the total charges, the discount if any, the shipping charges, and the grand total. The program then should display all the purchase information: the cost per kg, the quantity ordered, the total cost of the order, the discount, the shipping charge, and the grand total of all the charges.
4
Programming Techniques Module2: Introduction to C and Functions
Overview Activity 4 helps you to have hands on experience in using functions in C programming.
Instructions Activity 4.1
Write a C program using function which accepts date of birth and the current date and provides the age in years- month-day format
Activity 4.2 Using functions, write a menu driven program, which offers a list of items & their price per unit where certain items have a discount of 10% if the quantity purchased is more than 25 units. Write a program to calculate the total expenses, if quantity demanded is entered through keyboard.
Activity 4.3 Using functions, write a menu driven program which generates a salary slip. Allow user o view the Total earning, deduction: deduction scheme
Activity 4.4 The Kelvin scale, commonly used in science, is a scale in which 0 represents absolute zero, the lower limit to possible temperatures. Here is the formula for converting Celsius to Kelvin: Kelvin = Celsius + 273.16. Write a program that requests the user to enter a Fahrenheit temperature. The program should read the temperature as a type double number and pass it as an argument to a user-supplied function called Temperatures(). This function should calculate the Celsius equivalent and the Kelvin equivalent and display all three temperatures with a precision of two places to the right of the decimal. It should identify each value with the temperature scale it represents. Here is the formula for converting Fahrenheit to Celsius: Celsius = 1.8 * Fahrenheit + 32.0. The Temperatures () function should use const to create symbolic representations of the three constants that appear in the conversions. The main () function should use a loop to allow the user to enter temperatures repeatedly, stopping when a q or other non-numeric value is entered.
Activity 4.5 A teacher generates the results by aggregating the marks in 6 subjects and then assigns the letter grades using table 3.1. Further, using the modifiers listed in table 3.2 he also sets a + or - qualifiers after the letter
5
Programming Techniques Module2: Introduction to C and Functions
grade, based on the last digit of the score. For example, 81=B-, 94=A, and 68=D+. Note: An F is only an F. There is no F+ or F-. Using functions write a program to generate the grade in the above mentioned pattern, also allow the user to enter values repeatedly.
Table 4. 1
Aggregate Percentage Last Digit
0-60 F
61-70 D
71-80 C
81-90 B
91-100 A
Table 4. 2
Last digit Modifier
1-3 -
4-7 <blank>
8-0 +
Activity 4.6 Using recursive function Write a c program to find the Fibonacci series of
N numbers
6
Programming Techniques Module2: Introduction to C and Functions
Hints 1. Remember motivation comes from within. Take responsibility for your own learning. 2. Take notes from each presentation and activity. 3. If you don’t understand something, ask questions. 4. Participate in course discussions. 5. Practice what you’ve learned to keep your skills sharp.
7
Programming Techniques Module3: Arrays, Pointers And Structures
Overview Activity 5 will give you hands on experience in using arrays in C.
Instructions
Activity 5.0 Find whether the entered character is lower case or upper case character
Activity 5.1 Write a program to accept a 4 digit number and print the individual digits in a string format. (The number 7500 will be printed as “Seven Five Zero Zero”)
Activity 5.2 Write a program to merge two arrays into third array.
Activity 5.3 Write a function that returns the maximum value of an array of numbers.
Activity 5.4 Write a program to left rotate all the elements of an array by one position
Activity 5.5 Write a mailing list program. This program will read, write, sort, edit and print mailing labels.
Activity 5.6 Write a program to record maximum temperature in 5 cities during a month for 5 days. Provide highest and lowest temperature for each corresponding city over the month.
Activity 5.7 Write a function that scans a string for the character "-" and replaces it with "_"
Activity 5.8 Using if else statements, write a program that reads input up to #, replaces each period with an exclamation mark, replaces each exclamation mark initially present with two exclamation marks, and reports at the end the number of substitutions it has made.
8
Programming Techniques Module3: Arrays, Pointers And Structures
Overview Activity 6 will give you hands on experience in using pointers in C.
Instructions
Activity 6.0 The ABC Mail Order Grocery sells artichokes for Rs2.25 per kg, beets for Rs5.65 per kg, and carrots for Rs10.89 per kg. They give a 5% discount for orders of Rs1000 or more prior to adding shipping costs. They charge Rs3.50 shipping and handling for any order of 20 kg or under, Rs7.00 shipping and handling for orders over 20 kg and under 25 kg, and Rs10.50 plus Rs1.00 per kg for shipments of 25 kg or more. Write a program that uses a switch statement in a loop such that a response of a lets the user enter the kg of artichokes desired, b the kg of beets, c the kg of carrots, and q allows the user to exit the ordering process. The program then should compute the total charges, the discount, if any, the shipping charges, and the grand total. The program then should display all the purchase information: the cost per kg, the kg ordered, and the cost for that order for each vegetable, the total cost of the order, the discount, if there is one, the shipping charge, and the grand total of all the charges.
Activity 6.1 Write a program that requests the hours worked in a week and then prints the gross pay, the taxes, and the net pay. Assume the following:
a. Basic pay rate = Rs500.00/hr (Example)
b. Overtime (in excess of 40 hours) = time and a half
c. Tax rate 15% of the first Rs3000
20% of the next Rs1500
25% of the rest
10
Programming Techniques Module3: Arrays, Pointers And Structures
The program will present a menu of pay rates from which to choose. The beginning of a run should look something like this: *********************************************************** Enter the number corresponding to the desired pay rate or action: 1) Rs200/hr 2) Rs300/hr 3) Rs400/hr 4) Rs500/hr 5) Quit *********************************************************** If choices 1 through 4 are selected, the program should request the hours worked. The program should recycle until 5 are entered. If something other than choices 1 through 5 is entered, the program should remind the user what the proper choices are and then recycle. (HINTS: Use #defined constants for the various earning rates and tax rates. Use a switch to select the pay rate.)
11
Programming Techniques Module3: Arrays, Pointers And Structures
Overview Activity 7 will give you hands on experience in using Structures and Unions in C.
Instructions
Activity 7.0 Using structures create a program that searches for Customer details (name, accountNo, accountType, balance) based on the customer id.
Activity 7.1 Write a program using structure to accept and display employee details.(use nested structure for salary(basic, da, hra, pf).
Hints 1. Remember motivation comes from within. Take responsibility for your own learning. 2. Take notes from each presentation and activity. 3. If you don’t understand something, ask questions. 4. Participate in course discussions. 5. Practice what you’ve learned to keep your skills sharp.
1.
12
Programming Techniques Module4: Searching and Sorting
Overview During this activity you will implement all the algorithms that were discussed in the module.
Instructions
Activity 8.0 Write a program to search an element in a list using:
1. Sequential Search 2. Binary search
Note: Elements should be in sorted order for Binary search
(Use the algorithms discussed in the session).
Activity 8.1 Write a program to sort a given list of numbers using:
1. Bubble sort 2. Selection sort
(Use the algorithms discussed in the session).
Hints 1. Remember motivation comes from within. Take responsibility for your own learning. 2. Take notes from each presentation and activity. 3. If you don’t understand something, ask questions. 4. Participate in course discussions. 5. Practice what you’ve learned to keep your skills sharp.
Foods Price in Rs. /Serving Serving Size Calories Cholesterol mg Total_Fat g Sodium mg Carbohydrates g Dietary_Fiber g Protein g Vit_A IU Vit_C IU Calcium mg Iron mg