Download presentation
Presentation is loading. Please wait.
Published byEunice Houston Modified over 6 years ago
1
REVISION CSC 138 – Structured Programming One Dimensional Array
CHAPTER ONE One Dimensional Array Two Dimensional Array Records Input Output File CHAPTER TWO CHAPTER THREE CHAPTER FOUR
2
LEARNING OBJECTIVES Upon completion, you should be able to understand:
the structure of 1D array the structure of 2D array the structure of records/struct the structure of read(instream) and write(ofstream) file Apply all the concept for implementation phase(mini project)
3
Variable Array VARIABLE VS. ARRAY Variable can only store
one value at a time Array Array can store many values of the same data type at one time Fruit : Apple Fruit : Apple Grape Kiwi
4
REFRESH YOUR MEMORY float my_float_array [25] ; -1D ARRAY DECLARATION-
Declare an array of type float with 25 elements with identifier my_float_array float my_float_array [25] ; DATA TYPE VARIABLE NAME Array size -1D ARRAY DECLARATION-
5
REFRESH YOUR MEMORY 1. Declare an array of type char with 1000 elements with identifier my_char_array 2. Declare an array of type double called “price” having 5 elements 3. Declare an array “Scores”having 20 elements of type integer
6
REFRESH YOUR MEMORY 4. Explain the error in the following array declaration: a) char my char array []; b) score[25]; c) int ids[-30]; d) double [50] salaries;
7
INPUT DATA INTO ARRAY Counter-controlled loop: int main() {
int num[5]; for(int i =0; i<5; i++) cin >> num[i]; }
8
INPUT DATA INTO ARRAY Sentinel-controlled loop: int main() {
int arraySize; cout<< "Enter the size of array: "; cin >> arraySize; int num[arraySize]; for(int i =0; i<arraySize; i++) cin >> num[i]; }
9
ASSIGNING DATA INTO ARRAY
Assigns the letters x,y,and z to the letters array,replacing the letters A,B,C char letters[3] = {‘A’, ‘B’, ‘C’}; //line 1 letters[0] = ‘x’ //line 2 letters[1] = ‘y’ //line 3 letters[2] = ‘z’ //line 4
10
OUTPUT / PRINTING ARRAY
O Print all elements in the array using for loop: for(int i=0;i<ArraySize;i++) { cout<<mylist[i]<<endl; } O Print all elements in the array using while loop: int i=0; while(i<arraySize) i++;
11
ARRAY OF CHARACTERS
12
ARRAY OF CHARACTERS
13
ARRAY OF CHARACTERS
14
REFRESH YOUR MEMORY Find the average number among 10 numbers
below and list all numbers that are greater than the average. • 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
15
STEP TO SOLVE THE PROBLEM
Ask user to insert 10 numbers Add up all 10 numbers Divide by 10 Show the average number on screen 1 2 3 4
16
SOLUTION (WITHOUT ARRAY)
17
SOLUTION (OUTPUT)
18
SOLUTION (WITH ARRAY)
19
SOLUTION (OUTPUT)
20
REFRESH YOUR MEMORY -2D ARRAY DECLARATION- Chapter 2 COLUMN DATA TYPE
VARIABLE NAME ROW -2D ARRAY DECLARATION-
21
Let’s Do It!
22
INPUT INTO 2D ARRAY Input a single row:
To input data into row number 4 (fifth row) row = 4; for(col = 0; col < Number_of_Columns; col++) cin >> matrix[row][col]; Input data into each component of the array: for(row = 0; row < Number_of_Rows; row++) { }
23
PRINTING 2D ARRAY To print a two-dimensional array, you have to print each element in the array using a loop like the following: for (int row = 0; row < rowSize; row++) { for (int column=0; column<columnSize; column++) cout << matrix[row][column] << " "; } cout << endl;
24
Array operations using 7 basic algorithms
Min Max Count Total Average Sort (bubble) Search (sequential)
25
RECORD DECLARATION OR A struct is a definition, not a declaration
struct studentType { string firstName; string lastName; char courseGrade; int testScore; int programmingScore; double GPA; //variable declaration } newStudent, student; OR C++ Programming: From Problem Analysis to Program Design, Fourth Edition
26
RECORD INITIALIZATION
Initialization can be done during declaration. Example 1: struct student stud1 = {“Nadiah”, “ ”, “A11000”, 1998}; Example 2: struct date { int day; int month; int year; } struct date Birth_Day = {1, 1, 1982}; 1 day Birth_Day 1 month 1982 year Company Logo CSC 138 Structured programming
27
RECORD ASSIGNMENT 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
28
EXERCISE (3.2.3) struct studentType { string firstName;
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];
29
ANSWER (3.2.3) 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'; } 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; 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; }
30
EXERCISE (3.2.5) Suppose that you have the following definitions:
struct tourType { char cityName[20]; int distance, hour, sec; double min; }; Declare the variable named destination of type tourType. Write C++ statements to store the following data in destination: cityName - chicago, distance miles, travelTime - 9 hours and 30 minutes. 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. Write the definition of void function with reference parameter of type tourType to input data in a variable of type tourType.
31
EXERCISE (3.2.6) 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]; }; Create an array of 100 malay books Write the function definition for each of the following 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. 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.
32
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. 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.
33
WRITE DATA INTO FILE(A Complete Program)
Example 1:
34
WRITE DATA INTO FILE(A Complete Program)
Example 1 (output):
35
READ DATA FROM FILE The ifstream : is used to read primitive data type values, arrays, strings, and objects from a text file. Eg: The program creates an instance of ifstream and reads all lines from the file “testMarks.txt”. Each line consists of name (a string), test 1 and test 2 (an integer) can be displayed on the screen. inFile.getline(names, 25, ';') After INPUT from file inFile >> test1 >> test2;
36
READ DATA FROM FILE (A Complete Program)
#include <fstream.h> //Step1: Include a header file main(){ //Step 2: Declare an input stream variable ifstream inFile; char names[25]; double test1, test2; //Step 3: Open for an input file inFile.open(“testMarks.txt”); //Step 4: Read data from an input file - using eof() inFile.getline(names,25, ';'); inFile >> test1 >> test2; while(!inFile.eof()){ cout << names << " " << test1 << " " << test2; } inFile.close(); //Step 5: Close an input file getch(); Use getline() function to read character with spaces: ifstreamVariableName.getline(attributeVariable, characterSize, delimiter); If not at end of file, continue reading data
37
READ DATA FROM FILE & STORE INTO ARRAY
Example 1: Suppose that a file names inData.txt contains the following data: The numbers in each line represents the length and width of a rectangle. Write C++ statements that will read data from inData.txt file and store into array rectangle[3][2]. Lastly, display the array onto the screen as the following format:
38
READ DATA FROM FILE & STORE INTO ARRAY
Example 1:
39
READ DATA FROM FILE & STORE INTO ARRAY
Example 1:
40
READ DATA FROM FILE & STORE INTO ARRAY
Example 1 (Output): Notepad : Console (Command Prompt):
41
READ DATA FROM FILE & STORE INTO ARRAY
Example 2: Extend from the same program, calculate the area of rectangle by reading the data in each line and store the results in outData.txt.
42
READ DATA FROM FILE & STORE INTO ARRAY
Example 2:
43
READ DATA FROM FILE & STORE INTO ARRAY
Example 2 (Output): Notepad :
44
READ DATA AS RECORD Example 3:
Read all the records that have been stored in a file named compStock.txt which consist of: brand, price and operating system. Notepad :
45
READ DATA AS RECORD struct Computer { char brand[20]; double price;
Example 3: All the data will be stored into a variable struct array named computers. Given the definition of Computer record and declaration of computers array: struct Computer { char brand[20]; double price; int operating //1: Windows 8 //2: Windows 10 }; main() { Computer computers[7]; : }
46
READ DATA AS RECORD Example 3:
47
READ DATA AS RECORD Example 3:
48
READ DATA AS RECORD Example 3 (output): Notepad :
Console (Command Prompt): Notepad :
49
PASS FILE VARIABLE INTO FUNCTION (AS PARAMETER)
Example 4: Based on the previous program, write a program by using modular programming techniques that find and write all brands of computers using Windows 10 and the total numbers of those computers in an output file named win10.txt. Console (Command Prompt): Notepad:
50
PASS FILE VARIABLE INTO FUNCTION (AS PARAMETER)
Example 4:
51
PASS FILE VARIABLE INTO FUNCTION (AS PARAMETER)
Example 4:
52
PASS FILE VARIABLE INTO FUNCTION (AS PARAMETER)
Example 4:
53
PASS FILE VARIABLE INTO FUNCTION (AS PARAMETER)
Example 4:
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.