Local and Global Variables

Similar documents
Function. Mathematical function and C+ + function. Input: arguments. Output: return value

Lab Instructor : Jean Lai

do { statements } while (condition);

Other operators. Some times a simple comparison is not enough to determine if our criteria has been met.

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.

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

EP241 Computing Programming

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

Programming Language. Functions. Eng. Anis Nazer First Semester

A SHORT COURSE ON C++

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

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

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

Exam 2. CSI 201: Computer Science 1 Fall 2016 Professors: Shaun Ramsey and Kyle Wilson. Question Points Score Total: 80

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

Ch 6. Functions. Example: function calls function

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

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

UEE1302(1066) F12: Introduction to Computers and Programming Function (II) - Parameter

1 Unit 8 'for' Loops

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

Introduction to Programming EC-105. Lecture 2

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

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

C++ basics Getting started with, and Data Types.

Basic memory model Using functions Writing functions. Basics Prototypes Parameters Return types Functions and memory Names and namespaces

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

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

EP578 Computing for Physicists

CMPS 221 Sample Final

Fundamentals of Programming CS-110. Lecture 2

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

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

4. C++ functions. 1. Library Function 2. User-defined Function

Week 3. Function Definitions. Example: Function. Function Call, Return Statement. Functions & Arrays. Gaddis: Chapters 6 and 7.

Object-oriented Programming for Automation & Robotics Carsten Gutwenger LS 11 Algorithm Engineering

University of Dublin

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

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

CSCE 206: Structured Programming in C++

C++ Programming Lecture 1 Software Engineering Group

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

Week 4 EECS 183 MAXIM ALEKSA. maximal.io

CSCE Practice Midterm. Data Types

C++ for Everyone, 2e, Cay Horstmann, Copyright 2012 John Wiley and Sons, Inc. All rights reserved. Using a Debugger WE5.

Study Guide for Test 2

Laboratory 0 Week 0 Advanced Structured Programming An Introduction to Visual Studio and C++

Getting started with C++ (Part 2)

Introduction to Programming

Unit 6. Thinking with Functions

CSCE Practice Midterm. Data Types

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:

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

Problem Solving: Storyboards for User Interaction

Scientific Computing

Subprograms. Introduction to Programming (in C++) Subprograms: procedures and functions. Subprograms. Subprograms. Functions are defined as follows:

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

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

Why Is Repetition Needed?

6.1. Chapter 6: What Is A Function? Why Functions? Introduction to Functions

Week 3. Function Definitions. Example: Function. Function Call, Return Statement. Functions & Arrays. Gaddis: Chapters 6 and 7. CS 5301 Spring 2018

Computer Science II Lecture 1 Introduction and Background

Functions. CS111 Lab Queens College, CUNY Instructor: Kent Chin

Review. Modules. CS 151 Review #6. Sample Program 6.1a:

BITG 1113: Function (Part 2) LECTURE 5

Binomial pricer (1.1)

