You are on page 1of 22

# Assignments for Programming & Testing

Dec 2008

CONTENTS .............................................................................................................. 1 CONTEXT ............................................................................................................... 2 GUIDELINES ............................................................................................................. 2 DAY-1 ASSIGNMENTS .................................................................................................. 2 SELF EXERCISES DEBUGGING EXERCISES ……………………………………………………………………………………………………………………………..4 DAY-2 ASSIGNMENTS ................................................................................................ 11 PROBLEM SOLVING EXERCISES DAY-3 ASSIGNMENTS ................................................................................................ 14
UNIT TESTING EXERCISES

DAY-4 ASSIGNMENTS ................................................................................................ 16
CODE REVIEW

EXERCISES

Context
This document contains assignments to be completed as part of the hands on for the subject Programming & Testing. Few of the assignments can be re-used in P&T project.

Guidelines
• • • • • • Coding Standards need to be followed, wherever necessary. Header, footer and proper documentation are necessary for all programs implemented. These assignments contain Self exercises, debugging exercises, problem solving, code review and developing test case exercises Solving these exercises methodically would provide confidence to the learner to attempt the module and online exams The estimated time would help a learner to solve problems given a deadline The assignments need to be completed in sequence on day basis as instructed by the facilitators and submitted appropriately

Day-1 Assignments
1. What will be the values of iValue1 and iValue2 if iNumber assumes a value of a. 1 b. 0 iValue1 = 1; iValue2 = 1; if (iNumber > 0)

