Introduction to Programming I COS1511 School of Computing Revision Notes

Similar documents
Unit 7. 'while' Loops

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.

Lab Instructor : Jean Lai

Programming Language. Functions. Eng. Anis Nazer First Semester

Multiple Choice (Questions 1 13) 26 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)

Why Is Repetition Needed?

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

Input And Output of C++

Tutorial Letter 103/1/2017 Introduction to Programming I

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

DELHI PUBLIC SCHOOL TAPI

GE U111 Engineering Problem Solving & Computation Lecture 6 February 2, 2004

Exam 1. CSI 201: Computer Science 1 Fall 2018 Professors: Shaun Ramsey

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

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

CS 376b Computer Vision

FORM 2 (Please put your name and form # on the scantron!!!!)

8. Functions (II) Control Structures: Arguments passed by value and by reference int x=5, y=3, z; z = addition ( x, y );

Computer Programming : C++

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons

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

The following expression causes a divide by zero error:

Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS240 BRANCHING STATEMENTS

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

In this chapter you will learn:

Computer Programming

Chapter 17 - Notes Recursion

Chapter 5: Control Structures II (Repetition) Objectives (cont d.) Objectives. while Looping (Repetition) Structure. Why Is Repetition Needed?

CSCE Practice Midterm. Data Types

Agenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures

Chapter 10 - Notes Applications of Arrays

A SHORT COURSE ON C++

REPETITION CONTROL STRUCTURE LOGO

CS 115 Midterm 2 Solutions

1) What of the following sets of values for A, B, C, and D would cause the string "one" to be printed?

More Flow Control Functions in C++ CS 16: Solving Problems with Computers I Lecture #4

Unit 6. Thinking with Functions

do { statements } while (condition);

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 8/19/ Review. Here s a simple C++ program:

Chapter 4 - Notes Control Structures I (Selection)

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

University of Technology. Laser & Optoelectronics Engineering Department. C++ Lab.

Basic program The following is a basic program in C++; Basic C++ Source Code Compiler Object Code Linker (with libraries) Executable

Introduction to Programming

CSCE Practice Midterm. Data Types

Boolean Data-Type. Boolean Data Type (false, true) i.e. 3/6/2018. The type bool is also described as being an integer: bool bflag; bflag = true;

Program Organization and Comments

Fundamentals of Programming CS-110. Lecture 2

5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. The Increment and Decrement Operators

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

Do not turn to the next page until the start of the exam.

1 Unit 8 'for' Loops

Increment and the While. Class 15

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

Exam 3 Chapters 7 & 9

CSC 126 FINAL EXAMINATION FINAL Spring 2012 B. Name (last, First) Instructor. Total Possible. Received

C++ Programming: From Problem Analysis to Program Design, Fourth Edition. Chapter 5: Control Structures II (Repetition)

DHA Suffa University CS 103 Object Oriented Programming Fall 2015 Lab #01: Introduction to C++

C++ For Science and Engineering Lecture 12

1. In C++, reserved words are the same as predefined identifiers. a. True

LAB 4.1 Relational Operators and the if Statement

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 1/9/ Review. Here s a simple C++ program:

CS 115 Exam 3, Spring 2010

CS Spring 05 - MidTerm

Government Polytechnic, Muzaffarpur. Name of the Lab: OBJECT ORIENTED PROGRAMMING

SFU CMPT Topic: Control Statements

2 nd Week Lecture Notes

CS31 Discussion 1E. Jie(Jay) Wang Week3 Oct.12

Jordan University of Science & Technology Department of Computer Science CS 211 Exam #1 (23/10/2010) -- Form A

CSC 126 FINAL EXAMINATION Spring Total Possible TOTAL 100

Chapter 3 Problem Solving and the Computer

Total 100. The American University in Cairo Computer Science & Engineering Department CSCE 106. Instructor: Final Exam Fall Section No.

Chapter 5. Repetition. Contents. Introduction. Three Types of Program Control. Two Types of Repetition. Three Syntax Structures for Looping in C++

Object Reference and Memory Allocation. Questions:

int n = 10; int sum = 10; while (n > 1) { sum = sum + n; n--; } cout << "The sum of the integers 1 to 10 is " << sum << endl;

Chapter 2 Basic Elements of C++

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #44. Multidimensional Array and pointers

Chapter 3. More Flow of Control

CS 141, Introduction to Computer Science Fall Midterm Exam

The American University in Cairo Computer Science & Engineering Department CSCE 106 Fundamentals of Computer Science

THE INTEGER DATA TYPES. Laura Marik Spring 2012 C++ Course Notes (Provided by Jason Minski)

COP 2000 Introduction to Computer Programming Mid-Term Exam Review

#include <iostream> #include <algorithm> #include <cmath> using namespace std; int f1(int x, int y) { return (double)(x/y); }

Your first C++ program

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

READ THIS NOW! Do not start the test until instructed to do so!

CS31 Discussion. Jie(Jay) Wang Week8 Nov.18

CMPS 221 Sample Final

CS Introduction to Programming Midterm Exam #2 - Prof. Reed Fall 2015

