CSC 138 Structured Programming CHAPTER 3: RECORDS (STRUCT) [PART 1]

Size: px
Start display at page:

Download "CSC 138 Structured Programming CHAPTER 3: RECORDS (STRUCT) [PART 1]"

Transcription

1 CSC 138 Structured Programming CHAPTER 3: RECORDS (STRUCT) [PART 1]

2 LEARNING OBJECTIVES Upon completion, you should be able to: o define records (structures) that contain array data type as one of the member. o declare and initialize C++ record (struct) as an array. o differentiate between array and record (struct). o write program using array and function in record (struct).

3 RECORD OVERVIEW 3.1 RECORDS DEFINITION 3.2 RECORDS DECLARATION 3.3 RECORDS INITIALIZATION 3.4 ACCESSING RECORDS MEMBERS 3.5 RECORDS ASSIGNMENT 3.6 AGGREGATE OPERATIONS WITH STRUCT

4 CHAPTER 3 RECORDS / STRUCT DEFINITION DECLARATION INITIALIZATION ACCESSING RECORD MEMBERS RECORD ASSIGNMENT AGGREGATE OPERATIONS WITH STRUCT

5 RECORD INTRODUCTION o Assume that we want to store the following students information: name Ic number Matric number Year entry o Below are the example of data representation that might be used: char Name[15], ICno[15], MatricNo[7]; int YearEntry; o We cannot use an array to group all of the items associated with a student. How to group elements of different types together?

6 RECORD INTRODUCTION o An array is a homogeneous data structure; a struct is typically a heterogeneous data structure. o A collection of fixed number of components in which components are accessed by name. The components may be of different types. o Allowed a group of related data being accessed and manipulate as a unit(record) struct o For example, data associated with student are: Name IcNo MatricNo YearEntry - string 15 characters - string 15 characters/array - string 7 characters - integer

7 RECORD DEFINITION o struct: collection of a fixed number of components (members), accessed by name Members may be of different types o Syntax:

8 RECORD DECLARATION o A struct is a definition, not a declaration OR struct studenttype { string firstname; string lastname; char coursegrade; int testscore; int programmingscore; double GPA; //variable declaration } newstudent, student; C++ Programming: From Problem Analysis to Program Design, Fourth Edition 8

9 RECORD DECLARATION C++ Programming: From Problem Analysis to Program Design, Fourth Edition 9

10 o Initialization can be done during declaration. o Example 1: o Example 2: RECORD INITIALIZATION struct student stud1 = { Nadiah, , A11000, 1998}; struct date { int day; int month; int year; } struct date Birth_Day = {1, 1, 1982}; Birth_Day 1 1 day month 1982 year Company Logo CSC 138 Structured programming

11 RECORD INITIALIZATION o Example 3: struct date Birth_Day = {31, 10, 1966}; day month year Birth_Day Company Logo CSC 138 Structured programming

12 ACCESSING RECORDS MEMBERS o The syntax for accessing a struct member is: o The dot (.) is an operator, called the member access operator C++ Programming: From Problem Analysis to Program Design, Fourth Edition 12

13 ACCESSING RECORDS MEMBERS o To initialize the members of newstudent: newstudent.gpa = 0.0; newstudent.firstname = "John"; newstudent.lastname = "Brown"; C++ Programming: From Problem Analysis to Program Design, Fourth Edition 13

14 ACCESSING RECORDS MEMBERS More examples: cin>>newstudent.firstname; cin>>newstudent.testscore>>newstudent.programmingscore; Score=(newStudent.testScore + newstudent.programmingscore) / 2; if (score >= 90) newstudent.coursegrade = 'A'; else if (score >= 80) newstudent.coursegrade = 'B'; else if (score >= 70) newstudent.coursegrade = 'C'; else if (score >= 60) newstudent.coursegrade = 'D'; else newstudent.coursegrade = 'F'; C++ Programming: From Problem Analysis to Program Design, Fourth Edition 14

15 ACCESSING RECORDS MEMBERS o Example 3: struct student S1; strcpy(s1.name, "C Bin D"); strcpy(s1.icno, " "); strcpy(s1.matricno, "A11122"); S1.YearEntry = 1990; S1 Name IcNo MatricNo YearEntry 'C'' ' 'B''i' 'n' ' ''D'\0' '6' '6''1''1''2''2' '-' '0''2' '-' '5' '5' '5''4''\0' 'A''1''1''1''2''2''\0' 1990 CSC 138 Structured programming

16 ACCESSING RECORDS MEMBERS o Example 4: struct date Birth_Day; cout<< When is your birthday?(dd MM YYYY)\n"; cin>>birth_day.day>>birth_day.month>> Birth_Day.year; cout<< Your birthday is << Birth_Day.day<< / <<Birth_Day.month<< / << Birth_Day.year<<endl; day month year????????? Company Logo Birth_Day CSC 138 Structured programming

17 o Example ACCESSING RECORDS MEMBERS struct stud S1; cout<<"name, Ic no, Matric no, year?\n"); gets(s1.name); //also act as input data for char [cin] gets(s1.icno); //needs to include stdio.h in using gets()& puts() gets(s1.matricno); cin>>s1.yearentry; puts(s1.name); // also act as display data for char [cout] Company Logo S1 Name IcNo MatricNo YearEntry???????????????????????????????????????? CSC 138 Structured programming

18 RECORD ASSIGNMENT o Value of one struct variable can be assigned to another struct variable of the same type using an assignment statement o The statement: student = newstudent; copies the contents of newstudent into student C++ Programming: From Problem Analysis to Program Design, Fourth Edition 18

19 RECORD ASSIGNMENT o The assignment statement: student = newstudent; is equivalent to the following statements: student.firstname = newstudent.firstname; student.lastname = newstudent.lastname; student.coursegrade = newstudent.coursegrade; student.testscore = newstudent.testscore; student.programmingscore = newstudent.programmingscore; student.gpa = newstudent.gpa; C++ Programming: From Problem Analysis to Program Design, Fourth Edition 19

20 AGGREGATE OPERATIONS WITH STRUCTURES o Recall that arrays had none (except reference parameter) o Structures DO have aggregate operators assignment statement = parameter (value or reference) return a structure as a function type 20

21 AGGREGATE OPERATIONS WITH STRUCTURES o Limitations on aggregate operations no I/O no arithmetic operations cout << old_part; cin >> new_part; no comparisons old_part = new_part + old_part; if (old_part < new_part) cout <<...; 21

22 COMPARISON (RELATIONAL OPERATORS) o Compare struct variables member-wise No aggregate relational operations allowed o To compare the values of student and newstudent: C++ Programming: From Problem Analysis to Program Design, Fourth Edition 22

23 INPUT/OUTPUT o No aggregate input/output operations on a struct variable o Data in a struct variable must be read one member at a time o The contents of a struct variable must be written one member at a time C++ Programming: From Problem Analysis to Program Design, Fourth Edition 23

24 ARRAYS VERSUS STRUCTS C++ Programming: From Problem Analysis to Program Design, Fourth Edition 24

25 Exercise 1 1. Define a struct, checkingaccount, to store the following data about a checking account; account holder s name(string), account number (int), balance (double), and interest rate (double). 2. Define a struct, movietype, to store the following data about a movie: movie name(string), movie director(string), producer (string), the year movie was released (int),and number of copies in stock. C++ Programming: From Problem Analysis to Program Design, Fourth Edition 25

26 Exercise 2 Assume the definition of Exercise 1 1. Declare a checkingaccount variable and write C++ statements to store the following information: account holder s name Jason Miller, account number , balance , interest rate -2.5%. 2. Declare a variable of type movietype to store the following data: movie name Summer Vacation, director Tom Blair, producer Rajiv Merchant, year the movie released 2005, the number of copies in stock 34 C++ Programming: From Problem Analysis to Program Design, Fourth Edition 26

27 Exercise 3 a) Write a C++ statement for each of the following questions: i. Define a struct named Student_Information which has four members of different types. The members are student name, gender( F or M ), semester and CGPA. C++ Programming: From Problem Analysis to Program Design, Fourth Edition 27

28 Exercise 4 a) Consider the following statements: Struct nametype { }; string first; string last; double score; nametype name; nametype name2; Mark the following statements as valid or invalid. If statement is invalid explain why. i. name.first = Nafisah ; ii. iii. iv. cout<< nametype; name2= name; cin >> nametype; v. cout<< name2. last; vi. vii. nametype.last = Amin ; double total = score; viii. double average; average= name2.score /2; C++ Programming: From Problem Analysis to Program Design, Fourth Edition 28

29 Mark the following statements as valid or invalid based on the struct definition below: struct booktype { char authorname[30]; float price; char edition[15]; int yearpublished; char publisher[50]; }book1, book2; a) book1.price=50.00; b) book1.publisher[30]; c) book2==book1; Exercise 5 d) if (strcmp(book1.edition,book2.edition)==0) e) strcpy(book2.publisher, Pearson );

30 Exercise 6 a) Define a struct named Course with 3 members: coursename, coursecode and coursefee. Declare 2 struct variables namely course1 and course2. b) A company has six salespersons. Every month they go on road trips to sell the company s product. At the end of each month, the total sales for each salesperson, together with that salesperson s ID and month is recorded. Write an appropriate struct definition for this problem.

31 Exercise 7 Given the following struct definition: struct booktype { char authorname[30]; float price; char edition[15]; int yearpublished; char publisher[50]; }book1, book2; write a C++ statement for each of the following: a) Set the value of yearpublished for book2 to b) Set the price of book2 equal to the price of book1. c) Set the value of authorname for book2 as D.S. Malik.

32 CSC 138 Structured Programming CHAPTER 3: RECORDS (STRUCT) [PART 2]

33 RECORD OVERVIEW 3.7 RECORDS AND ARRAY 3.8 RECORDS AND FUNCTION

34 CHAPTER 3 RECORDS AND ARRAY ARRAY IN RECORD RECORDS IN ARRAY

