REVISION CSC 138 – Structured Programming One Dimensional Array

Slides:



Advertisements
Similar presentations
Student Data Score First Name Last Name ID GPA DOB Phone... How to store student data in our programs? 1.
Advertisements

C++ Basics March 10th. A C++ program //if necessary include headers //#include void main() { //variable declaration //read values input from user //computation.
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 10: Records ( structs )
Chapter 11: Records (structs)
1 11/3/08CS150 Introduction to Computer Science 1 Reading from and Writing to Files Section 3.12 & 13.1 & 13.5.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 8 Multidimensional.
1 10/29/07CS150 Introduction to Computer Science 1 Reading from and Writing to Files Section 3.12 & 13.1 & 13.5.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 11: Records (structs)
Chapter 8. 2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays as Arguments Two-Dimensional Arrays Common.
1 September 6, 2005CS150 Introduction to Computer Science I What Actions Do We Have Part 1 CS150 Introduction to Computer Science I.
Computer Science 1620 Programming & Problem Solving.
1 10/25/06CS150 Introduction to Computer Science 1 Reading from and Writing to Files.
EGR 2261 Unit 10 Records (structs)
Chapter 10: Records (structs)
Modular Programming Chapter Value and Reference Parameters computeSumAve (x, y, sum, mean) ACTUALFORMAL xnum1(input) ynum2(input) sumsum(output)
STREAMS AND FILES OVERVIEW.  Many programs are "data processing" applications  Read the input data  Perform sequence of operations on this data  Write.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 11: Records ( struct s)
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 10: Records ( struct s)
Edited from Powerpoint Slides provided by Thomson Learning
© Copyright 2013 by Pearson Education, Inc. All Rights Reserved. 1 Chapter 8 Multidimensional Arrays.
CHAPTER 7 arrays I NTRODUCTION T O C OMPUTER P ROGRAMMING (CSC425)
Arrays & Structures II Chapter 9. 2 Organizing Heterogeneous Data  Arrays allow a programmer to organize values of the same type  Homogeneous data 
Organizing Heterogeneous Data Arrays allow a programmer to organize lists of values that are all of the same type (homogeneous). But we are often faced.
CS161 Topic #16 1 Today in CS161 Lecture #16 Prepare for the Final Reviewing all Topics this term Variables If Statements Loops (do while, while, for)
1 Topic: Array Topic: Array. 2 Arrays Arrays In this chapter, we will : Learn about arrays Learn about arrays Explore how to declare and manipulate data.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays.
CHAPTER 10 ARRAYS AND FUNCTIONS Prepared by: Lec. Ghader Kurdi.
GE 211 Dr. Ahmed Telba. // compound assignment operators #include using namespace std; int main () { a =5 int a, b=3; a = b; a+=2; // equivalent to a=a+2.
Quiz // // The function exchanges the two parameters. // Param: ( ) // Param:
Copyright © 2002 W. A. Tucker1 Chapter 9 Lecture Notes Bill Tucker Austin Community College COSC 1315.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 6 Arrays.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
Arrays Dr. Jose Annunziato. Arrays Up to this point we have been working with individual primitive data types Arrays allow working with multiple instances.
Chapter 8 Arrays. A First Book of ANSI C, Fourth Edition2 Introduction Atomic variable: variable whose value cannot be further subdivided into a built-in.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 11: Records ( struct s)
CPS120 Introduction to Computer Science Exam Review Lecture 18.
Introduction to Programming Lecture 12. Today’s Lecture Includes Strings ( character arrays ) Strings ( character arrays ) Algorithms using arrays Algorithms.
A FIRST BOOK OF C++ CHAPTER 7 ARRAYS. OBJECTIVES In this chapter, you will learn about: One-Dimensional Arrays Array Initialization Arrays as Arguments.
Basic concepts of C++ Presented by Prof. Satyajit De
What Actions Do We Have Part 1
Chapter 8 Multidimensional Arrays
Chapter 7 – Arrays.
Chapter 8: Arrays Starting Out with C++ Early Objects Ninth Edition
Yanal Alahmad Java Workshop Yanal Alahmad
Basic Array Definition
Chapter 5: Control Structure
Java Programming: From Problem Analysis to Program Design,
New Structure Recall “average.cpp” program
Chapter 7: Arrays.
Siti Nurbaya Ismail Senior Lecturer
One-Dimensional Array Introduction Lesson xx
Chapter 9: Records (structs)
Chapter 9: Records (structs)
CNG 140 C Programming (Lecture set 8)
Chapter 9: Records (structs)
Chapter 8 Multidimensional Arrays
Programming Funamental slides
Chapter 3 Input output.
Multidimensional Arrays
Multidimensional Arrays
Chapter 11: Records (structs)
Chapter 5: Control Structures II (Repetition)
Functions continued.
CPS120: Introduction to Computer Science
What Actions Do We Have Part 1
Fundamental Programming
Arrays.
C++ Basics CSci 107. A C++ program //include headers; these are modules that include functions that you may use in your //program; we will almost always.
Chapter 7 Multidimensional Arrays
Chapter 9: Records (structs)
Presentation transcript:

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

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)

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

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-

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

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;

INPUT DATA INTO ARRAY Counter-controlled loop: int main() { int num[5]; for(int i =0; i<5; i++) cin >> num[i]; }

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]; }

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

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++;

ARRAY OF CHARACTERS

ARRAY OF CHARACTERS

ARRAY OF CHARACTERS

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

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

SOLUTION (WITHOUT ARRAY)

SOLUTION (OUTPUT)

SOLUTION (WITH ARRAY)

SOLUTION (OUTPUT)

REFRESH YOUR MEMORY -2D ARRAY DECLARATION- Chapter 2 COLUMN DATA TYPE VARIABLE NAME ROW -2D ARRAY DECLARATION-

Let’s Do It!

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++) { }

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;

Array operations using 7 basic algorithms Min Max Count Total Average Sort (bubble) Search (sequential)

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

RECORD INITIALIZATION Initialization can be done during declaration. Example 1: struct student stud1 = {“Nadiah”, “880409-13-5555”, “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

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

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];

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; }

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 - 550 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.

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.

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.

WRITE DATA INTO FILE(A Complete Program) Example 1:

WRITE DATA INTO FILE(A Complete Program) Example 1 (output):

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;

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

READ DATA FROM FILE & STORE INTO ARRAY Example 1: Suppose that a file names inData.txt contains the following data: 10.20 5.35 15.60 8.20 16.12 7.28 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:

READ DATA FROM FILE & STORE INTO ARRAY Example 1:

READ DATA FROM FILE & STORE INTO ARRAY Example 1:

READ DATA FROM FILE & STORE INTO ARRAY Example 1 (Output): Notepad : Console (Command Prompt):

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.

READ DATA FROM FILE & STORE INTO ARRAY Example 2:

READ DATA FROM FILE & STORE INTO ARRAY Example 2 (Output): Notepad :

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 :

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]; : }

READ DATA AS RECORD Example 3:

READ DATA AS RECORD Example 3:

READ DATA AS RECORD Example 3 (output): Notepad : Console (Command Prompt): Notepad :

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:

PASS FILE VARIABLE INTO FUNCTION (AS PARAMETER) Example 4:

PASS FILE VARIABLE INTO FUNCTION (AS PARAMETER) Example 4:

PASS FILE VARIABLE INTO FUNCTION (AS PARAMETER) Example 4:

PASS FILE VARIABLE INTO FUNCTION (AS PARAMETER) Example 4: