CS31 Discussion 1D Winter19: week 4

Slides:



Advertisements
Similar presentations
1 Arrays Chapter 9. 2 Outline  The array structure (Section 9.1)  Array declaration  Array initialization  Array subscripts  Sequential access to.
Advertisements

1 10/29/07CS150 Introduction to Computer Science 1 Reading from and Writing to Files Section 3.12 & 13.1 & 13.5.
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.
Basic Elements of C++ Chapter 2.
C++ Programming Language Day 1. What this course covers Day 1 – Structure of C++ program – Basic data types – Standard input, output streams – Selection.
Section 2 - More Basics. The char Data Type Data type of a single character Example char letter; letter = 'C';
VARIABLES, TYPES, INPUT/OUTPUT, ASSIGNMENT OPERATION Shieu-Hong Lin MATH/CS Department Chapel.
Elements of a C++ program 1. Review Algorithms describe how to solve a problem Structured English (pseudo-code) Programs form that can be translated into.
CSC 107 – Programming For Science. Today’s Goal ALL  Understand why ALL I/O is file I/O  Common bugs to avoid when coding with files in C++  Get a.
Data & Data Types & Simple Math Operation 1 Data and Data Type Standard I/O Simple Math operation.
Current Assignments Homework 3 is due tonight. Iteration and basic functions. Exam 1 on Monday.
CHAPTER 7 DATA INPUT OUTPUT Prepared by: Lec. Ghader R. Kurdi.
CSC1201: Programming Language 2 Lecture 1 Level 2 Course Nouf Aljaffan (C) CSC 1201 Course at KSU1.
Chapter 2: Introduction to C++. Language Elements Keywords Programmer-defined symbols (identifiers) Operators Punctuation Syntax Lines and Statements.
C++ Basics. Compilation What does compilation do? g++ hello.cpp g++ -o hello.cpp hello.
CS Class 03 Topics  Sequence statements Input Output Assignment  Expressions Read pages Read pages 40 – 49 for next time.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays.
Arrays.
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.
DCT1063 Programming 2 CHAPTER 3 STRINGS Mohd Nazri Bin Ibrahim Faculty of Computer, Media & Technology TATi University College
Computer Programming Arrays 1. Question #1 2 Question Choose the correct answer..
A Sample Program #include using namespace std; int main(void) { cout
Arrays An array is a sequence of objects all of which have the same type. The objects are called the elements of the array and are numbered consecutively.
Objectives You should be able to describe: One-Dimensional Arrays
C LANGUAGE UNIT 3. UNIT 3 Arrays Arrays – The concept of array – Defining arrays – Initializing arrays.
String in C++. 2 Using Strings in C++ Programs String library or provides functions to: - manipulate strings - compare strings - search strings ASCII.
A FIRST BOOK OF C++ CHAPTER 7 ARRAYS. OBJECTIVES In this chapter, you will learn about: One-Dimensional Arrays Array Initialization Arrays as Arguments.
Looping I (while statement). CSCE 1062 Outline  Looping/repetition construct  while statement (section 5.1)
Lecture 3: Getting Started & Input / Output (I/O)
ARRAYS.
Array in C# Array in C# RIHS Arshad Khan
Review 1.
Chapter Topics The Basics of a C++ Program Data Types
CS31 Discussion Jie(Jay) Wang Week6 Nov.4.
Topic Pre-processor cout To output a message.
2008/11/19: Lecture 18 CMSC 104, Section 0101 John Y. Park
CS31 Discussion 1E Jie(Jay) Wang Week5 Oct.27.
Computing Fundamentals
Basic Elements of C++.
Chapter 2 Assignment and Interactive Input
Programming fundamentals 2 Chapter 1:Array
Introduction to C++ October 2, 2017.
Multi-dimensional Array
Arrays in C.
C++ Arrays.
Basic Elements of C++ Chapter 2.
CS 1430: Programming in C++ Turn in your Quiz1-2 No time to cover HiC.
Programming Funamental slides
Screen output // Definition and use of variables
Data type List Definition:
Arrays November 8, 2017.
String What it is Why it’s useful
Arrays an array of 5 ints is filled with 3,2,4,1,7
ECE 103 Engineering Programming Chapter 25 C Strings, Part 1
Arrays Arrays A few types Structures of related data items
Reading from and Writing to Files
Using string type variables
CS 144 Advanced C++ Programming February 12 Class Meeting
CS31 Discussion 1D Winter19: week 3
CS31 Discussion 1H Fall18: week 6
2008/11/19: Lecture 18 CMSC 104, Section 0101 John Y. Park
CS31 Discussion 1D Fall18: week 2
Chapter 1 c++ structure C++ Input / Output
CS31 Discussion 1H Fall18: week 3
CS31 Discussion 1H Fall18: week 1
CS31 Discussion 1H Winter19: week 1
cout << str1;  pear
Dr. Khizar Hayat Associate Prof. of Computer Science
Reading from and Writing to Files
Presentation transcript:

CS31 Discussion 1D Winter19: week 4 TA: Behnam Shahbazi bshahbazi@cs.ucla.edu Credit to former TAs: Chelsea Ju and Bo-Jhang Ho

Good coding style guideline (5) Don’t declare two variables whose lifecycles are overlapped

Variable lifecycle Does it compile? int main() { if (100 < 150) { int a = 0; if (6 * 7 < 8) { a = 1; if (9 + 10 < -11) a = 2; } a = 3; } a = 4; return 0; } Does it compile?

Variable lifecycle Does it compile then? int main() { int a = 0; if (100 < 150) { int a = 1; if (6 * 7 < 888) { a = 2; } } cout << a << endl; return 0; } Does it compile then?

Variable lifecycle Does it compile then? What’s the output? int main() { int a = 0; if (100 < 150) { int a = 1; if (6 * 7 < 888) { a = 2; } } cout << a << endl; return 0; } Does it compile then? What’s the output?

Variable lifecycle Does it compile then? What’s the output? int main() { int a = 0; if (100 < 150) { int a = 1; if (6 * 7 < 888) { a = 2; } } cout << a << endl; return 0; } Does it compile then? What’s the output?

Why function? Save repeating codes Make the main function more compact

Function Can we write a function which exchange the values of two variables? void swap(int x, int y) { //TODO: how to do this? } int main() { int a = 3; int b = 6; swap(a, b); // Hope a = 6, b = 3 now return 0; }

Reference We can use reference (& after the data type) to achieve the task void swap(int &x, int &y) { int t = x; x = y; y = t; } int main() { int a = 3; int b = 6; swap(a, b); cout << "a=" << a << ", b=" << b << endl; // Hope a = 6, b = 3 now return 0; } x, y are going to control a, b

Have you done the exercise? * ** *** **** ***** * ** *** **** ***** Done! ***** **** *** ** * ***** **** *** ** *

New challenges! * *** ***** *** ***** ******* ***** ******* ********* *********** ********* *********** ************* *** *** * *** ***** ******* ********* *********** *************

Global variable Global variables are those variables declared beyond any functions #include <iostream> int a; void increase() { a++; } int main() { a = 5; increase(); cout << a << endl; return 0; } What’s the output?

Global variable Using global variables is discouraged That is, if there’s a way to avoid global variables, remove them It is because every function can change global variables. It’s hard to trace why and how the values are changed.

Array Array is for storing a sequence of elements Array declaration: string apple[100]; Type name[size] Access an element by index: apple[3]; Note the range can only be 0 to N-1 if there are N elements

Array

Array What is the output? int main() { int scores[5]; scores[0] = 10000; scores[1] = 2000; scores[2] = 300; scores[3] = 40; scores[4] = 5; cout << "Sum=" << (scores[0] + scores[1] + scores[2] + scores[3] + scores[4]) << endl; return 0; } What is the output?

Array Getting interactive int main() { int scores[5]; cout << "Enter student 1's score: "; cin >> scores[0]; cout << "Enter student 2's score: "; cin >> scores[1]; cout << "Enter student 3's score: "; cin >> scores[2]; cout << "Enter student 4's score: "; cin >> scores[3]; cout << "Enter student 5's score: "; cin >> scores[4]; cout << "Sum=" << (scores[0] + scores[1] + scores[2] + scores[3] + scores[4]) << endl; return 0; } Getting interactive

Array Save the repetitions in input section by a loop int main() { int scores[5]; for (int i = 0; i < 5; i++) { cout << "Enter student " << (i+1) << "'s score: "; cin >> scores[i]; } cout << "Sum=" << (scores[0] + scores[1] + scores[2] + scores[3] + scores[4]) << endl; return 0; } Save the repetitions in input section by a loop

Array Save the repetitions in input section by a loop int main() { int scores[5]; for (int i = 0; i < 5; i++) { cout << "Enter student " << (i+1) << "'s score: "; cin >> scores[i]; } int sum = 0; for (int i = 0; i < 5; i++) sum += scores[i]; cout << "Sum=" << sum << endl; return 0; } Save the repetitions in input section by a loop Further use a loop to simplify the processing section

Array If the index in an array is not within the valid range, the behavior is undefined For example, a[-1] = 999; However, sometimes the problem is not that simple: #include <iostream> int main() { int arr[10]; int a = 2; int b = 3; int x = a * b - 7; arr[x] = 1000; return 0; }

Array If the index in an array is not within the valid range, the behavior is undefined For example, a[-1] = 999; However, sometimes the problem is not that simple: C++ doesn’t check the boundary for you. It will run silently. And it will screw the memory (how?) That’s why this is one of the most annoying bugs int a = 2; int b = 3; int x = a * b - 7; arr[x] = 1000;

Array – zero-indexed From the explanation of how a program accesses the memory through an array, does it give you any hint why C++ array is zero-indexed?

Array – dimensionality What can be the example of 1D-array? E.g., int score[100]; What can be the example of 2D-array? E.g., int color[100][100]; How about a 3D-array? How about an N-D-array?

String / character array How do I print “Hello” on the screen if single-quote and double-quote are not invented?

String / character array How do I print “Hello” on the screen if single-quote and double-quote are not invented?

String / character array How do I print “Hello” on the screen if single-quote and double-quote are not invented? #include <stdio.h> int main() { char str[6]; str[0] = 72; str[1] = 101; str[2] = 108; str[3] = 108; str[4] = 111; str[5] = 0; printf("%s", str); return 0; }

String / character array How do I print “Hello” on the screen if single-quote and double-quote are not invented? #include <stdio.h> int main() { char str[6]; str[0] = 'H'; str[1] = 'e'; str[2] = 'l'; str[3] = 'l'; str[4] = 'o'; str[5] = 0; printf("%s", str); return 0; }

String / character array How do I print “Hello” on the screen if single-quote and double-quote are not invented? #include <stdio.h> int main() { char str[6]; str[0] = 'H'; str[1] = 'e'; str[2] = 'l'; str[3] = 'l'; str[4] = 'o'; str[5] = '\0'; printf("%s", str); return 0; }

String / character array How do I print “Hello” on the screen if single-quote and double-quote are not invented? #include <stdio.h> int main() { char str[6] = "Hello"; printf("%s", str); return 0; }

String / character array How do I print “Hello” on the screen if single-quote and double-quote are not invented? #include <iostream> using namespace std; int main() { string str = "Hello"; cout << str; return 0; }

String / character array Change characters in a string #include <iostream> using namespace std; int main() { string str = "HELLO"; str[1] = '3'; str[4] = '0'; cout << str; return 0; }

String / character array Double quotes are strings (“12345”) What are single quotes (‘a’, ‘3’, ‘@’)? Treat them as a symbol for numbers ‘a’ is 97 ‘3’ is 51 ‘@’ is 40

String / character array Double quotes are strings (“12345”) What are single quotes (‘a’, ‘3’, ‘@’)? Treat them as a symbol for numbers ‘a’ is 97 ‘3’ is 51 ‘@’ is 40 That’s why ‘12’ are invalid – no such symbol! Escaped characters: ‘\n’ newline ‘\t’ tab ‘\0’ null character ‘\a’ used to be beep sound ‘\\’ a back-slash character

Puzzle 2 (warm-up) int main() { int a = 25 + 'Z'; cout << a; }

Puzzle 2 int main() { int a = '-'-'-'; cout << a; }