Exceptions, Case Study-Exception handling in C++.

Starting Out with C++: Early Objects, 9 th ed. (Gaddis, Walters & Muganda) Chapter 2 Introduction to C++ Chapter 2 Test 1 Key

1st Midterm Exam: Solution COEN 243: Programming Methodology I

The American University in Cairo Computer Science & Engineering Department CSCE 106 Fundamentals of Computer Science

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

Name MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

ENJOY! Problem 2 What does the following code do, in a brief English sentence? int mystery(int k) { int i = 0; if (k < 0) return -1;

Problem Solving: Storyboards for User Interaction

C++ Final Exam 2017/2018

Discussion 1H Notes (Week 3, April 14) TA: Brian Choi Section Webpage:

Transcription:

Introduction to Programming I COS1511 School of Computing Revision Notes UNISA 2018 1

Introduction Some key basic principles to remember: Apply the BODMAS rules of Mathematics for all calculations; The use of OR ( ) as well as AND (&&) are mathematical concepts from discrete mathematics ( ; respectively ), NOT the general English language use. Keep together what belongs together. UNISA 2018 2

Basic Principles Apply the BODMAS rules of Mathematics for all calculations; e.g. When asked to calculate the average of three assignment marks. To do this in a single calculation Add the item values (marks) together in Brackets; Then divide by the number of items (assignments). float Average = (mark1+mark2 + mark3)/numassignments UNISA 2018 3

Basic Principles Keep together what belongs together. int a = 10; a /= 1+1; cout << a; You might guess the answer as 11 because most of us translate the compound assignment operator as follows: a = a / 1 + 1; //this is wrong The statement a /= 1 + 1; is equivalent to a = a / (1 + 1); What was on the right hand side stays together. So the output is 5, not 11. UNISA 2018 4

Loops The use of OR as well as AND are mathematical concepts from discrete mathematics, NOT the general English language use. Know the difference between the two questions below: 1. A loop should execute if age >= 30 or finalmark <= 65 2. A loop should exit if age < 30 and finalmark > 65 These questions are essentially different ways of asking the same thing. In (1) it says that the loop should execute if either of the conditions is true. Then the condition to exit the loop is obviously the opposite of it. ie., the loop should exit if both these conditions are false. See their implementation in the next slide. UNISA 2018 5

Suppose we want to input and validate the age of students that qualify for an internship, as well as the final mark obtained for the examination, in a while loop. To qualify, the student should be younger than 30 with a final mark of more than 65. The variable names are age and finalmark respectively. The while loop should exit only when the right candidate is found. In other words, if a student does not qualify, the loop should iterate again and continue to validate the age and mark for the next student. Complete the program below. cout << "Enter age: "; cin >> age; cout << "Enter final mark for exam: "; cin >> finalmark; while ( ) //complete the condition { //complete the while loop } Loops UNISA 2018 6

Loops Solution: int age, finalmark; cout << "Enter age: "; cin >> age; cout << "Enter final mark for exam: "; cin >> finalmark; while (age >= 30 finalmark <=65) { cout << "Sorry, candidate not selected." << endl; cout << "Enter age: "; cin >> age; cout << "Enter final mark for exam: "; cin >> finalmark; } cout << "Candidate selected." << endl; UNISA 2018 7

Sample loop question Suppose two char variables c1 and c2 are initialised and then input repeatedly in the body of a while loop. The loop has to be executed as long as the value of c1 is not equal to A or the value of c2 is equal to A. Which of the options below is a correct condition for the while loop? 1. ((c1 == 'A') (c2!= 'A')) 2. ((c1!= 'A') (c2 == 'A')) 3. ((c1 == 'A') && (c2!= 'A')) 4. ((c1!= 'A') && (c2 == 'A')) 5. None of the above options is correct. Correct option: 2 The loop has to be executed as long as the value of c1 is not equal to A or the value of c2 is equal to A. Therefore, as soon as one of the two conditions is not valid anymore, the loop must stop. Look at the wording in the question. The question dictates the conditions for which the loop has to be executed which means the wording can be directly translated to condition. However, if the wording is like the loop has to exit when the value of c1 is equal to A and c2 not equal to A, then it needs a bit more effort to arrive at the condition. See the next question. UNISA 2018 8

Sample loop question contd Suppose two char variables c1 and c2 are initialised and then input repeatedly in the body of a while loop. The loop has to exit when the value of c1 is equal to B and the value of c2 is not equal to B. Which of the options below is a correct condition for the while loop? 1. ((c1 == 'B') && (c2!= 'B')) 2. ((c1 == 'B') (c2!= 'B')) 3. ((c1!= 'B') && (c2 == 'B')) 4. ((c1!= 'B') (c2 == 'B')) 5. None of the above options is correct. Correct option: 4 Contrary to the previous question, where the conditions under which the loop must be executed, is described, the conditions under which the loop must exit, are described in this question. The loop must exit when c1 is equal to B and c2 is not equal to B. Therefore, the condition in the loop should be opposite of this. Opposite of (c1 is equal to B ) c1!= B Opposite of (c2 not equal to B) c2 == B Opposite of AND which connects the above two conditions OR Combine all, and you have the answer! UNISA 2018 9

More Topics 1. Variable diagrams; 2. Functions; 3. Data structures (Arrays & Structs); and 4. Two-dimensional arrays; 5. Reference parameters. Thank you to all the students who participated. UNISA 2018 10

1. Variable Diagrams Variable diagrams help in tracing the value stored in each variable as the program executes. In a variable diagram we only show those lines which changes the value of variable(s). For instance, we do not draw diagrams for cout statements. UNISA 2018 11

1. Variable Diagrams- Example The variable diagram should indicate what changes took place in variables. We DO NOT represent every single line of a program in a variable diagram;it is only those lines where a variable is declared and/or changes made to them represented. The most simplified way to work out the variable diagrams is to label the line numbers and substitute the values of the variables as you go along;e.g.: 1. valuep = 6; 2. { 3. a = 2; 4. count= 0; 5. while ( 0 < 6)// count =0; valuep = 6; count = 2; count = 4; //count = 6 then loop exits; 6. { 7. a = a + count +a /2 ; // a = 2 + 0 +(2 /2) = 3; a= 3 +2 +(3/2) = 3 ; a = 3 +4 +3 /2 ; a = 0 +2 /2 ; 8. count = 0 +2; count =2;count =4; count= 6; 9. } 10. return a; //current value of a after line 7 updated 11. } 12. Note: The quality of the past exam papers uploaded on myunisa is very poor. Some of the semicolons are displayed as commas. Consider them as semicolons, especially those at the end of C++ statements. UNISA 2018 12

Solution to previous example UNISA 2018 13

Solution contd UNISA 2018 14

1. Variable Diagrams- Example Solution: You can use variable diagrams to trace the value as it changes. The variable diagram should indicate those lines where changes took place to variable(s). In this question keep in mind that only statements following the condition that is true will execute, not all of them. if(var1 * 2 >= var2) evaluates to if(4 * 2 >= 10). It is false, therefore the control goes to the next else if. There it checks the condition if(var1 < var2) which evaluates to if(4 < 10). The condition is true, therefore the line of statement following this else if will execute and the control will exit the if structure. Therefore after line 3 in the VD, we need to represent only line 7. UNISA 2018 15

2. Functions A function is a piece of code(a group of statements) that executes a particular task. All C++ programs have at least one function in it which is the main(). Two types of functions: built-in functions. eg: abs(), rand(), sqrt() user-defined functions UNISA 2018 16

Functions contd Built-in functions: C++ has built-in functions for which we do not have to write the code. eg: rand(), abs(), sqrt() etc. These functions are already defined in the C++ library. We just have to invoke them through a function call. User-defined functions Users can define their own function. It takes the form: return-type function-name(parameter list) { body of the function; } UNISA 2018 17

3. Data Structures- Arrays & Structs A data structure is a collection of related data values stored under a single name and organised so that the individual values can be accessed separately. Structs are data structures for storing related data values of different types. Arrays are data structures for storing related data values of the same type. UNISA 2018 18

4. Data Structures-2D Arrays Two-dimensional Arrays eg: int arr[2][3]; declares a 2D array arr with two rows and 3 columns. When a 2D array is initialized as follows the first dimension is optional. eg:- int arr[][3] = { {1,2,3}, {4,5,6}}; UNISA 2018 19

Solution to Q 6.2.1 of Oct/Nov 2016 exam paper bool checknumber(const int arr1[size_of_array], int num1, int & pos1) { bool flag = false; //checking the number in the array for(int i=0;i< size_of_array;i++) { if(arr1[i]==num1) { pos1=i; flag=true; } } return flag; } UNISA 2018 20

5. Reference Parameters Reference parameters are used when the values for variables declared in the main function should be updated within other functions. For example, if a function has to change more than one value and if both the values has to be returned to the calling function then we have to use reference parameters (&). UNISA 2018 21

5. Reference Parameters - example Reference parameter variables declared with the ampersand (&). Image placeholder Here, the value of the variable first in the main function is updated. The same happens for the variable second, in the next line. The function twice is called with the two variables that it should updated. The updated variable values after the execution of the function twice will be displayed. UNISA 2018 22

5. Reference Parameter example Code #include <iostream> using namespace std; void twice (int &firstp, int &secondp) { firstp = firstp *2; secondp = secondp * 2; } int main() { int first, second; cout << "Enter the first number to double: "<<endl; cin >> first; cout << "Enter the second number to double :" << endl; cin >> second; twice(first, second); cout << "The first number times two = " << first << endl; cout << "The second number times two = " << second << endl; } return 0; UNISA 2018 23

Sample question Answer is option 3. There is no endl in the first cout statement. Hence the string in the second cout statement will be printed on the same line as the previous string. There is endl in the second cout statement. So the third string will be printed on a newline. UNISA 2018 24

Sample Question [In your past exam papers because of the poor quality, you are seeing commas where it should be semicolon in some places]. The indentation is given just to confuse you. Here x is not greater than 10. so the statement after the if structure will be executed. Output is Low UNISA 2018 25