acString[10] + ‘5’). 3.iValue1 = iValue1 + 1. fnDivide(10. float fnDivide(float fValue1.2). printf(“%c\n”. The following function returns the value of x/y.acString[i]). iValue2).acString[iIndex]). h. e. for (iIndex=0. acString). c..10s”.acString[i] != “. printf(“%25. printf(“%d%d”. b.”. printf(“%s”. iIndex++) printf(“%d\n”. 2. Assuming the variable acString contains the value “The sky is the limit”.acString[i]). iIndex<= strlen(acString].acString[0]).) { acString[iIndex++] = iIndex.acString[10] + 5). } g. for (iIndex=0. iIndex++) printf(“%c”. printf(“%s”. f. d.acString). printf(“%s\n”. for (iIndex=0. acString[iIndex] != ‘\0’. } What will be the value returned when the function fnDivide is called with the parameters given? a. iValue1. float fValue2) { return (fValue1 / fValue2). printf(“%c\n”. Determine what will be the output of the following code segments: a. . iValue2 = iValue2 – 1.

int main(int argc.5.2).c 3. After corrections. * FileName: CalculationOfArea. Objective: To identify errors in the program. iTemp1 = fnProd(iNumber1. iTemp2). int iValue2) { return (iValue1 * iValue2).b. fnDivide(4. } Debugging Exercise 1. fnProd(iNumber1. * Description: This is a program to find the perimeter and area 5.2)). ***************************************************************/ 7. printf("%d%d\n". iTemp1. * of circle 6. iTemp2. iTemp2 = fnProd(iTemp1. char **argv) { int iNumber1 = 10.iNumber2). int iNumber2 = 20. 4. Determine the output of the following program: #include <stdio. Infosys Technologies Limited 4./*************************************************************** 2. int iTemp1.h> int fnProd(int. c. return 0. } int fnProd(int iValue1. fnDivide(9.1.5). what output would you expect when you execute it? 1. . * Author: E&R Department.int).

float fPerimeter. return 0. 34. if (iCode > 1). * int argc . #include<stdio. 37. 29.14159 11. 35. 30. char **argv) 24. * 15. 23. /* variable declaration */ 27. float fArea. fArea = iCircumference * iRadius * iRadius. fPerimeter. if any. fPerimeter = 2. 31.no of cmd line parameters 18. 36. Find errors. * DESCRIPTION: Entry point to the program 16.cmd line parameters 19. “).c 41. in each of the following segments: a. printf("%f". 33. **********************************************************/ 2. * char **argv . *********************************************************** **/ 22. * RETURNS: 0 on success. Non-Zero value on error 20. 32. 10. * Function main 14. iRadius = 5. * PARAMETERS: 17. if (iNumber1 +iNumber2 = iNumber3 && iNumber2 > 0) printf(“ b. . * End of CalculationOfArea. 12. %d". fArea). { 25. 26.0 * iCircumference * iRadius. /********************************************************** ** 13. int iRadius. * Working with array 21.8. } 39. /********************************************************** 40. iCircumference = PI. int main(int agrc. iCircumference.h> 9. 38. 28. #define PI 3.

b. for (.2. float fItem [3][2] = {0.0. iIndex3). iSum = iSum + iNumber. .0.1.5}. iIndex2 = 0. printf(“Hello\n”). if any. iIndex1 + iIndex2 < 10. iCount = iCount + 1. While (iCount != 10). 4. iIndex3 > 0. Find errors. if (iTemp1 < 0) || (iTemp2 < 0) printf(“Sign is negative”).iValue1 = iValue2 + iValue3 else iValue1 = 0 c. int iNumber[] = {0. 3. do { cName = cName + 1. } b. iIndex1 = 1. { iCount = 1. in each of the following looping segments. cName = 0.3. ++iIndex2). Identify errors. printf(“%f”. printf(“My name is XXXX\n”).0}.4.) iIndex3 = iIndex3 – 1. } while (cName = 1) c. if any. Assume that all the variables have been declared and assigned values. a. for (iIndex3 = 10. iIndex1 = iIndex1 + 10 d. in each of the following initialization statements: a.0.

d.0.0. char **argv) { /* variable declaration */ int aiArr[SIZE]. /*************************************************************** * FileName: arrayAssignment. printf("\nEnter the 10 numbers "). Infosys Technologies Limited * Description: This is a demo program to find the sum * 10 numbers using array ***************************************************************/ #include<stdio.h> #define SIZE 10 /************************************************************ * Function main * * DESCRIPTION: Entry point to the program * PARAMETERS: * int argc .c * Author: E&R Department.’Y’}.0)(1.1)}. 5. char cWord[] = {‘A’.’R’. e. Step 1: Type the following program.1. to identify and debug the program Problem Description: Try to locate the error in the program.4] = {(0.no of cmd line parameters * char **argv .’A’.1. float fResult[10] = 0. Non-Zero value on error * Working with array *************************************************************/ int main(int agrc. int iArray[2. int iIndex.’R’. Objective: To write a program in C using arrays. int iSum .cmd line parameters * RETURNS: 0 on success. /* get the value of 10 numbers and store them in an array */ .c.

iIndex <= SIZE. Step 4: Try to locate the error in the program and display the output. 6. } printf("\nThe sum is %d".c * Description: A test program created to familiarise students * on how to handle compiler and linker errors when writing * programs. /* return the value back to OS! */ return 0. Objective: To identify and debug the program /************************************************************ * Filename: compileerrors. } /* calculate the sum of the numbers in the array */ for( iIndex = 0. Step 3: The program on execution leads to runtime errors.aiArr[iIndex]). * Date: 01-Dec-2008 *************************************************************/ . * Author: E&R Department. iIndex ++ ) { scanf("%d".for( iIndex = 0.iSum).c ***************************************************************/ Step 2: Compile the program. iIndex++ ) { iSum = iSum + aiArr[iIndex]. Execute it. } /************************************************************ * End of arraydebug. Infosys Technologies Ltd. iIndex < SIZE.

double dPriceAfterDiscount.Number of command line arguments * char **argv The command line arguments passed * Returns: 0 on success to the operating system *************************************************************/ int main (int argc. dNetPrice. char** argv) { /* declaration of variables */ double dPrice. * * (Code with errors in it.#include <stdio. Program accepts the price of * the product and also Sales Tax Rate. Students have to find and fix it) * Input Parameters: * int argc . dDiscount. fflush (stdin). /* Read the Sales Tax in percent */ printf ("Enter the sales tax (in %%): "). Sales Tax is * computed after the discount.h> /************************************************************ * Function: main() * Description: Program computes the discount based on the * Price of the product. /* Read the Price of the item */ printf ("Enter the price of the product (INR): "). . &dPrice). scanf ("%lf".

dPriceAfterDiscount). fflush (stdin). printf ("Net Price: %. printf ("Discount: %. } else { /* For any product costing less than INR 500.scanf ("%lf". . &dSalesTax). /* Calculate the Net Price */ dNetPrice = dPriceAfterDiscount + ((dPriceAfterDiscount * dSalesTax) /100.((dPrice * dDiscount) / 100.2lf\n". dSalesTax) dPriceAfterDiscount = dPrice .2lf\n". printf ("Sales Tax: %. dDiscount).2lf %%\n".0. dPrice). /* For any product costing more than INR 500. Discount = 15% */ dDiscount = 15.0).0).2lf\n". dNetPrice). /* Return a success code to the Operating System */ return 0.0.2lf %%\n".0) dDiscount = 25. printf ("\nPrice after Discount: %. Discount = 25% */ if (dPrice > 500. } /* Print the summary */ printf ("\nPrice of the product: %.

If any other character is encountered. Declare a function ‘fnEmployeeNameValid’ that accepts the name as an argument 3.} /********************************************************************* * end of compileerrors. Declare the error codes using #define 6. The allowed characters in an employee’s name are: lower case and upper case alphabets and a blank space. If the name contains valid characters then return a success code to function ‘main’ 7. and net pay. An operation to return the weekly gross pay. (Hint: Use ‘for’ loop) 4. Obtain the employee's name. The requirements are as follows: a. 2. gross pay. where overtime is paid at the rate of time-and-a-half for any hours worked over 40. Write a program to accept two strings and to count the common characters present in the strings using a function. Accept the name of a person 2. Write a program to count the Vowels in a given string using pointers. 4.50 per hour and the hours worked to 0 when the employee is defined. hourly rate. including overtime pay. The function should receive a pointer to these strings and should return . An operation to initialize the hourly rate to a minimum wage of \$5. e. An operation to return the weekly net pay. c. An operation to display the employee's name. based on a 30% deduction for taxes and benefits. b. Each individual character should be checked. return a suitable error code to function ‘main’ 5. Write a program in C for the given requirements.c *********************************************************************/ Day-2 Assignments 1. Write a function to check Employee Name Validation The requirements are as follows: 1. Depending on the return value display “Valid name” or “Invalid name” 3. and hours worked from the user. d.

Problem Description: • • • Create a structure called with three short int members namely day. Display the telephone number • • • 6.the count of common characters. The requirements are as follows: Declare a character array to hold a 7-digit telephone number • • Accept the telephone number as a string. month and year Create an instance of this structure called as dateOfBirth Display the date of Birth in the formal day-mon-year (Example: If the date of birth is 05-06-1991 then the display should be 05-Jun-1991) 7. Declare VALID and INVALID using #define The valid months are between 1 and 12 The valid days ranges between 1 to 31 Every 4th year is a leap year and every 400th year is also a leap year. (Example : For the above telephone number the function should return next telephone number in the sequence as 1001002) Use ‘atoi’ function to convert the given string to an integer. Because it is also divisible by 100 and not divisible by 400) Return the error code to function ‘main’ Display the message “Valid Date” or “Invalid Date” depending on the error code . The first four digits is the department code and the last three digits is the telephone number. Creating structures” create the structure to store date of birth Write a function that accepts instance of date of birth as an argument The function should validate the date and return the VALID or INVALID code. (The function ‘atoi’ accepts a character array and returns the integer equivalent if the string contains only digits) Increment the telephone number and return it to the function ‘main’. Write a program to automatically generate the telephone numbers. Year 1900 is not a leap year even though it is divisible by 4. Write a program to Validate the date of birth of a person. It should be made case insensitive) 5. (Example: If the strings were “Infosys” and “Microsoft” then the count will be 4. (Example: year 2000 is a leap year not only because it is divisible by 4 but it is also divisible by 400. Write a program to create a structure to store the date of birth of a person. (Example: If the telephone number is “1001001” then “1001” is the department code and “001” is the telephone number) Write a function called as ‘fnGenerateTelNumber’ that accepts the telephone number string as an argument and returns the next telephone number in the sequence. Problem Description: • • • • • • • • • As described in “Assignment-6.

Assume that m characters are extracted. Write a program to arrange the telephone extension numbers of ‘N’ employees in the ascending order using insertion sort. batting average Using cricket. declare an array player with 50 elements and write a program to read the information about all the 50 players and print a team-wise list containing names of players with their batting average. 11. 9. 10. Write a function fnDay_Name that receives a number n and returns a pointer to a character string containing the name of the corresponding day. It should display the corrected string with no blank spaces. Write a program to arrange the department codes of ‘N’ departments in descending order using selection sort. The day names should be kept in a static table of character strings local to the function. Marks in physics >= 50 c. Note : Use built in functions wherever possible. starting with the nth character. Write a program that receives a character string and a character as argument. Using pointers. Assume the total number of applications to process is “n”. Write a program to search for an employee id in an array containing ‘N’ employee Ids using binary search. Total in all three subjects >= 200 or Total in mathematics and physics >= 150 Given the marks in three subjects. Perform the following: a. A function to Count the occurrences of the given character in the character string b. team name. Write a program to extract a portion of a character string and print the extracted string.8. Marks in mathematics >= 60 b. 13. A function to delete all occurrences of this character in the character string. Write a program to process the applications to list the eligible candidates. 15. Define a structure called cricket that will describe the following information: Player name. 14. 12. . Admission to a professional course is subject to the following conditions: a. Marks in chemistry >= 40 d.

. Day-3 Assignments Assignment 1: Identifying Test cases using Boundary Value analysis Objective: To identify and document test cases for a given functionality. Minimum Amount is Rs. appropriate Error messages should be displayed. 5000 to 10000 5% * Rs. using Boundary value Analysis... /****************************************************************** * Function: fnComputeRateOfInterest * Description: Given the Amount in Rs. 200001 to 25000 11% * Rs. 150001 to 20000 9% * Rs. Problem Description: Consider the function below whose functionality is described in its documentation.. computes and returns * the interest rate. Sl No Test case name Test Procedure Precondition Expected Result Reference to Detailed Design / . ******************************************************************/ float fnComputeRateOfInterest (int iAmount) { . 250001 to 30000 15% * PARAMETERS: * int iAmount Amount * * RETURNS: Appropriate Rate of Interest. . then the month should be displayed as October. * * Criteria for Interest: * Rs. 10001 to 15000 7% * Rs.Example: if the day is 10. -1.5000 and * maximum Amount is 30000. } Step 1: Create an Excel sheet with the columns shown below. If the value of the day exceeds 12.0 in case of error..

EmpId : . Assignment 2: Identifying Test cases using Logic Coverage Objective: To identify and document test cases for a given user interface design. EmpId starts from 1001. Step 3: Document them in the Excel sheet created earlier. Problem Description: Online Balance Enquiry The User interface design for balance enquiry is given. using Logic coverage Analysis. account number should be a 10 digit number. PIN Number: Account Number: Balance Amount: ……………………………………………………… Submit Assignment 3: Identifying Test cases using Logic Coverage Objective: To identify and document test cases for a given user interface design. it displays appropriate error message. Problem Description: Searching an Employee Telephone number The user interface design for searching an employee telephone number is given. Otherwise. using Logic coverage Analysis.Spec Document Step 2: Identify the test cases based on boundary value analysis. The user can enter either empId or employee name to fetch the telephone number. no special characters except dot (. Employee name should contain min 5 and max 30 characters. Balance amount is displayed if valid PIN number and account number are entered by the user. PIN number can take only 4 digits starting from 1000.) and blank space.

h> #include <string. Step 1: Type the following source code /******************************************************************************* * File Name: bookInventory. Submit Day-4 Code Review Assignment Objective: To Review the code based on the checklist. The source code calculates and displays the total price of the book based on the quantity ordered.Name of the author (Range: 20 characters) . The checklist is given in the PF course material in Code Review Chapter.c * Description: Simple program which calculates area of a circle. Problem Description: Searching and ordering a book from the Library.h> /* Business Logic related error and success codes */ #define SUCCESS 0 -1 #define ERROR_INSUFFICIENT_BALANCE /******************************************************************************* * Structure: book * Description: Stores book details* * Member Variables: * acAuthor . * Author: ABC * Date: 02-Dec-2008 *******************************************************************************/ #include <stdio.Employee Name : Telephone Number : ………………………………………………….

float fPrice. /******************************************************************************* * Function: main() * Description: A code to search for a book in the Inventory. that book is searched in the library. void fnGetString(char []). if the book is available. }. } date.* * acTitle .Price of the book *******************************************************************************/ struct book { char acAuthor[20]. int atoi(char[]). int iYear. char[].Title of the book (Range: 30 characters) fPrice . struct { char acMonth[10]. If the requested number of copies . /* Forward declarations of functions*/ int fnLook_Up (struct book sBook[]. then the number of copies is requested from the user and the total cost is displayed. char[]. int iQuantity. char acPublisher[10].int). char acTitle[30]. * * * When a customer requires a book.

int iquantity. iNo_of_Books = sizeof(sbook) / sizeof(struct book). {"Herbert". {"B V Kumar". printf("\n Title: fnGetString(title). char** argv) { /* Declare an instance of bookdetails */ char title[30].Number of command line arguments char **argv The command line arguments passed 0 on success to the operating system * Returns: *******************************************************************************/ int main (int argc."Hayden". 0} }. "C Language"."TMH"."Web Services". "Programming in Java".180.1983.00.* are not available. * Input Parameters: * * int argc . 5}. author[20]. "PHI".1995. iNo_of_Books. 1977. "DreamTech". 90. 250.150. ").1984. int iIndex. static struct book sbook[] = { {"Ritche"."january". "May"."October".00. char acResponse[10]. then appropriate error message is displayed. do { printf("Enter title and author name \n"). "SCJP". . "July".10}. printf("Author: "). {"Sierra Bates".00. quantity[10].10}.

acMonth. fnGetString(quantity). sbook[iIndex].acPublisher ). else printf("\nRequired copies not in stock\n\n"). iIndex = fnLook_Up(sbook. } else printf("\nBook not in list\n\n").date. if (iIndex != -1) /* Book found */ { printf("\n%s%s%.fPrice * iquantity). fnGetString(acResponse). if (iquantity < sbook[iIndex].author. iquantity = atoi(quantity). iquantity.2f\n". printf("\nDo you want ay other book? (YES/NO):"). sbook[iIndex]. sbook[iIndex].fPrice.iYear. sbook[iIndex]. sbook[iIndex]. title.date.acTitle.iNo_of_Books).fnGetString(author).acAuthor. sbook[iIndex].2f %s%d%s\n\n". } .iQuantity) printf("Cost of %d copies = %. sbook[iIndex]. printf("Enter number of copies:").

acstring[i-1] = '\0'. acstring[i++] = c. return 0.String which has to be input *******************************************************************************/ void fnGetString (char acstring[]) { char c. } /******************************************************************************* * Function: fnLook_Up . } /******************************************************************************* * Function: fnGetString * Description: Gets the character input from the User * Input Parameters: * * * Returns: nothing char string[] . printf("\n\nThank you. Good Bye\n"). } while (c != '\n').while(acResponse[0] ='Y' || acResponse[0] == 'y'). int i = 0. do { c = getchar().

i++) if (strcmp(actitle. /* book found */ return(-1).acTitle) == 0 || strcmp(acauthor. Step 4: Write the Review comments in the Review_Comments.which receives the title char acauthor[] . char actitle[].A variable is declared as type struct book char actitle[] .* Description: A function which searches for the book in the list * Input Parameters: * * * * * Returns: * * * *******************************************************************************/ int fnLook_Up(struct book sbook[]. char acauthor[]. -1 when the book is not found book sbook . There are no errors or warnings in the source code. Refer to the list of checklist in the course material.which receives the author name int iTotal_No_Of_Books . Step 3: The code has to be reviewed based on the checklist.xls file as follows: /* book not found */ Serial Number on success. for (i=0. sbook[i]. } Step 2: Compile & Execute the source code. i < iTotal_No_Of_Books.which receives the total number of books in the list .acAuthor) == 0) return (i). sbook[i]. int iTotal_No_Of_Books) { /* Declaration for account number and amount */ int i.

. Suggestion Write a proper description Step 5: Incorporate the Review comments in the source code and now execute the code.Sl No 1 Line # 3 Comment Description of C file does not reflect what the code is meant for.