35 ARRAY IN RECORD (STRUCT) o Example 1: const int arraysize = 500; struct listtype { //array in struct int elements[arraysize]; int listlength; }; Memory: listone elements elements[0] elements[1]... elements[499] listlength listtype listone; //declared a struct variable

36 ARRAY IN RECORD (STRUCT) o Example 1: listone.listlength = 0; listone.elements[0] = 11; listone.listlength++; Memory: listone elements elements[0] elements[1]... elements[499] listone.elements[1] = 22; listlength 0 listone.listlength++;

37 ARRAY IN RECORD (STRUCT) o Example 1: listone.listlength = 0; listone.elements[0] = 11; listone.listlength++; Memory: listone elements elements[0] elements[1]... elements[499] 11 listone.elements[1] = 22; listlength 0 listone.listlength++;

38 ARRAY IN RECORD (STRUCT) o Example 1: listone.listlength = 0; listone.elements[0] = 11; listone.listlength++; Memory: listone elements elements[0] elements[1]... elements[499] 11 listone.elements[1] = 22; listlength 0 1 listone.listlength++;

39 ARRAY IN RECORD (STRUCT) o Example 1: listone.listlength = 0; listone.elements[0] = 11; listone.listlength++; Memory: listone elements elements[0] elements[1]... elements[499] listone.elements[1] = 22; listlength 1 listone.listlength++;

40 ARRAY IN RECORD (STRUCT) o Example 1: listone.listlength = 0; listone.elements[0] = 11; listone.listlength++; Memory: listone elements elements[0] elements[1]... elements[499] listone.elements[1] = 22; listlength 1 2 listone.listlength++;

41 ARRAY IN RECORD (STRUCT) o Example 1 (Complete Program): const int arraysize = 500; struct listtype { int elements[arraysize]; //array in struct int listlength; }; int main(){ listtype listone; //Declares a struct variable cout << "Enter number of element(s): "; cin >> listone.listlength; for(int i = 0; i < listone.listlength; i++) listone.elements[i] = (i+1); } for(int i = 0; i < listone.listlength; i++) cout << listone.elements[i] << endl;

42 ARRAY IN RECORD (STRUCT) o Example 2 (struct definition & variable declaration): struct studenttype { string studname; char coursegrade; int testscore[2]; int asgnscore; double GPA; }; studenttype student; Memory: student studname coursegrade testscore [0] testscore [1] asgnscore GPA

43 ARRAY IN RECORD (STRUCT) o Example 2 (variable declaration & initialization): studenttype student = { Jamaluddin, A, 90, 87, 85, 3.85 }; Memory: student studname coursegrade testscore [1] asgnscore GPA Jamaluddin A testscore [0]

44 ARRAY IN RECORD (STRUCT) o Example 2 (main function): int main() { studenttype student = { Jamaluddin, A, 90, 87, 85, 3.85 }; //Assignment statement: Method 1 studenttype newstudent; //Assignment statement: Method 2 for(int i = 0; i < 2; i++) newstudent.studname = student.studname; newstudent.coursegrade = student.coursegrade; newstudent.testscore[i] = student.testscore[i]; newstudent.asgnscore = student.asgnscore; newstudent.gpa = student.gpa;

45 ARRAY IN RECORD (STRUCT) o Example 2 (main function cont.):... cout << " STUDENT'S INFORMATION" << endl; } cout << " NAME\t: " << student.studname[0] << " " << student.studname[1]; cout << "\n GPA\t: " << student.gpa; cout << "\n COURSE GRADE : " << student.coursegrade; cout << "\n\n ASSIGNMENT SCORE\t: " << student.asgnscore; cout << "\n TEST SCORE\t\t: [1] " << student.testscore[0] << " [2] " << student.testscore[1];

46 o Example 2 (Output): ARRAY IN RECORD (STRUCT)

47 EXERCISE (3.2.1) Extends the codes from previous program in Example 1 to: 1. display the elements of the array in reverse order. 2. display the odd elements of the array.

48 ANSWER (3.2.1) const int arraysize = 500; struct listtype { }; int elements[arraysize]; //array in struct int listlength; main(){ : //Display elements in reverse order for(int i = (listone.listlength - 1); i >= 0; i--) cout << listone.listelement[i] << endl; } //Display odd elements for(int i = 0; i < listone.listlength; i++) if(listone.listelement[i] % 2!= 0) cout << listone.listelement[i] << endl;

49 RECORDS (STRUCT) IN ARRAY o Suppose a company has 50 employees. The employer need to print the employees monthly paychecks and keep track of how much money has been paid to each employee. o Step 1 : Define struct const int noofemployee = 50; struct employeetype { char name[50], deptid[15], employeeid[15]; int hourworked; double basicsalary, monthlysalary; }; name deptid employeeid hourworked basicsalary monthlysalary

50 RECORDS (STRUCT) IN ARRAY o Step 2 : Declare an array of struct variable employeetype employees[noofemployee]; Declares an array employees with 50 components of type employeetype. Every elements is a struct. Memory: employees[0] name deptid employeeid hourworked basicsalary monthlysalary Memory: employees[1] name deptid employeeid hourworked basicsalary monthlysalary Memory: employees[49] name deptid employeeid hourworked basicsalary monthlysalary

51 RECORDS (STRUCT) IN ARRAY o Step 3 : Input / Read data for each of the employees for(int x = 0; x < noofemployee; x++) { //Input statement //Calculate the monthly salary } Output screen:

52 RECORDS (STRUCT) IN ARRAY //Input statement cout << " Employee " << x+1 << endl; cout << " \n"; cout << " Name : "; cin.getline(employees[x].name, 50); cout << " Department : "; cin.getline(employees[x].deptid,15); cout << " Employee ID : "; cin.getline(employees[x].employeeid,15); cout << " Hours Worked : "; cin >> employees[x].hourworked; cout << " Basic Salary : RM "; cin >> employees[x].basicsalary; //Calculate the monthly salary employees[x].monthlysalary = employees[x].hourworked * employees[x].basicsalary; cout << endl;

53 RECORDS (STRUCT) IN ARRAY o Step 4 : Access elements of the array, elements of the struct //print all the name for each employees for(int x = 0; x < noofemployee; x++) cout << employees[x].name; //print all the employeeid for(int x = 0; x < noofemployee; x++) cout << employees[x].employeeid;

54 RECORDS (STRUCT) IN ARRAY //Display the record for each employee cout << setw(10) << "EMPLOYEE ID" << setw(20) << "BASIC SALARY (RM)" << setw(25) << "MONTHLY SALARY (RM)" << endl; cout << setfill('-') << setw(55) << endl; cout << setfill(' '); } for(int i = 0; i < noofemployee; i++) { cout << setw(8) << employees[i].employeeid; cout << setw(16) << employees[i].basicsalary; cout << setw(16) << employees[i].monthlysalary; cout << endl; } system("pause");

55 EXERCISE (3.2.2) Extends the codes from previous program to: 1. search employee record by their employee ID. 2. display the particular details as the following output screen:

56 ANSWER (3.2.2) main() { employeetype employees[noofemployee]; char searchid[15]; cout << "\n Enter Employee ID to be searched: "; cin >> searchid; for(int i = 0; i < noofemployee; i++) { if(strcmp(employees[i].employeeid, searchid) == 0) { //Display the record for the employee cout << endl << setw(10) << " EMPLOYEE ID" << setw(15) << "EMPLOYEE NAME" << setw(25) << "DEPARTMENT" << endl; cout << " " << endl; cout << setfill(' '); cout << setw(10) << employees[i].employeeid; cout << setw(15) << employees[i].name; cout << setw(25) << employees[i].deptid; cout << endl; } else cout << " Record doesn't exist!";} }

57 EXERCISE (3.2.3) Suppose FSKM has 5 students. We need to calculate the total score obtained by each student. The total score is by adding the mark of test score and programming score. From the total score, find the course grade of each student. Lastly, display all information of all students. struct studenttype { string firstname; string lastname; char coursegrade; int testscore; int programmingscore; double GPA; int score; } ; studenttype student[5];

58 EXERCISE (3.2.4) Suppose a company has 10 full-time employed. We need to print their monthly paychecks and keep track of how much money has been paid to each employee in the year-to-date. First, let s define an employee s record: Input : firstname, lastname, personid, deptid, yearlysalary, monthlybonus struct employeetype { string firstname, lastname; string deptid; int personid; double yearlysalary; double monthlysalary; double yeartodatepaid; double monthlybonus; } ; employeetype employee[10];

59 ANSWER (3.2.3) int main() { for(int i=0; i<5; i++) { cout<<"insert first name : "; cin>>student[i].firstname; cout<<"insert last name : "; cin>>student[i].lastname; cout<<"insert test score : "; cin>>student[i].testscore; cout<<"insert programming score : "; cin>>student[i].programmingscore; cout<<"insert GPA : "; cin>>student[i].gpa; } } for(int i=0; i<5; i++) { student[i].score = student[i].testscore+student[i].programmingscore; if(student[i].score >=90) student[i].coursegrade='a'; else if(student[i].score >=80 && student[i].score<90) student[i].coursegrade='b'; else if(student[i].score >=70 && student[i].score<80) student[i].coursegrade='c'; else if(student[i].score >=60 && student[i].score<70) student[i].coursegrade='d'; else student[i].coursegrade='f'; } for(int i=0; i<5; i++) { cout<<"first Name : <<student[i].firstname<<endl; cout<<"last Name : <<student[i].lastname<<endl; cout<<"course Grade : <<student[i].coursegrade<<endl; cout<<"test Score : <<student[i].testscore<<endl; cout<<"programming Score : <<student[i].programmingscore<<endl; cout<<" GPA : <<student[i].gpa<<endl; }

60 ANSWER (3.2.4) int main() { for(int i=0; i<10; i++) { cout << \ninsert first name : "; cin >> employee[i].firstname; cout << \ninsert last name : "; cin >> employee[i].lastname; cout << \ninsert id : "; cin >> employee[i].personid; cout << \ninsert dept id : "; cin >> employee[i].deptid; cout << \ninsert yearly salary: "; cin >> employee[i].yearlysalary; cout << \ninsert monthly bonus: "; cin >> employee[i].monthlybonus; } for(int i=0; i<10; i++) { employee[i].monthlysalary = employee[i].yearlysalary / 12; double paycheck = employee[i].monthlysalary + employee[i].monthlybonus; employee[i].yeartodatepaid = paycheck; cout << "Year To Date Paid : <<employee[i].yeartodatepaid << endl; } }

61 RECORD OVERVIEW 3.7 RECORDS AND ARRAY 3.8 RECORDS AND FUNCTION

62 CHAPTER 3 RECORDS AND FUNCTION PASS RECORD VARIABLE AS PARAMETER PASS RECORD MEMBER AS PARAMETER PASS ARRAY OF RECORDS AS PARAMETER RETURN RECORDS

63 PASS RECORD VARIABLE AS PARAMETER o Recall the difference between array and struct involving aggregate operation: AGGREGATE OPERATION ARRAY STRUCT Arithmetic No No Assignment No Yes Input / Output No (except strings) No Comparison No No Parameter passing By reference only By value or reference Function returning a value No Yes

64 PASS RECORD VARIABLE AS PARAMETER o The following struct definition were given: struct studenttype { char name[25]; char matrixno[15]; int icno; }; name matrixno icno

65 PASS RECORD VARIABLE AS o Construct main function: PARAMETER main() { studenttype s;//struct variable declaration cout << Enter Matrix No.: ; cin.getline(s.matrixno, 15); cout << Enter Name: cin.getline(s.name, 25); cout << Enter IC No.: ; cin >> s.icno; } display(s) //function call

66 PASS RECORD VARIABLE AS PARAMETER (Pass entire struct) o Construct function prototype: void display(studenttype); o Construct function definition: Pass entire struct at once void display(studenttype x) { cout << x.name << << x.matrixno << << x.icno; } Member s name CANNOT BE RENAMED! But the arrangement of variable CAN BE MODIFIED.

67 PASS RECORD VARIABLE AS PARAMETER (Pass address of struct) o Construct function prototype: void display(studenttype&); o Construct function definition: Pass only the address of struct void display(studenttype& x) { cout << x.name << << x.matrixno << << x.icno; } Member s name CANNOT BE RENAMED! But the arrangement of variable CAN BE MODIFIED.

68 PASS RECORD MEMBERS AS PARAMETER o The following struct definition were given: struct studenttype { char name[25]; char matrixno[15]; int icno; }; name matrixno icno

69 o Construct main function: PASS RECORD MEMBERS AS PARAMETER main() { studenttype s; //struct variable declaration cout << Enter Matrix No.: ; cin.getline(s.matrixno, 15); cout << Enter Name: cin.getline(s.name, 25); cout << Enter IC No.: ; cin >> s.icno; } //function call display( s.matrixno, s.name, s.icno ) Pass members of struct individually

70 PASS RECORD MEMBERS AS PARAMETER o Construct function prototype: void display(char[], char[], int); o Construct function definition: Pass only the members of STRUCT individually void display(char matrix[], char name[], int ic) { cout << matrix << << name << } << ic; Member s name CAN BE RENAMED! But the arrangement of variables CANNOT BE MODIFIED

71 PASS ARRAY OF RECORDS AS PARAMETER o The following struct definition were given: struct studenttype { char name[25]; char matrixno[15]; int icno; }; name matrixno icno

72 o Main function: PASS ARRAY OF RECORDS AS PARAMETER main() { int arraysize = 10; studenttype s[arraysize]; getdata(s, arraysize); //function call } for(int i = 0; i < arraysize; i++) { cout << s[i].name << << s[i].matrixno << << s[i].icno; } Member s name CANNOT BE RENAMED! But the arrangement of variables CAN BE MODIFIED

73 o Function prototype: PASS ARRAY OF RECORDS AS void getdata(studenttype[]); PARAMETER Pass the array of struct o Function definition: void getdata(studenttype s[], int size) { for(int i = 0; i < size; i++) { cout << Enter Matrix No. and Name ; cin.getline(s[i].matrixno, 15); cin.getline(s[i].name, 25); cout << Enter IC No.: ; cin >> s[i].icno; } }

74 RETURN RECORD (By parameter) o The following struct definition were given: struct studenttype { char name[25]; char matrixno[15]; int icno; }; name matrixno icno

75 RETURN RECORD (By parameter) o Function prototype: void getdata(studenttype&); Pass the address of struct, by reference o Function definition: void getdata(studenttype& x) { cout << Enter Matrix No.: ; cin.getline(x.matrixno, 15); cout << Enter Name: cin.getline(x.name, 25); cout << Enter IC No.: ; cin >> x.icno; }

76 o Main function: RETURN RECORD (By parameter) main() { studenttype s;//struct variable declaration getdata(s) //function call } cout << s.name << << s.matrixno << << s.icno; Member s name CANNOT BE RENAMED! But the arrangement of variables CAN BE MODIFIED

77 RETURN RECORD (By return value) o The following struct definition were given: struct studenttype { char name[25]; char matrixno[15]; int icno; }; name matrixno icno

78 RETURN RECORD (By return value) o Function prototype: studenttype getdata(); o Function definition: studenttype getdata() { studenttype s; Pass the type of struct cout << Enter Matrix No. and Name ; cin.getline(s.matrixno, 15); cin.getline(s.name, 25); cout << Enter IC No.: ; cin >> s.icno; } return s;

79 RETURN RECORD (By return value) o Main function: main() { studenttype s;//struct variable declaration s = getdata() //function call } cout << s.name << << s.matrixno << << s.icno; Member s name CANNOT BE RENAMED! But the arrangement of variables CAN BE MODIFIED

80 EXERCISE (3.2.5) o Suppose that you have the following definitions: struct tourtype { char cityname[20]; int distance, hour, sec; double min; }; i. Declare the variable named destination of type tourtype. ii. Write C++ statements to store the following data in destination: cityname - chicago, distance miles, traveltime - 9 hours and 30 minutes. iii. iv. Write the definition of a function to output the data stored in a variable of type tourtype. Write the definition of value returning function that input data into a variable of type tourtype. v. Write the definition of void function with reference parameter of type tourtype to input data in a variable of type tourtype.

81 EXERCISE (3.2.6) o The following struct definition consists of four data members: book s title, serial number, price and shelf location. struct Books { char title[50]; int serialno; float price; char location[20]; }; a) Create an array of 100 malay books b) Write the function definition for each of the following i. Function inputdata(): This function receives two parameters; an array of malay books and the size of the array. It then reads data from the user and stores them into the array. ii. Function preciousbook(): this function receives two parameters; an array of malay books and the size of the array. It determines the most expensive book and displays all the information about the book.

82 EXERCISE (3.2.7) A bookshop wants to manage the information of the books sold in their shop. You have been assigned to develop the program to update the books information. The information stored consists of the titles, quantities and prices of books. The title, quantity and price of book are stored in a structure named bookstock. Assuming that there are FIVE HUNDRED (500) books managed by the bookshop. Write definition for the following functions. Note : function parameter must at least have an array of type bookstock. o o o o InputData() : this function prompts user to enter book information and stores them in array of type bookstock. totalprice(): this function calculates total price by summing up multiplication result of quantities and prices. It will then return the result. displayrestock(): this function displays the details of restocked book by finding its quantity which is less than FIVE (5) books. searchtitle(): this function searches book title and display the book details. If the title is not found, display appropriate message. Searched book title is received through this function parameter.

83 RECORD OVERVIEW 3.7 RECORDS AND ARRAY 3.8 RECORDS AND FUNCTION

84 #include <iostream> #include <cstring> #include <conio.h> EXAMPLE 1 OF STRUCT WITH FUNCTION void printbook( struct Books book ); struct Books { char title[50]; char author[50]; char subject[100]; int book_id; }; int main( ) { struct Books Book1; struct Books Book2; // Declare Book1 of type Book // Declare Book2 of type Book strcpy( Book1.title, "Learn C++ Programming"); // book 1 specification strcpy( Book1.author, "Chand Miyan"); strcpy( Book1.subject, "C++ Programming"); Book1.book_id = ;

85 EXAMPLE 1 OF STRUCT WITH FUNCTION strcpy( Book2.title, "Telecom Billing"); // book 2 specification strcpy( Book2.author, "Yakit Singha"); strcpy( Book2.subject, "Telecom"); Book2.book_id = ; printbook( Book1 ); // Print Book1 info printbook( Book2 ); // Print Book2 info getch(); } void printbook( struct Books book ) { cout << "Book title : " << book.title <<endl; cout << "Book author : " << book.author <<endl; cout << "Book subject : " << book.subject <<endl; cout << "Book id : " << book.book_id <<endl; }

86 EXAMPLE 2 OF STRUCT WITH FUNCTION #include <iostream.h> #include <conio.h> #include <stdio.h> #include <cstring.h> void display_details (struct person Someone_I_know); //function prototype //declaraton of struct struct person { char name [30]; int eye_colour; float height; }; int main() { struct person sibling, mother; struct person spouse; //initialization for person : sibling, mother and spouse strcpy(sibling.name, "Diane"); sibling.eye_colour = 1; sibling.height = 1.61;

87 EXAMPLE 2 OF STRUCT WITH FUNCTION strcpy(mother.name,"mary"); mother.eye_colour = 2; mother.height = 1.44; strcpy(spouse.name,"helen"); spouse.eye_colour = 1; spouse.height = 1.7; display_details(sibling); //function call display_details(mother); display_details(spouse); getch(); } void display_details (struct person someone_i_know) { cout << "Name : " << someone_i_know.name <<endl; cout << "Eye colour : "; switch (someone_i_know.eye_colour) { case 1 : cout << "Brown"; break; case 2 : cout << "Blue"; break; case 3 : cout <<"Green"; break; default : cout << "Unknown"; } cout << endl; cout << "Height : " << someone_i_know.height << " metres" << endl; }

88 CSC 138 Structured Programming THE END..

Lecture 6 Records (structs)

Lecture 6 Records (structs) Lecture 6 Records (structs) In this Lecture, you will: Learn about records (structs) Examine various operations on a struct Explore ways to manipulate data using a struct Learn about the relationship between

More information

C++ Programming: From Problem Analysis to Program Design, Third Edition. Chapter 11: Records (structs)

C++ Programming: From Problem Analysis to Program Design, Third Edition. Chapter 11: Records (structs) C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 11: Records (structs) Objectives In this chapter you will: Learn about records (structs) Examine various operations on a

More information

C++ Programming: From Problem Analysis to Program Design, Third Edition

C++ Programming: From Problem Analysis to Program Design, Third Edition C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 11: Records (structs) Records (structs) struct: collection of a fixed number of components, accessed by name Components may

More information

C++ Programming: From Problem Analysis to Program Design, Fifth Edition. Chapter 11: Records (structs)

C++ Programming: From Problem Analysis to Program Design, Fifth Edition. Chapter 11: Records (structs) C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 11: Records (structs) Objectives In this chapter, you will: Learn about records (structs) Examine various operations on a

More information

Lecture 12 - Structures

Lecture 12 - Structures Lecture 12 - Structures 1 Outline Introduction Structure Definitions and Declarations Initializing Structures Operations on Structures Members Structures as Functions Parameters Array of Structures 2 Introduction

More information

cout << "How many numbers would you like to type? "; cin >> memsize; p = new int[memsize];

cout << How many numbers would you like to type? ; cin >> memsize; p = new int[memsize]; 1 C++ Dynamic Allocation Memory needs were determined before program execution by defining the variables needed. Sometime memory needs of a program can only be determined during runtime, or the memory

More information

Unit 8. Structures and Unions. School of Science and Technology INTRODUCTION

Unit 8. Structures and Unions. School of Science and Technology INTRODUCTION INTRODUCTION Structures and Unions Unit 8 In the previous unit 7 we have studied about C functions and their declarations, definitions, initializations. Also we have learned importance of local and global

More information

CSC 138 Structured Programming CHAPTER 4: TEXT FILE [PART 1]

CSC 138 Structured Programming CHAPTER 4: TEXT FILE [PART 1] CSC 138 Structured Programming CHAPTER 4: TEXT FILE [PART 1] LEARNING OBJECTIVES Upon completion, you should be able to: o define C++ text files o explain the benefits of using I/O file processing o explain

More information

Apllications. February 17, Indian Institute of Space Science and Technology. MA122 - Computer Programming and. Apllications. Structures.

Apllications. February 17, Indian Institute of Space Science and Technology. MA122 - Computer Programming and. Apllications. Structures. Indian Institute of Space Science Technology February 17, 2017 Lecture 14 1 2 3 Declaration 1 struct inflatable // structure declaration 2 { 3 char name[20]; 4 float volume; 5 double price; 6 }; ++ types

More information

CSC128 FUNDAMENTALS OF COMPUTER PROBLEM SOLVING Chapter 4: Repetition Control Structure

CSC128 FUNDAMENTALS OF COMPUTER PROBLEM SOLVING Chapter 4: Repetition Control Structure Learning Objectives At the end of this chapter, student should be able to: Understand the requirement of a loop Understand the Loop Control Variable () Use increment (++) and decrement ( ) operators Program

More information

CSC128 FUNDAMENTALS OF COMPUTER PROBLEM SOLVING Chapter 6: One Dimensional Array

CSC128 FUNDAMENTALS OF COMPUTER PROBLEM SOLVING Chapter 6: One Dimensional Array Lesson Outcomes At the end of this chapter, student should be able to: Define array Understand requirement of array Know how to access elements of an array Write program using array Know how to pass array

More information

Data Types (C/C++) Structures

Data Types (C/C++) Structures Data Types (C/C++) Scalar (or Basic) Data Types (atomic values) o Arithmetic types Integers short, int, long char, bool Floating points float, double, long double Composite (or Aggregate) Types: o Arrays:

More information

COMPUTER SCIENCE (083)

COMPUTER SCIENCE (083) Roll No. Code : 112011-083-A Please check that this question paper contains 7 questions and 6 printed pages. CLASS-XI COMPUTER SCIENCE (083) Time Allowed : 3 Hrs. Maximum Marks : 70 General Instructions

More information

6. User Defined Functions I

6. User Defined Functions I 6 User Defined Functions I Functions are like building blocks They are often called modules They can be put togetherhe to form a larger program Predefined Functions To use a predefined function in your

More information

conditional statements

conditional statements L E S S O N S E T 4 Conditional Statements PU RPOSE PROCE DU RE 1. To work with relational operators 2. To work with conditional statements 3. To learn and use nested if statements 4. To learn and use

More information

CAMBRIDGE SCHOOL, NOIDA ASSIGNMENT 1, TOPIC: C++ PROGRAMMING CLASS VIII, COMPUTER SCIENCE

CAMBRIDGE SCHOOL, NOIDA ASSIGNMENT 1, TOPIC: C++ PROGRAMMING CLASS VIII, COMPUTER SCIENCE CAMBRIDGE SCHOOL, NOIDA ASSIGNMENT 1, TOPIC: C++ PROGRAMMING CLASS VIII, COMPUTER SCIENCE a) Mention any 4 characteristic of the object car. Ans name, colour, model number, engine state, power b) What

More information

Chapter 8 Arrays and Strings. Objectives. Objectives (cont d.) Introduction. Arrays 12/23/2016. In this chapter, you will:

Chapter 8 Arrays and Strings. Objectives. Objectives (cont d.) Introduction. Arrays 12/23/2016. In this chapter, you will: Chapter 8 Arrays and Strings Objectives In this chapter, you will: Learn about arrays Declare and manipulate data into arrays Learn about array index out of bounds Learn about the restrictions on array

More information

PASCAL - RECORDS. To define a record type, you may use the type declaration statement. The record type is defined as

PASCAL - RECORDS. To define a record type, you may use the type declaration statement. The record type is defined as http://www.tutorialspoint.com/pascal/pascal_records.htm PASCAL - RECORDS Copyright tutorialspoint.com Pascal arrays allow you to define of iables that can hold several data items of the same kind but a

More information

Consider the following statements. string str1 = "ABCDEFGHIJKLM"; string str2; After the statement str2 = str1.substr(1,4); executes, the value of str2 is " ". Given the function prototype: float test(int,

More information

Classes and Data Abstraction. Topic 5

Classes and Data Abstraction. Topic 5 Classes and Data Abstraction Topic 5 Introduction Object-oriented programming (OOP) Encapsulates data (attributes) and functions (behavior) into packages called classes The data and functions of a class

More information

LAB 4.1 Relational Operators and the if Statement

LAB 4.1 Relational Operators and the if Statement LAB 4.1 Relational Operators and the if Statement // This program tests whether or not an initialized value of num2 // is equal to a value of num1 input by the user. int main( ) int num1, // num1 is not

More information

Superior University. Department of Electrical Engineering CS-115. Computing Fundamentals. Experiment No.7. User Defined Functions II

Superior University. Department of Electrical Engineering CS-115. Computing Fundamentals. Experiment No.7. User Defined Functions II Superior University Department of Electrical Engineering CS-115 Computing Fundamentals Experiment No.7 User Defined Functions II Prepared for By: Name: ID: Section: Semester: Total Marks: Obtained Marks:

More information

LAB 12 STRUCTURES School of Computer and Communication Engineering Universiti Malaysia Perlis

LAB 12 STRUCTURES School of Computer and Communication Engineering Universiti Malaysia Perlis LAB 12 STRUCTURES School of Computer and Communication Engineering Universiti Malaysia Perlis 1 1. OBJECTIVES: 1.1 To be able to define, declare and initialize structures. 1.2 To be able to access members

More information

CS242 COMPUTER PROGRAMMING

CS242 COMPUTER PROGRAMMING CS242 COMPUTER PROGRAMMING I.Safa a Alawneh Variables Outline 2 Data Type C++ Built-in Data Types o o o o bool Data Type char Data Type int Data Type Floating-Point Data Types Variable Declaration Initializing

More information

I SEMESTER EXAM : : XI :COMPUTER SCIENCE : MAX MARK a) What is the difference between Hardware and Software? Give one example for each.

I SEMESTER EXAM : : XI :COMPUTER SCIENCE : MAX MARK a) What is the difference between Hardware and Software? Give one example for each. I SEMESTER EXAM : : XI :COMPUTER SCIENCE : MAX MARK 70. a) What is the difference between Hardware and Software? Give one example for each. b) Give two differences between primary and secondary memory.

More information

Tutorial 13 Salary Survey Application: Introducing One- Dimensional Arrays

Tutorial 13 Salary Survey Application: Introducing One- Dimensional Arrays Tutorial 13 Salary Survey Application: Introducing One- Dimensional Arrays Outline 13.1 Test-Driving the Salary Survey Application 13.2 Introducing Arrays 13.3 Declaring and Initializing Arrays 13.4 Constructing

More information

Questions Bank. 14) State any four advantages of using flow-chart

Questions Bank. 14) State any four advantages of using flow-chart Questions Bank Sub:PIC(22228) Course Code:-EJ-2I ----------------------------------------------------------------------------------------------- Chapter:-1 (Overview of C Programming)(10 Marks) 1) State

More information

Tutorial Letter 103/1/2017 Introduction to Programming I

Tutorial Letter 103/1/2017 Introduction to Programming I COS1511/103/1/2017 Tutorial Letter 103/1/2017 Introduction to Programming I COS1511 Semester 1 School of Computing Examination Tutorial Letter Contents 1 INTRODUCTION... 2 2 EXAMINATION... 2 3 PAST EXAMINATION

More information

Programming. C++ Basics

Programming. C++ Basics Programming C++ Basics Introduction to C++ C is a programming language developed in the 1970s with the UNIX operating system C programs are efficient and portable across different hardware platforms C++

More information

Scheme G. Sample Test Paper-I. Course Name : Computer Engineering Group Course Code : CO/CD/CM/CW/IF Semester : Second Subject Tile : Programming in C

Scheme G. Sample Test Paper-I. Course Name : Computer Engineering Group Course Code : CO/CD/CM/CW/IF Semester : Second Subject Tile : Programming in C Sample Test Paper-I Marks : 25 Time:1 Hrs. Q1. Attempt any THREE 09 Marks a) State four relational operators with meaning. b) State the use of break statement. c) What is constant? Give any two examples.

More information

Chapter-14 STRUCTURES

Chapter-14 STRUCTURES Chapter-14 STRUCTURES Introduction: We have seen variables of simple data types, such as float, char, and int. Variables of such types represent one item of information: a height, an amount, a count, and

More information

Recognize the correct ordering of decisions in multiple branches Program simple and complex decision

Recognize the correct ordering of decisions in multiple branches Program simple and complex decision Lesson Outcomes At the end of this chapter, student should be able to: Use the relational operator (>, >=,

More information

Downloaded S. from Kiran, PGT (CS) KV, Malleswaram STRUCTURES. Downloaded from

Downloaded S. from Kiran,  PGT (CS) KV, Malleswaram STRUCTURES. Downloaded from Downloaded S. from Kiran, www.studiestoday.com PGT (CS) KV, STRUCTURES WHAT IS A STRUCTURE? Structure is a collection of logically related data. It is also a collection of dissimilar datatype. Downloaded

More information

Lab 2: Pointers. //declare a pointer variable ptr1 pointing to x. //change the value of x to 10 through ptr1

Lab 2: Pointers. //declare a pointer variable ptr1 pointing to x. //change the value of x to 10 through ptr1 Lab 2: Pointers 1. Goals Further understanding of pointer variables Passing parameters to functions by address (pointers) and by references Creating and using dynamic arrays Combing pointers, structures

More information

BITG 1113: Array (Part 1) LECTURE 8

BITG 1113: Array (Part 1) LECTURE 8 BITG 1113: Array (Part 1) LECTURE 8 1 1 LEARNING OUTCOMES At the end of this lecture, you should be able to: 1. Describe the fundamentals of arrays 2. Describe the types of array: One Dimensional (1 D)

More information

Lecture 2 Arrays, Searching and Sorting (Arrays, multi-dimensional Arrays)

Lecture 2 Arrays, Searching and Sorting (Arrays, multi-dimensional Arrays) Lecture 2 Arrays, Searching and Sorting (Arrays, multi-dimensional Arrays) In this lecture, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning of

More information

Structures can be easily used as a function parameters. It is done similar as with variables.

Structures can be easily used as a function parameters. It is done similar as with variables. 1. Structures in functions. Structures can be easily used as a function parameters. It is done similar as with variables. #include char title[50]; char author[50]; char subject[100]; int book_id;

More information

A structure is an aggregate data type which contains a fixed number of heterogeneous components.

A structure is an aggregate data type which contains a fixed number of heterogeneous components. Structures 1 Definition: A structure is an aggregate data type which contains a fixed number of heterogeneous components. Structure components are termed fields or members, each with a unique name. Each

More information

The American University in Cairo Department of Computer Science & Engineering CSCI &09 Dr. KHALIL Exam-I Fall 2011

The American University in Cairo Department of Computer Science & Engineering CSCI &09 Dr. KHALIL Exam-I Fall 2011 The American University in Cairo Department of Computer Science & Engineering CSCI 106-07&09 Dr. KHALIL Exam-I Fall 2011 Last Name :... ID:... First Name:... Form I Section No.: EXAMINATION INSTRUCTIONS

More information

1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol.

1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol. 1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol. B. Outputs to the console a floating point number f1 in scientific format

More information

BITG 1233: Array (Part 1) LECTURE 8 (Sem 2, 17/18)

BITG 1233: Array (Part 1) LECTURE 8 (Sem 2, 17/18) BITG 1233: Array (Part 1) LECTURE 8 (Sem 2, 17/18) 1 LEARNING OUTCOMES At the end of this lecture, you should be able to: 1. Describe the fundamentals of arrays 2. Describe the types of array: One Dimensional

More information

CPT101- Principles of Programming

CPT101- Principles of Programming UNIVERSITI SAINS MALAYSIA Stamford College First Semester Examination 2004/2005 Academic Session October 2004 External Degree Programme Bachelor of Computer Science (Hons.) CPT101- Principles of Programming

More information

Object Oriented Pragramming (22316)

Object Oriented Pragramming (22316) Chapter 1 Principles of Object Oriented Programming (14 Marks) Q1. Give Characteristics of object oriented programming? Or Give features of object oriented programming? Ans: 1. Emphasis (focus) is on data

More information

Chapter 3 Problem Solving and the Computer

Chapter 3 Problem Solving and the Computer Chapter 3 Problem Solving and the Computer An algorithm is a step-by-step operations that the CPU must execute in order to solve a problem, or to perform that task. A program is the specification of an

More information

Name Section: M/W or T/TH. True or False (14 Points)

Name Section: M/W or T/TH. True or False (14 Points) Name Section: M/W or T/TH True or False (14 Points) 1. (14 pts) Circle T for true and F for false: T F a) In C++, a function definition should not be nested within another function definition. T F b) Static

More information

Syntax to define a Structure: struct structurename { datatype membername1; datatype membername2;... } ; For Example:

Syntax to define a Structure: struct structurename { datatype membername1; datatype membername2;... } ; For Example: STRUCTURE IN C++ 1 A Structure is a collection of variables of different data types under one name. A structure defines a new user defined data type for your current program using which items of different

More information

CPE Summer 2015 Exam I (150 pts) June 18, 2015

CPE Summer 2015 Exam I (150 pts) June 18, 2015 Name Closed notes and book. If you have any questions ask them. Write clearly and make sure the case of a letter is clear (where applicable) since C++ is case sensitive. You can assume that there is one

More information

Chapter 7 Arithmetic

Chapter 7 Arithmetic Chapter 7 Arithmetic 7-1 Arithmetic in C++ Arithmetic expressions are made up of constants, variables, operators and parentheses. The arithmetic operators in C++ are as follows + (addition) - (subtraction)

More information

Babaria Institute of Technology Computer Science and Engineering Department Practical List of Object Oriented Programming with C

Babaria Institute of Technology Computer Science and Engineering Department Practical List of Object Oriented Programming with C Practical -1 Babaria Institute of Technology LEARN CONCEPTS OF OOP 1. Explain Object Oriented Paradigm with figure. 2. Explain basic Concepts of OOP with example a. Class b. Object c. Data Encapsulation

