Assignments For Programming & Testing
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
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)
iValue1 = iValue1 + 1; iValue2 = iValue2 1; printf(%d%d, iValue1, iValue2); 2. Assuming the variable acString contains the value The sky is the limit. Determine what will be the output of the following code segments: a. printf(%s,acString); b. printf(%25.10s, acString); c. printf(%s,acString[0]); d. for (iIndex=0;acString[i] != .; iIndex++) printf(%c,acString[i]); e. for (iIndex=0; acString[iIndex] != \0; iIndex++) printf(%d\n,acString[i]); f. for (iIndex=0; iIndex<= strlen(acString];;) { acString[iIndex++] = iIndex; printf(%s\n,acString[iIndex]); } g. printf(%c\n,acString[10] + 5); h. printf(%c\n,acString[10] + 5); 3. The following function returns the value of x/y. float fnDivide(float fValue1, float fValue2) { return (fValue1 / fValue2); } What will be the value returned when the function fnDivide is called with the parameters given? a. fnDivide(10,2);
b. fnDivide(9,2); c. fnDivide(4.5,1.5); 4. Determine the output of the following program: #include <stdio.h> int fnProd(int,int); int main(int argc, char **argv) { int iNumber1 = 10; int iNumber2 = 20; int iTemp1, iTemp2; iTemp1 = fnProd(iNumber1,iNumber2); iTemp2 = fnProd(iTemp1, fnProd(iNumber1,2)); printf("%d%d\n", iTemp1, iTemp2); return 0; } int fnProd(int iValue1, int iValue2) { return (iValue1 * iValue2); }
Debugging Exercise
1. Objective: To identify errors in the program. After corrections, what output would you expect when you execute it? 1./*************************************************************** 2. * FileName: CalculationOfArea.c 3. * Author: E&R Department, Infosys Technologies Limited 4. * Description: This is a program to find the perimeter and area 5. * of circle 6. ***************************************************************/ 7.
8. #include<stdio.h> 9. 10. #define PI 3.14159 11. 12. /********************************************************** ** 13. * Function main 14. * 15. * DESCRIPTION: Entry point to the program 16. * PARAMETERS: 17. * int argc - no of cmd line parameters 18. * char **argv - cmd line parameters 19. * RETURNS: 0 on success, Non-Zero value on error 20. * Working with array 21. *********************************************************** **/ 22. 23. int main(int agrc, char **argv) 24. { 25. 26. /* variable declaration */ 27. int iRadius, iCircumference; 28. float fPerimeter; 29. float fArea; 30. 31. iCircumference = PI; 32. iRadius = 5; 33. fPerimeter = 2.0 * iCircumference * iRadius; 34. fArea = iCircumference * iRadius * iRadius; 35. 36. printf("%f", %d", fPerimeter, fArea); 37. return 0; 38. } 39. /********************************************************** 40. * End of CalculationOfArea.c 41. **********************************************************/
2. Find errors, if any, in each of the following segments: a. if (iNumber1 +iNumber2 = iNumber3 && iNumber2 > 0) printf( b. if (iCode > 1); );
iValue1 = iValue2 + iValue3 else iValue1 = 0 c. if (iTemp1 < 0) || (iTemp2 < 0) printf(Sign is negative); 3. Find errors, if any, in each of the following looping segments. Assume that all the variables have been declared and assigned values. a. While (iCount != 10); { iCount = 1; iSum = iSum + iNumber; iCount = iCount + 1; }
b. cName = 0; do { cName = cName + 1; printf(My name is XXXX\n); } while (cName = 1) c. iIndex1 = 1; iIndex2 = 0; for (; iIndex1 + iIndex2 < 10; ++iIndex2); printf(Hello\n); iIndex1 = iIndex1 + 10 d. for (iIndex3 = 10; iIndex3 > 0;) iIndex3 = iIndex3 1; printf(%f, iIndex3); 4. Identify errors, if any, in each of the following initialization statements: a. int iNumber[] = {0,0,0,0,0}; b. float fItem [3][2] = {0,1,2,3,4,5};
c. char cWord[] = {A,R,R,A,Y}; d. int iArray[2,4] = {(0,0,0,0)(1,1,1,1)}; e. float fResult[10] = 0; 5. Objective: To write a program in C using arrays, to identify and debug the program Problem Description: Try to locate the error in the program. Step 1: Type the following program. /*************************************************************** * FileName: arrayAssignment.c * Author: E&R Department, 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 - no of cmd line parameters * char **argv - cmd line parameters * RETURNS: 0 on success, Non-Zero value on error * Working with array *************************************************************/ int main(int agrc, char **argv) { /* variable declaration */ int aiArr[SIZE]; int iSum ; int iIndex;
printf("\nEnter the 10 numbers "); /* get the value of 10 numbers and store them in an array */
/* calculate the sum of the numbers in the array */ for( iIndex = 0; iIndex < SIZE; iIndex++ ) { iSum = iSum + aiArr[iIndex]; }
printf("\nThe sum is %d",iSum); /* return the value back to OS! */ return 0; } /************************************************************ * End of arraydebug.c ***************************************************************/
Step 2: Compile the program. Execute it. Step 3: The program on execution leads to runtime errors. Step 4: Try to locate the error in the program and display the output. 6. Objective: To identify and debug the program /************************************************************ * Filename: compileerrors.c * Description: A test program created to familiarise students * on how to handle compiler and linker errors when writing * programs. * Author: E&R Department, Infosys Technologies Ltd. * Date: 01-Dec-2008
*************************************************************/
#include <stdio.h> /************************************************************ * Function: main() * Description: Program computes the discount based on the * Price of the product. Program accepts the price of * the product and also Sales Tax Rate. Sales Tax is * computed after the discount. * * (Code with errors in it. Students have to find and fix it) * Input Parameters: * int argc - Number of command line arguments * char **argv The command line arguments passed * Returns: 0 on success to the operating system *************************************************************/ int main (int argc, char** argv) { /* declaration of variables */ double dPrice, dDiscount; double dPriceAfterDiscount, dNetPrice;
/* Read the Price of the item */ printf ("Enter the price of the product (INR): "); scanf ("%lf", &dPrice); fflush (stdin); /* Read the Sales Tax in percent */ printf ("Enter the sales tax (in %%): ");
scanf ("%lf", &dSalesTax); fflush (stdin); /* For any product costing more than INR 500, Discount = 25% */ if (dPrice > 500.0) dDiscount = 25.0; } else { /* For any product costing less than INR 500, Discount = 15% */ dDiscount = 15.0; } /* Print the summary */ printf ("\nPrice of the product: %.2lf\n", dPrice); printf ("Discount: %.2lf %%\n", dDiscount); printf ("Sales Tax: %.2lf %%\n", dSalesTax)
dPriceAfterDiscount = dPrice - ((dPrice * dDiscount) / 100.0); /* Calculate the Net Price */ dNetPrice = dPriceAfterDiscount + ((dPriceAfterDiscount * dSalesTax) /100.0);
printf ("\nPrice after Discount: %.2lf\n", dPriceAfterDiscount); printf ("Net Price: %.2lf\n", dNetPrice);
Day-2 Assignments
1. Write a program in C for the given requirements. The requirements are as follows: a. Obtain the employee's name, hourly rate, and hours worked from the user. b. An operation to initialize the hourly rate to a minimum wage of
$5.50 per hour and the hours worked to 0 when the employee is defined.
e. An operation to display the employee's name, gross pay, and net pay.
2. Write a function to check Employee Name Validation The requirements are as follows: 1. Accept the name of a person 2. Declare a function fnEmployeeNameValid that accepts the name as an argument 3. The allowed characters in an employees name are: lower case and upper case alphabets and a blank space. Each individual character should be checked. (Hint: Use for loop) 4. If any other character is encountered, return a suitable error code to function main 5. Declare the error codes using #define 6. If the name contains valid characters then return a success code to function main 7. Depending on the return value display Valid name or Invalid name 3. Write a program to count the Vowels in a given string using pointers. 4. Write a program to accept two strings and to count the common characters present in the strings using a function. The function should receive a pointer to these strings and should return
the count of common characters. (Example: If the strings were Infosys and Microsoft then the count will be 4. It should be made case insensitive) 5. Write a program to automatically generate the telephone numbers. The requirements are as follows: Declare a character array to hold a 7-digit telephone number Accept the telephone number as a string. The first four digits is the department code and the last three digits is the telephone number. (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. (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. (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. Display the telephone number
6. Write a program to create a structure to store the date of birth of a person. Problem Description: Create a structure called with three short int members namely day, 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. Write a program to Validate the date of birth of a person. Problem Description: As described in Assignment-6, 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. 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: year 2000 is a leap year not only because it is divisible by 4 but it is also divisible by 400. Year 1900 is not a leap year even though it is divisible by 4. 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
8. Write a program to arrange the department codes of N departments in descending order using selection sort. 9. Write a program to arrange the telephone extension numbers of N employees in the ascending order using insertion sort. 10. Write a program to search for an employee id in an array containing N employee Ids using binary search. 11. Admission to a professional course is subject to the following conditions: a. Marks in mathematics >= 60 b. Marks in physics >= 50 c. Marks in chemistry >= 40 d. Total in all three subjects >= 200 or Total in mathematics and physics >= 150 Given the marks in three subjects, Write a program to process the applications to list the eligible candidates. Assume the total number of applications to process is n. 12. Write a program to extract a portion of a character string and print the extracted string. Assume that m characters are extracted, starting with the nth character. Note : Use built in functions wherever possible. 13. Define a structure called cricket that will describe the following information: Player name, team name, 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. 14. Using pointers, Write a program that receives a character string and a character as argument. Perform the following: a. A function to Count the occurrences of the given character in the character string b. A function to delete all occurrences of this character in the character string. It should display the corrected string with no blank spaces. 15. 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. The day names should be kept in a static table of character strings local to the function.
Example: if the day is 10, then the month should be displayed as October. If the value of the day exceeds 12, appropriate Error messages should be displayed.
Day-3 Assignments
Assignment 1: Identifying Test cases using Boundary Value analysis
Objective: To identify and document test cases for a given functionality, using Boundary value Analysis. Problem Description: Consider the function below whose functionality is described in its documentation. /****************************************************************** * Function: fnComputeRateOfInterest * Description: Given the Amount in Rs., computes and returns * the interest rate. Minimum Amount is Rs.5000 and * maximum Amount is 30000. * * Criteria for Interest: * Rs. 5000 to 10000 5% * Rs. 10001 to 15000 7% * Rs. 150001 to 20000 9% * Rs. 200001 to 25000 11% * Rs. 250001 to 30000 15% * PARAMETERS: * int iAmount Amount * * RETURNS: Appropriate Rate of Interest. -1.0 in case of error. ******************************************************************/ float fnComputeRateOfInterest (int iAmount) { ... ... }
Step 1: Create an Excel sheet with the columns shown below. Sl No Test case name Test Procedure Precondition Expected Result Reference to Detailed Design /
Spec Document
Step 2: Identify the test cases based on boundary value analysis. Step 3: Document them in the Excel sheet created earlier.
Submit
Submit
#define ERROR_INSUFFICIENT_BALANCE
/******************************************************************************* * Structure: book * Description: Stores book details* * Member Variables: * acAuthor - Name of the author (Range: 20 characters)
* *
acTitle - Title of the book (Range: 30 characters) fPrice - Price of the book
*******************************************************************************/ struct book { char acAuthor[20]; char acTitle[30]; float fPrice; struct { char acMonth[10]; int iYear; } date; char acPublisher[10]; int iQuantity; }; /* Forward declarations of functions*/ int fnLook_Up (struct book sBook[], char[], char[],int); void fnGetString(char []); int atoi(char[]); /******************************************************************************* * Function: main()
* Description: A code to search for a book in the Inventory. * * * When a customer requires a book, that book is searched in the library. if the book is available, then the number of copies is requested from the user and the total cost is displayed. If the requested number of copies
* Input Parameters: * * int argc - Number of command line arguments char **argv The command line arguments passed 0 on success to the operating system
* Returns:
*******************************************************************************/ int main (int argc, char** argv) { /* Declare an instance of bookdetails */ char title[30], author[20]; int iIndex, iNo_of_Books; int iquantity; char acResponse[10], quantity[10]; static struct book sbook[] = { {"Ritche", "C Language", 90.00, "May", 1977, "PHI",10}, {"Herbert", "Programming in Java",150.00, "July",1983,"Hayden", 5}, {"B V Kumar","Web Services",180.00,"january",1984,"TMH",10}, {"Sierra Bates", "SCJP", 250,"October",1995, "DreamTech", 0} }; iNo_of_Books = sizeof(sbook) / sizeof(struct book); do { printf("Enter title and author name \n"); printf("\n Title: fnGetString(title); printf("Author: "); ");
fnGetString(author); iIndex = fnLook_Up(sbook, title,author,iNo_of_Books); if (iIndex != -1) /* Book found */ { printf("\n%s%s%.2f %s%d%s\n\n", sbook[iIndex].acAuthor, sbook[iIndex].acTitle, sbook[iIndex].fPrice, sbook[iIndex].date.acMonth, sbook[iIndex].date.iYear, sbook[iIndex].acPublisher ); printf("Enter number of copies:"); fnGetString(quantity); iquantity = atoi(quantity); if (iquantity < sbook[iIndex].iQuantity) printf("Cost of %d copies = %.2f\n", iquantity, sbook[iIndex].fPrice * iquantity); else printf("\nRequired copies not in stock\n\n"); } else printf("\nBook not in list\n\n"); printf("\nDo you want ay other book? (YES/NO):"); fnGetString(acResponse); }
while(acResponse[0] ='Y' || acResponse[0] == 'y'); printf("\n\nThank you. Good Bye\n"); return 0; } /******************************************************************************* * Function: fnGetString
* Description: Gets the character input from the User * Input Parameters: * * * Returns: nothing char string[] - String which has to be input
*******************************************************************************/ void fnGetString (char acstring[]) { char c; int i = 0; do { c = getchar(); acstring[i++] = c; } while (c != '\n'); acstring[i-1] = '\0'; } /******************************************************************************* * Function: fnLook_Up
* Description: A function which searches for the book in the list * Input Parameters: * * * * * Returns: * * * *******************************************************************************/ int fnLook_Up(struct book sbook[], char actitle[], char acauthor[], int iTotal_No_Of_Books) { /* Declaration for account number and amount */ int i; for (i=0; i < iTotal_No_Of_Books; i++) if (strcmp(actitle, sbook[i].acTitle) == 0 || strcmp(acauthor, sbook[i].acAuthor) == 0) return (i); /* book found */ return(-1); } Step 2: Compile & Execute the source code. There are no errors or warnings in the source code. Step 3: The code has to be reviewed based on the checklist. Refer to the list of checklist in the course material. Step 4: Write the Review comments in the Review_Comments.xls file as follows: /* book not found */ Serial Number on success, -1 when the book is not found book sbook - A variable is declared as type struct book
char actitle[] - which receives the title char acauthor[] - which receives the author name int iTotal_No_Of_Books - which receives the total number of books in the list
Sl No 1
Line # 3
Comment Description of C file does not reflect what the code is meant for.
Step 5: Incorporate the Review comments in the source code and now execute the code.