Week 2: Console I/O and Operators Arithmetic Operators. Integer Division. Arithmetic Operators. Gaddis: Chapter 3 (2.14,3.1-6,3.9-10,5.

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:

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;

C++ For Science and Engineering Lecture 12

SOLUTIONS TO EXERCISES PART ONE: Problem-Solving Techniques

Lecture 7: General Loops (Chapter 7)

Midterm Practice TA: Brian Choi Section Webpage:

CS 31 Discussion 1A, Week 4. Zengwen Yuan (zyuan [at] cs.ucla.edu) Humanities A65, Friday 10:00 11:50 a.m.

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

Computer Programming

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

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

CSc Introduc/on to Compu/ng. Lecture 8 Edgardo Molina Fall 2011 City College of New York

Designing Loops and General Debug Pre-Defined Functions in C++ CS 16: Solving Problems with Computers I Lecture #6

Chapter 17 - Notes Recursion

Functions. Lecture 6 COP 3014 Spring February 11, 2018

Lecture 23: Pointer Arithmetic

Building on the foundation. Now that we know a little about cout cin math operators boolean operators making decisions using if statements

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

Chapter Five: Functions. by Cay Horstmann Copyright 2018 by John Wiley & Sons. All rights reserved

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

Compiling with Multiple Files The Importance of Debugging CS 16: Solving Problems with Computers I Lecture #7

CIS 130 Exam #2 Review Suggestions

The following is a typical execution run of this program:

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

PIC 10A Flow control. Ernest Ryu UCLA Mathematics

CSci 1113 Final. Name: Student ID:

CS 101 Computer Programming and utilization. Dr Deepak B Phatak Subrao Nilekani Chair Professor Department of CSE, Kanwal Rekhi Building IIT Bombay

Topics. Functions. Functions

EECS402 Lecture 02. Functions. Function Prototype

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

o Counter and sentinel controlled loops o Formatting output o Type casting o Top-down, stepwise refinement

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

Module Contact: Dr Pierre Chardaire, CMP Copyright of the University of East Anglia Version 1

Transcription:

Lecture 10

Local and Global Variables Nearly every programming language has a concept of local variable. As long as two functions mind their own data, as it were, they won t interfere with each other. Ex. i in prime function and i in main function are not same! Why global variables? Global variables are often the best way to communicate information between functions.

Global Variables #include <iostream> #include <cmath> using namespace std; int status = 0; // global variable status void main () { //

prime again Use a global variable divisor to return divisor if n is not a prime. int divisor =0; // global a variable bool prime(int n){ if (n<0) n=-n; // to handle negative number. if (n==1) {divisor=1; return false; //extra code for 1. for(int i=2;i<=sqrt(n);i++){ if(n%i==0) {divisor=i; return false; return true;

prime again #include <iostream> #include <cmath> using namespace std; int divisor =0; //global variable bool prime(int n); //declare. int main() { int i; while (true) { cout << "Enter num (0 = exit) and press ENTER: ; cin >> i; if (i == 0) break; if (prime(i)) cout << i << " is prime" << endl; else cout << i << " is not prime since " <<i<<"="<<divisor<<"*"<<i/divisor<< endl; return 0;

Declaring variables in a block Where we declare a variable in our C++ program, inherently determine where this variable would be accessible. A block of code is defined as code inside { If statements, while loop, for loop, are usually follow by a block of code. If the variable is declared in the block, it can t be accessed anywhere else.

Example of block declaration while(c<10){ for( int i =0; i<10; i++) cout<< i; cout<< i; int i = 0 cout<< i; c++ cout << i;

Declaring variables in a function A variable defined in a function is contained with in the function block of code. This means that you can not share variables between functions. Each function needs to be self sufficient in terms of declaring variables that it needs. OR The variable must be pass into the function as a parameter.

Passing variables as arguments When we pass variable as an argument from main function to a sub function Only the value of the variable is passed through That is why we can give the variable a different name That is also why whatever changes we do to this new, different variable wouldn t affect main program.

Example of Passing variables by value #include <iostream> using namespace std; double avg(double, double); int main() { double a = 1.2; double b = 2.7; cout << "Avg is " << avg(a,b); double avg(double x, double y){ double v = (x + y)/2; return v; #include <iostream> using namespace std; void print_results(double a, double b); double avg(double x, double y); int main() { double a = 1.2, b=2.7; print_results(a, b); return 0; void print_results(double a, double b) { cout << "Average is: " << avg(a, b) << endl; double avg(double x, double y) { double v = (x + y)/2; return v;

Pass by value Everything we have done so far is pass by value The value with in the variable is pass to the sub function The sub-function will take the value and store in a variable within its own scope The variable with the value is discarded when it runs out of scope(in the sub-function)

How can we keep the change? One way is to return the newly calculated value to the calling function Then assign the value to the same variable, effectively updating it However there is another way to do it in c++

Passing variables by reference Instead of giving a copy of the value to the sub function, we can give the reference of the value. When we give the reference of the value, the sub function would be able to change the value. Reference is another name referring to the location where the value is stored.

Example Passing variables by value #include <iostream> using namespace std; void update(int); int main() { int n = 100; cout<< Value of n:"<< n <<endl; update(n); cout<< Value of new n: "<< n<<endl; return 0; void update(int n) { cout<< IN UPDATE:Value of n:"<<n<<endl; n =0; cout<< IN UPDATE:Value of n again:"<<n<<endl; Passing by reference #include <iostream> using namespace std; void update(int&) int main() { int n =100; cout<< Value of n:"<<n<<endl; update(n); cout<< Value of new n:"<<n<<endl; return 0; void update(int &n) { cout<< IN UPDATE:Value of n:"<<n <<endl; n= 0; cout<< IN UPDATE:Value of n again:"<<n<<endl;

Other Uses Passing by reference would also come in handy if you need to read in a set of inputs from the user and you don t want to write a function to read in one at a time. Example void getthreevalue(int &a,int &b,int &c) { cout<< "Enter a, b, c: "; cin >>c >> b>> c;

Exercise What is the output of this program? Answer:??? #include <iostream> void sss(int,int &,int &); void mmm(int,int &,int &); using namespace std; int main () { int x = 2, y = 3, z = 3; sss (x, y, z); cout << x << " " << y << " " << z<<endl; sss (y, z, x); //note the order of the variables cout << x << " " << y << " " << z<<endl; mmm (y, z, x); //note the order of the variables cout << x << " " << y << " " << z << endl; return 0; void sss (int a, int &e, int &c) { a = e + 1; c = 4 + a; e = 9; void mmm (int e, int &c, int &a) { e = 11; a = e;

Exercise Exercise 2: Write a function named print_out that prints all the whole numbers from 1 to N. Test the function by placing it in a program that passes a number n to print_out, where this number is entered from the keyboard. The print_out function should have type void; it does not return a value. The function can be called with a simple statement: print_out(n); Exercise 3: Write a function do primetest. Exercise 4: Optimize the prime-number function by calculating the square root of n only once during each function call. Declare a local variable sqrt_of_n of type double. (Hint: A variable is local if it is declared inside the function.) Then use this variable in the loop condition.

Homework 7 Due one week from today Question 1: Ask user enter an integer, and print all the prime numbers less than user input integer. User enter integer: 10 prime number less than 10: 2, 3, 5, 7 Question 2: Ask user enter an integer n, and print 1 1, 2 2,3 3..n n. (use long int here, and for loop, do not use pow() function) Question 3: Use nested for loops to write a n x n multiplication table. User enter integer: 5 1 2 3 4 5 1 1 2 3 4 5 2 2 4 6 8 10 3 3 6 9 12 15 4 4 8 12 16 20 5 5 10 15 20 25