More information

I Mid Semester May 2012 : Class XII : Computer Science Max Mark 50 : Time 2 Hrs. 1. a) What is macro in C++? Give example 2

I Mid Semester May 2012 : Class XII : Computer Science Max Mark 50 : Time 2 Hrs. 1. a) What is macro in C++? Give example 2 I Mid Semester May 01 : Class XII : Computer Science Max Mark 50 : Time Hrs 1. a) What is macro in C++? Give example b) Give the Header file for the following functions:- i) gets ( ) ii) tolower( ) 1 c)

More information

Downloaded from

Downloaded from Unit I Chapter -1 PROGRAMMING IN C++ Review: C++ covered in C++ Q1. What are the limitations of Procedural Programming? Ans. Limitation of Procedural Programming Paradigm 1. Emphasis on algorithm rather

More information

CLASS-XI COMPUTER SCIENCE

CLASS-XI COMPUTER SCIENCE Roll No. Code : 112014-083-A Please check that this question paper contains 7 questions and 8 printed pages. CLASS-XI COMPUTER SCIENCE Time Allowed : 3 Hrs. Maximum Marks : 70 General Instructions : All

More information

The University of Nottingham

The University of Nottingham The University of Nottingham SCHOOL OF COMPUTER SCIENCE A LEVEL 2 MODULE, AUTUMN SEMESTER 2008 2009 C/C++ for Java Programmers Time allowed TWO hours Candidates may complete the front cover of their answer

More information

Array Part dimensional arrays - 2-dimensional array operations - Arrays of Strings - N-dimensional arrays

Array Part dimensional arrays - 2-dimensional array operations - Arrays of Strings - N-dimensional arrays Array Array Part 1 - Accessing array - Array and loop arrays must be used with loops - Array and bound checking Be careful of array bound: invalid subscripts => corrupt memory; cause bugs - Array initialization

More information

typedef int Array[10]; String name; Array ages;

typedef int Array[10]; String name; Array ages; Morteza Noferesti The C language provides a facility called typedef for creating synonyms for previously defined data type names. For example, the declaration: typedef int Length; Length a, b, len ; Length

More information

Name SECTION: 12:45 2:20. True or False (12 Points)

Name SECTION: 12:45 2:20. True or False (12 Points) Name SECION: 12:45 2:20 rue or False (12 Points) 1. (12 pts) Circle for true and F for false: F a) Local identifiers have name precedence over global identifiers of the same name. F b) Local variables

More information

True or False (15 Points)

True or False (15 Points) Name Number True or False (15 Points) 1. (15 pts) Circle T for true and F for false: T F a) Void Functions cannot use reference parameters. T F b) Arguments corresponding to value parameters can be variables

More information

Arrays. CS10001: Programming & Data Structures. Pallab Dasgupta Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur

Arrays. CS10001: Programming & Data Structures. Pallab Dasgupta Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur Arrays CS10001: Programming & Data Structures Pallab Dasgupta Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur 1 Array Many applications require multiple data items that have common

More information

Introduction to Programming EC-105. Lecture 2

Introduction to Programming EC-105. Lecture 2 Introduction to Programming EC-105 Lecture 2 Input and Output A data stream is a sequence of data - Typically in the form of characters or numbers An input stream is data for the program to use - Typically

More information

CPE 112 Spring 2015 Exam III (100 pts) April 8, True or False (12 Points)

CPE 112 Spring 2015 Exam III (100 pts) April 8, True or False (12 Points) Name rue or False (12 Points) 1. (12 pts) Circle for true and F for false: F a) Local identifiers have name precedence over global identifiers of the same name. F b) Local variables retain their value

More information

CSCE Practice Midterm. Data Types

CSCE Practice Midterm. Data Types CSCE 2004 - Practice Midterm This midterm exam was given in class several years ago. Work each of the following questions on your own. Once you are done, check your answers. For any questions whose answers

More information

True or False (14 Points)

True or False (14 Points) Name Number True or False (14 Points) 1. (15 pts) Circle T for true and F for false: T F a) void functions can use the statement return; T F b) Arguments corresponding to value parameters can be variables.

More information

Objectives. Chapter 8 Arrays and Strings. Objectives (cont d.) Introduction 12/14/2014. In this chapter, you will:

Objectives. Chapter 8 Arrays and Strings. Objectives (cont d.) Introduction 12/14/2014. In this chapter, you will: Objectives Chapter 8 Arrays and Strings In this chapter, you will: Learn about arrays Declare and manipulate data into arrays Learn about array index out of bounds Learn about the restrictions on array

More information

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible)

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible) Name Closed notes, book and neighbor. If you have any questions ask them. Notes: Segment of code necessary C++ statements to perform the action described not a complete program Program a complete C++ program

More information

Introduction to Algorithms and Data Structures. Structuring Data: Multidimensional Arrays, Arrays of Structures, and Structures Containing Arrays

Introduction to Algorithms and Data Structures. Structuring Data: Multidimensional Arrays, Arrays of Structures, and Structures Containing Arrays Introduction to Algorithms and Data Structures Structuring Data: Multidimensional Arrays, Arrays of Structures, and Structures Containing Arrays grades.cpp #include const int numstudents =

More information

Arrays - Vectors. Arrays: ordered sequence of values of the same type. Structures: named components of various types

Arrays - Vectors. Arrays: ordered sequence of values of the same type. Structures: named components of various types Arrays - Vectors Data Types Data Type: I. set of values II. set of operations over those values Example: Integer I. whole numbers, -32768 to 32767 II. +, -, *, /, %, ==,!=, , =,... Which operation

More information

F4104 ALGORITHM & DATA STRUCTURE

F4104 ALGORITHM & DATA STRUCTURE F4104 ALGORITHM & DATA STRUCTURE.:: UNIT 1::. INTRODUCTION TO ALGORITHM & DATA STRUCTURES 1.1 ALGORITHM CONCEPTS ALGORITHM Algorithm: A clearly specified finite set of instructions a computer follows to

More information

Fundamentals of Programming CS-110. Lecture 2

Fundamentals of Programming CS-110. Lecture 2 Fundamentals of Programming CS-110 Lecture 2 Last Lab // Example program #include using namespace std; int main() { cout

More information

Introduction to C++ 2. A Simple C++ Program. A C++ program consists of: a set of data & function definitions, and the main function (or driver)

Introduction to C++ 2. A Simple C++ Program. A C++ program consists of: a set of data & function definitions, and the main function (or driver) Introduction to C++ 1. General C++ is an Object oriented extension of C which was derived from B (BCPL) Developed by Bjarne Stroustrup (AT&T Bell Labs) in early 1980 s 2. A Simple C++ Program A C++ program

More information

CSCE 110 PROGRAMMING FUNDAMENTALS

CSCE 110 PROGRAMMING FUNDAMENTALS CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 11. The Struct Data Type Prof. amr Goneid, AUC 1 The Struct Data Type Prof. amr Goneid, AUC 2 The Struct Data Type What are Structs?

More information

Programming in C++ The manager of a company. Lecture Notes 6. Functions (Procedures) 4/24/2018. he he he. Does Does Does

Programming in C++ The manager of a company. Lecture Notes 6. Functions (Procedures) 4/24/2018. he he he. Does Does Does The manager of a company Programming in C++ Lecture Notes 6 Functions (Procedures) Does Does Does he he he pay the bills? answer the phone? clean the office? 2 1 Division of Labor Our programs until now

More information

I BCS-031 BACHELOR OF COMPUTER APPLICATIONS (BCA) (Revised) Term-End Examination. June, 2015 BCS-031 : PROGRAMMING IN C ++

I BCS-031 BACHELOR OF COMPUTER APPLICATIONS (BCA) (Revised) Term-End Examination. June, 2015 BCS-031 : PROGRAMMING IN C ++ No. of Printed Pages : 3 I BCS-031 BACHELOR OF COMPUTER APPLICATIONS (BCA) (Revised) Term-End Examination 05723. June, 2015 BCS-031 : PROGRAMMING IN C ++ Time : 3 hours Maximum Marks : 100 (Weightage 75%)

More information

CSC 126 FINAL EXAMINATION Spring Total Possible TOTAL 100

CSC 126 FINAL EXAMINATION Spring Total Possible TOTAL 100 CSC 126 FINAL EXAMINATION Spring 2011 Version A Name (Last, First) Your Instructor Question # Total Possible 1. 10 Total Received 2. 15 3. 15 4. 10 5. 10 6. 10 7. 10 8. 20 TOTAL 100 Name: Sp 11 Page 2

More information

The American University in Cairo Computer Science & Engineering Department CSCE Dr. KHALIL Exam II Spring 2010

The American University in Cairo Computer Science & Engineering Department CSCE Dr. KHALIL Exam II Spring 2010 The American University in Cairo Computer Science & Engineering Department CSCE 106-08 Dr. KHALIL Exam II Spring 2010 Last Name :... ID:... First Name:... Form - I EXAMINATION INSTRUCTIONS * Do not turn

More information

CHAPTER 4 FUNCTIONS. 4.1 Introduction

CHAPTER 4 FUNCTIONS. 4.1 Introduction CHAPTER 4 FUNCTIONS 4.1 Introduction Functions are the building blocks of C++ programs. Functions are also the executable segments in a program. The starting point for the execution of a program is main

More information

PROGRAMMAZIONE I A.A. 2017/2018

PROGRAMMAZIONE I A.A. 2017/2018 PROGRAMMAZIONE I A.A. 2017/2018 STRUCTURES STRUCTS Arrays allow to define type of variables that can hold several data items of the same kind. Similarly structure is another user defined data type available

More information

Computer Department. Question (1): State whether each of the following is true or false. Question (2): Select the correct answer from the following:

Computer Department. Question (1): State whether each of the following is true or false. Question (2): Select the correct answer from the following: Computer Department Program: Computer Midterm Exam Date : 19/11/2016 Major: Information & communication technology 1 st Semester Time : 1 hr (10:00 11:00) Course: Introduction to Programming 2016/2017

More information

IT 1003 Introduction to Programming (New)

IT 1003 Introduction to Programming (New) [All Rights Reserved] SLIATE SRI LANKA INSTITUTE OF ADVANCED TECHNOLOGICAL EDUCATION (Established in the Ministry of Higher Education, vide in Act No. 29 of 1995) Instructions for Candidates: Answer five

More information

3/12/2018. Structures. Programming in C++ Sequential Branching Repeating. Loops (Repetition)

3/12/2018. Structures. Programming in C++ Sequential Branching Repeating. Loops (Repetition) Structures Programming in C++ Sequential Branching Repeating Loops (Repetition) 2 1 Loops Repetition is referred to the ability of repeating a statement or a set of statements as many times this is necessary.

More information

1. a) What #include statement do you put at the top of a program that does uses cin, cout or endl?

1. a) What #include statement do you put at the top of a program that does uses cin, cout or endl? Exercises with solutions. 1. a) What #include statement do you put at the top of a program that does uses cin, cout or endl? #include b) What using statement do you always put at the top of

More information

Duhok Polytechnic University Amedi Technical Institute/ IT Dept. Halkawt Rajab Hussain

Duhok Polytechnic University Amedi Technical Institute/ IT Dept. Halkawt Rajab Hussain Duhok Polytechnic University Amedi Technical Institute/ IT Dept. By Halkawt Rajab Hussain 2016-04-02 : Structure declaration and initialization. Access to fields of structure. Array of Structs. 11/10/2016

More information

b) #include<iostream.h> void main() { int a, b; cout<<"input two integer values? "; cin>>a>>b; double avg=(a+b)/2.0; cout<<"average="<<avg<<endl; }

b) #include<iostream.h> void main() { int a, b; cout<<input two integer values? ; cin>>a>>b; double avg=(a+b)/2.0; cout<<average=<<avg<<endl; } SAMPLEPAPER-2016 (Class 11) 1a)Name the header file(s) that shall be needed for successful compilation of the following C++ code. void main( ) char Name[20]; gets(name); int n=1+random(5); for(int k=0;k

More information

Expressions, Input, Output and Data Type Conversions

Expressions, Input, Output and Data Type Conversions L E S S O N S E T 3 Expressions, Input, Output and Data Type Conversions PURPOSE 1. To learn input and formatted output statements 2. To learn data type conversions (coercion and casting) 3. To work with

More information

1. To introduce and allow students to work with arrays 2. To introduce the typedef statement 3. To work with and manipulate multidimensional arrays

1. To introduce and allow students to work with arrays 2. To introduce the typedef statement 3. To work with and manipulate multidimensional arrays L E S S O N S E T 7 Arrays PURPOSE PROCEDURE 1. To introduce and allow students to work with arrays 2. To introduce the typedef statement 3. To work with and manipulate multidimensional arrays 1. Students

More information

True or False (15 Points)

True or False (15 Points) Name Number True or False (15 Points) 1. (15 pts) Circle T for true and F for false: T F a) Value Returning Functions cannot use reference parameters. T F b) Arguments corresponding to value parameters

More information

WARM UP LESSONS BARE BASICS

WARM UP LESSONS BARE BASICS WARM UP LESSONS BARE BASICS CONTENTS Common primitive data types for variables... 2 About standard input / output... 2 More on standard output in C standard... 3 Practice Exercise... 6 About Math Expressions

More information

Subject: Computer Science

Subject: Computer Science Subject: Computer Science Topic: Data Types, Variables & Operators 1 Write a program to print HELLO WORLD on screen. 2 Write a program to display output using a single cout statement. 3 Write a program

More information

Introduction to Algorithms and Programming (COMP151)

Introduction to Algorithms and Programming (COMP151) Introduction to Algorithms and Programming (COMP151) A Student's Manual for Practice Exercises Dr. Mohamed Aissa m.issa@unizwa.edu.om 11i13 Summer 2014 Practice Exercises #1 Introduction Page 2 Practice

More information

C++ Final Exam 2017/2018

C++ Final Exam 2017/2018 1) All of the following are examples of integral data types EXCEPT. o A Double o B Char o C Short o D Int 2) After the execution of the following code, what will be the value of numb if the input value

More information

Using Parallel Arrays. Parallel Array Example

Using Parallel Arrays. Parallel Array Example Using Parallel Arrays Parallel arrays: two or more arrays that contain related data A subscript is used to relate arrays: elements at same subscript are related Arrays may be of different types Parallel

More information

BASIC ELEMENTS OF A COMPUTER PROGRAM

BASIC ELEMENTS OF A COMPUTER PROGRAM BASIC ELEMENTS OF A COMPUTER PROGRAM CSC128 FUNDAMENTALS OF COMPUTER PROBLEM SOLVING LOGO Contents 1 Identifier 2 3 Rules for naming and declaring data variables Basic data types 4 Arithmetic operators

More information

6.096 Introduction to C++

6.096 Introduction to C++ MIT OpenCourseWare http://ocw.mit.edu 6.096 Introduction to C++ January (IAP) 2009 For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms. MASSACHUSETTS INSTITUTE

More information

The American University in Cairo Computer Science & Engineering Department CSCE 106 Fundamentals of Computer Science. Instructor: Final Exam Fall 2011

The American University in Cairo Computer Science & Engineering Department CSCE 106 Fundamentals of Computer Science. Instructor: Final Exam Fall 2011 The American University in Cairo Computer Science & Engineering Department CSCE 106 Fundamentals of Computer Science Instructor: Final Exam Fall 2011 Last Name :... ID:... First Name:... Section No.: EXAMINATION

More information

Getting started with C++ (Part 2)

Getting started with C++ (Part 2) Getting started with C++ (Part 2) CS427: Elements of Software Engineering Lecture 2.2 11am, 16 Jan 2012 CS427 Getting started with C++ (Part 2) 1/22 Outline 1 Recall from last week... 2 Recall: Output

More information

Chapter 4 - Notes Control Structures I (Selection)

Chapter 4 - Notes Control Structures I (Selection) Chapter 4 - Notes Control Structures I (Selection) I. Control Structures A. Three Ways to Process a Program 1. In Sequence: Starts at the beginning and follows the statements in order 2. Selectively (by

More information

C++ Input/Output Chapter 4 Topics

C++ Input/Output Chapter 4 Topics Chapter 4 Topics Chapter 4 Program Input and the Software Design Process Input Statements to Read Values into a Program using >>, and functions get, ignore, getline Prompting for Interactive Input/Output

More information

.:: UNIT 1 ::. INTRODUCTION TO ALGORITHM & DATA STRUCTURES

.:: UNIT 1 ::. INTRODUCTION TO ALGORITHM & DATA STRUCTURES .:: UNIT 1 ::. INTRODUCTION TO ALGORITHM & DATA STRUCTURES 1.1 Algorithm: A clearly specified finite set of instructions a computer follows to solve a problem. An algorithm is a well-ordered collection

More information

The University of Alabama in Huntsville Electrical and Computer Engineering CPE Example of Objective Test Questions for Test 4

The University of Alabama in Huntsville Electrical and Computer Engineering CPE Example of Objective Test Questions for Test 4 The University of Alabama in Huntsville Electrical and Computer Engineering CPE 112 02 Example of Objective Test Questions for Test 4 True or False Name: 1. The statement switch (n) case 8 : alpha++; case

More information

Functions, Arrays & Structs

Functions, Arrays & Structs Functions, Arrays & Structs Unit 1 Chapters 6-7, 11 Function Definitions! Function definition pattern: datatype identifier (parameter1, parameter2,...) { statements... Where a parameter is: datatype identifier

More information

void Add() { cin >> trainnumber; gets(trainname); } void display() { cout<<trainnumber <<":"<<TrainName<<end;

void Add() { cin >> trainnumber; gets(trainname); } void display() { cout<<trainnumber <<:<<TrainName<<end; . T SHREE MAHAPRABHU PUBLIC SCHOOL & COLLEGE QUESTION BANK FOR BOARD EXAMINATION 016-17 SUBJECT COMPUTER SCIENCE (Code: 083) Q1. Answer the following questions: a) Name the header file(s) that shall be

More information