Passing 1D arrays to functions.

Size: px
Start display at page:

Download "Passing 1D arrays to functions."

Transcription

1 Passing 1D arrays to functions. In C++ arrays can only be reference parameters. It is not possible to pass an array by value. Therefore, the ampersand (&) is omitted. What is actually passed to the function, when an array is the formal parameter, is the base address of the array (the memory address of the first element in the array). This is true whether the array has one or more dimensions. When declaring a 1-D array parameter, the compiler only needs to know that the parameter is an array; it doesn t need to know its size. The complier will ignore it, if it is included. However, inside the function we still need to make sure that only legitimate array elements are referenced. Thus a separate parameter specifying the length of the array must also be passed to the function. int ProcessValues (int [], int ); // works with ANY 1-d array Example: int SumValues (int [], int ); //function prototype void main( ) int Array[10]=0,1,2,3,4,5,6,7,8,9; int total_sum; total_sum = SumValues (Array, 10); //function call cout << Total sum is <<total_sum; int SumValues (int values[], int num_of_values) //function header int sum = 0; for( int i=0; i < num_of_values; i++) sum+=values[i]; return sum; Note that we are using only the name of the array in the function call: Array, not Array[10]. 1

2 Since arrays are always passed by reference, all changes made to the array elements inside the function will be made to the original array. The only way to protect the elements of the array from being inadvertently changed, is to declare an array to be a const parameter. Example: int SumValues (const int [], int); //function prototype int main( ) const int length =10; int Array[10]=0,1,2,3,4,5,6,7,8,9; int total_sum; total_sum = SumValues (Array, length); cout << Total sum is <<total_sum; return 0; //function call int SumValues (const int values[], int num_of_values) //function header int sum = 0; for( int i=0; i < num_of_values; i++) sum+=values[i]; return sum; Since you do not intend to change the values of an array in the above function, make it a const parameter to protect yourself. The original array (in the main) should not be const, or you wouldn t be able to make any changes to it at all. You do not however need to make the length of an array a const parameter, since it is passed by value and any changes to it will not affect the actual parameter. The compiler will not allow you to pass it by reference if it was declared as a const int in the main ( ). 2

3 Passing arrays to functions (examples) 4/9/04 Passing arrays to functions (Examples). //example of passing one-dimensional array to functions int maximum_1_d (int[ ], int); void main() const int size = 5; int nums[size] = 2,18,1,25,3; // 1-D array cout << "The max value of array nums is " << maximum_1_d(nums, size) << endl; int maximum_1_d ( int vals[ ], int number_elements) int i, max = vals[0]; for (i=0; i<number_elements; i++) if (max <vals[i]) max = vals[i]; return max; 1

4 Passing arrays to functions (examples) 4/9/04 // The called function receives access to the actual array, not a copy of the values in the // array. Thus any changes made to the array within the function change the original // array. void change_1_d(int[], int); // function prototype void main() const int size = 5; int i; int nums[size] = 2,18,1,25,3; cout << "The values in array nums before the functions call are "; for (i=0; i<size;i++) cout<<nums[i]<<' '; cout<<endl; change_1_d(nums,size); //function call cout << "The values in array nums after the functions call are "; for (i=0; i<size;i++) cout<<nums[i]<<' '; cout<<endl; void change_1_d(int vals[], int number_elements) //function header int i; // let's try to change the values in vals for (i=0;i<number_elements; i++) vals[i]=i; 2

5 1D Arrays Code example: passing arrays to functions void get_array(int[], int); int calc_sum(int[], int); void display_array(int[], int); void main () int num[1000]; int n; cout << "Enter size of array (must be < 1000):"; cin >> n; int sum; get_array(num, n); cout << endl; display_array(num, n); cout << endl; sum = calc_sum(num, n); cout << "The sum is " << sum << endl; void get_array(int arr[], int size) for (int k = 0; k < size; k++) cout << "Please enter value for arr[" << k << "]:"; cin >> arr[k]; int calc_sum(int arr[], int size) int s = 0; for (int i = 0; i < size; i++) s += arr[i]; return s; void display_array(int arr[], int size) for(int j = 0; j < size; j++) cout << "arr[" << j << "] = " << arr[j] << endl;

6 1 Strings A string literal (or string) is any sequence of characters enclosed in double quotes. In C++ strings of characters are held as an array of characters, one character held in each array element. A special null character, represented by `\0', is appended to the end of the string to indicate the end of the string. Think of it as a sentinel that marks the end of every string. If a string has n characters then it requires an n+1 element array (at least) to store it. Note: \0 is stored by the compiler as a single character. A single character enclosed in double quotes, rather than single quotes, is also viewed by the compiler as a string. Character in single quotes - `a'- is stored in a single byte. Character in double quotes -"a" is stored in two consecutive bytes holding the character `a' and the null character. Examples of strings: o This is a string o xyz 123 *!#@@& o m o A string variable s1 could be declared as follows: char s1[10]; The string variable s1 could hold strings of length up to nine (only 9!!!) characters since space is needed for the final null character. Strings can be initialized at the time of declaration just as other variables are initialized. For example: char s1[] = "example"; char s2[20] = "another example" would store the two strings as follows: s1 e x a m p l e \0 s2 a n o t h e r e x a m p l e \0???? In the first case the array would be allocated space for eight characters, that is space for the seven characters of the string and the null character. In the second case the string is set by the declaration to be twenty characters long but only sixteen of these characters are set, i.e. the fifteen characters of the string and the null character. Note that the length of a string does not include the terminating null character.

7 2 Note: The individual characters in the string can be handled with standard array operations More examples of String Initialization Each of the following declarations produces the same result: char test[5] = abcd ; char test[ ] = abcd ; char test[5] = a, b, c, d, \0 ; char test[ ] = a, b, c, d, \0 ; String Output: A string is output by sending it to an output stream, for example: cout << "The string s1 is " << s1 << endl; would print The string s1 is example String Input (single word) When the input stream cin is used, space characters, newline etc. are used as separators and terminators. Thus when inputting numeric data cin skips over any leading spaces and terminates reading a value when it finds a white-space character (space, tab, newline etc. ). This same system is used for the input of strings, hence a string to be input cannot start with leading spaces, also if it has a space character in the middle then input will be terminated on that space character. The null character will be appended to the end of the string in the character array by the stream functions. If the string s1 was initialized char s1[] = "example"; then the statement cin << s1; would set the string s1 as follows when the string "first" is entered (without the double quotes) f i r s t \0 e \0 Note that the last two elements are a relic of the initialization at declaration time.

8 3 Note: If the string that is entered is longer than the space available for it in the character array then C++ will just write over whatever space comes next in memory. This can cause some very strange errors when some of your other variables reside in that space! String Input (several words, i.e. strings that contain spaces) To read a string with several words in it we can call cin once for each word. A better way is to use cin.getline( ) or cin.get( ) cin.getline( ) continuously accepts and stores characters typed at the terminal into the character array until either the array size is reached or the end-of-string(null, \0) marker is detected. (Note: \n is input when the Enter key is depressed. This character is interpreted by cin.getline( ) as the end-of-line entry. cin.getline( ) inserts the \0 character in place of the \n character at the end of the array.). whereas cin reads entry up to the first blank space or \n, cin.getline( ) accepts whitespace as a character and terminates with \n (or until the array if full). syntax: o cin.getline(string, terminating-length, terminating-character) string a string or character pointer variable terminating-length an integer constant or variable indicating the maximum number of input characters that can be input terminating-character an optional character constant or variable specifying the terminating character if omitted, the default terminating character is the newline ( \n ) character Examples: cin.getline(message, size); cin.getline(message, size, \n ); cin.getline(message, size, x ); the first two functions stop reading characters when the Return key is pressed or until size characters have been read, whichever comes first. The third function continues until size or the character x have been read. cin.get( ) reads in a single character at a time. Will read any character. if you need to read the ENTER key, a space, or the tab key, you cannot use cin. These characters stop cin from reading!!! You must use cin.get because cin.get will read any character. Example: char c1; cin.get(c1) - reads a single character into variable c1

9 Character Arrays and Strings: Worksheet 2 1. What is the difference between character arrays and strings? 2. char my_word[5] = c, l, a, s, s ; a. Is it a character array or a string? Why? b. How can you display it to the screen? 3. char my_word[6] = c, l, a, s, s, \0 ; a. Is it a character array or a string? Why? b. How can you display it to the screen? 4. Given the following declaration: char hello[3] = hi ; a. What is hello[0] = b. What is hello[2] = c. What is hello[3] = d. Adding the following lines: hello[1] = m ; cout << hello; What is displayed on a screen?

10 5. Write a code segment that will prompt the user for his first name and his last name and display to the screen: Hello, first_name last_name. 6. Write a function that will accept two strings and return true if they are equal in length and false if they are not. 7. Write a function that will accept an integer array, its size and a code integer. The function should find the location of that code integer in the array and return it s position (index) in the array or 999 if the code was not found in the array.

11 1D Arrays Code example: manipulating strings int calc_length(char w[]); bool compare_words(char w1[], char w2[]); void main () char word1[81], word2[81]; int word_length1, word_length2; cout << "Enter word 1 (max 80 chars): "; cin >> word; cout << "Enter word 2 (max 80 chars): "; cin >> word; word_length1 = calc_length(word1); word_length2 = calc_length(word2); cout << "Length of word 1 is " << word_length1; cout << "Length of word 2 is " << word_length2; if (compare_words(word1, word2)) cout << "Words are the same"; else cout << "Words are not the same ; cout << endl; int calc_length(char w[]) int len; // continue looping until we bump into the null char for (len = 0; w[len]!= '\0'; len++); return len; bool compare_words(char w1[], char w2[]) int i; // continue looping as long as chars are equal and not null for (i = 0; w1[i]!= '\0' && w2[i]!= '\0' && w1[i] == w2[i]; i++); // the only way that identical words can end the loop is // by both having a null char at the same time: any other // combination means that they are not identical return (w1[i] == '\0' && w2[i] == '\0');

Basics of I/O Streams and File I/O

Basics of I/O Streams and File I/O Basics of This is like a cheat sheet for file I/O in C++. It summarizes the steps you must take to do basic I/O to and from files, with only a tiny bit of explanation. It is not a replacement for reading

More information

What is a Loop? Pretest Loops in C++ Types of Loop Testing. Count-controlled loops. Loops can be...

What is a Loop? Pretest Loops in C++ Types of Loop Testing. Count-controlled loops. Loops can be... What is a Loop? CSC Intermediate Programming Looping A loop is a repetition control structure It causes a single statement or a group of statements to be executed repeatedly It uses a condition to control

More information

The C++ Language. Loops. ! Recall that a loop is another of the four basic programming language structures

The C++ Language. Loops. ! Recall that a loop is another of the four basic programming language structures The C++ Language Loops Loops! Recall that a loop is another of the four basic programming language structures Repeat statements until some condition is false. Condition False True Statement1 2 1 Loops

More information

Answers to Review Questions Chapter 7

Answers to Review Questions Chapter 7 Answers to Review Questions Chapter 7 1. The size declarator is used in a definition of an array to indicate the number of elements the array will have. A subscript is used to access a specific element

More information

9 Control Statements. 9.1 Introduction. 9.2 Objectives. 9.3 Statements

9 Control Statements. 9.1 Introduction. 9.2 Objectives. 9.3 Statements 9 Control Statements 9.1 Introduction The normal flow of execution in a high level language is sequential, i.e., each statement is executed in the order of its appearance in the program. However, depending

More information

Lecture 3. Arrays. Name of array. c[0] c[1] c[2] c[3] c[4] c[5] c[6] c[7] c[8] c[9] c[10] c[11] Position number of the element within array c

Lecture 3. Arrays. Name of array. c[0] c[1] c[2] c[3] c[4] c[5] c[6] c[7] c[8] c[9] c[10] c[11] Position number of the element within array c Lecture 3 Data structures arrays structs C strings: array of chars Arrays as parameters to functions Multiple subscripted arrays Structs as parameters to functions Default arguments Inline functions Redirection

More information

Member Functions of the istream Class

Member Functions of the istream Class Member Functions of the istream Class The extraction operator is of limited use because it always uses whitespace to delimit its reads of the input stream. It cannot be used to read those whitespace characters,

More information

C++ Input/Output: Streams

C++ Input/Output: Streams C++ Input/Output: Streams 1 The basic data type for I/O in C++ is the stream. C++ incorporates a complex hierarchy of stream types. The most basic stream types are the standard input/output streams: istream

More information

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program. Name: Class: Date: Exam #1 - Prep True/False Indicate whether the statement is true or false. 1. Programming is the process of writing a computer program in a language that the computer can respond to

More information

Common Beginner C++ Programming Mistakes

Common Beginner C++ Programming Mistakes Common Beginner C++ Programming Mistakes This documents some common C++ mistakes that beginning programmers make. These errors are two types: Syntax errors these are detected at compile time and you won't

More information

Introduction to Java

Introduction to Java Introduction to Java The HelloWorld program Primitive data types Assignment and arithmetic operations User input Conditional statements Looping Arrays CSA0011 Matthew Xuereb 2008 1 Java Overview A high

More information

13 Classes & Objects with Constructors/Destructors

13 Classes & Objects with Constructors/Destructors 13 Classes & Objects with Constructors/Destructors 13.1 Introduction In object oriented programming, the emphasis is on data rather than function. Class is a way that binds the data & function together.

More information

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement? 1. Distinguish & and && operators. PART-A Questions 2. How does an enumerated statement differ from a typedef statement? 3. What are the various members of a class? 4. Who can access the protected members

More information

Comp151. Definitions & Declarations

Comp151. Definitions & Declarations Comp151 Definitions & Declarations Example: Definition /* reverse_printcpp */ #include #include using namespace std; int global_var = 23; // global variable definition void reverse_print(const

More information

PIC 10A. Lecture 7: Graphics II and intro to the if statement

PIC 10A. Lecture 7: Graphics II and intro to the if statement PIC 10A Lecture 7: Graphics II and intro to the if statement Setting up a coordinate system By default the viewing window has a coordinate system already set up for you 10-10 10-10 The origin is in the

More information

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority) Boolean Expressions, Conditions, Loops, and Enumerations Relational Operators == // true if two values are equivalent!= // true if two values are not equivalent < // true if left value is less than the

More information

Arrays. number: Motivation. Prof. Stewart Weiss. Software Design Lecture Notes Arrays

Arrays. number: Motivation. Prof. Stewart Weiss. Software Design Lecture Notes Arrays Motivation Suppose that we want a program that can read in a list of numbers and sort that list, or nd the largest value in that list. To be concrete about it, suppose we have 15 numbers to read in from

More information

ASCII Encoding. The char Type. Manipulating Characters. Manipulating Characters

ASCII Encoding. The char Type. Manipulating Characters. Manipulating Characters The char Type ASCII Encoding The C char type stores small integers. It is usually 8 bits. char variables guaranteed to be able to hold integers 0.. +127. char variables mostly used to store characters

More information

Chapter One Introduction to Programming

Chapter One Introduction to Programming Chapter One Introduction to Programming 1-1 Algorithm and Flowchart Algorithm is a step-by-step procedure for calculation. More precisely, algorithm is an effective method expressed as a finite list of

More information

Data Structures using OOP C++ Lecture 1

Data Structures using OOP C++ Lecture 1 References: 1. E Balagurusamy, Object Oriented Programming with C++, 4 th edition, McGraw-Hill 2008. 2. Robert Lafore, Object-Oriented Programming in C++, 4 th edition, 2002, SAMS publishing. 3. Robert

More information

While Loop. 6. Iteration

While Loop. 6. Iteration While Loop 1 Loop - a control structure that causes a set of statements to be executed repeatedly, (reiterated). While statement - most versatile type of loop in C++ false while boolean expression true

More information

C++ Outline. cout << "Enter two integers: "; int x, y; cin >> x >> y; cout << "The sum is: " << x + y << \n ;

C++ Outline. cout << Enter two integers: ; int x, y; cin >> x >> y; cout << The sum is:  << x + y << \n ; C++ Outline Notes taken from: - Drake, Caleb. EECS 370 Course Notes, University of Illinois Chicago, Spring 97. Chapters 9, 10, 11, 13.1 & 13.2 - Horstman, Cay S. Mastering Object-Oriented Design in C++.

More information

C++ Programming: From Problem Analysis to Program Design, Fifth Edition. Chapter 3: Input/Output

C++ Programming: From Problem Analysis to Program Design, Fifth Edition. Chapter 3: Input/Output C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 3: Input/Output Objectives In this chapter, you will: Learn what a stream is and examine input and output streams Explore

More information

MS Visual C++ Introduction. Quick Introduction. A1 Visual C++

MS Visual C++ Introduction. Quick Introduction. A1 Visual C++ MS Visual C++ Introduction 1 Quick Introduction The following pages provide a quick tutorial on using Microsoft Visual C++ 6.0 to produce a small project. There should be no major differences if you are

More information

Moving from C++ to VBA

Moving from C++ to VBA Introduction College of Engineering and Computer Science Mechanical Engineering Department Mechanical Engineering 309 Numerical Analysis of Engineering Systems Fall 2014 Number: 15237 Instructor: Larry

More information

CpSc212 Goddard Notes Chapter 6. Yet More on Classes. We discuss the problems of comparing, copying, passing, outputting, and destructing

CpSc212 Goddard Notes Chapter 6. Yet More on Classes. We discuss the problems of comparing, copying, passing, outputting, and destructing CpSc212 Goddard Notes Chapter 6 Yet More on Classes We discuss the problems of comparing, copying, passing, outputting, and destructing objects. 6.1 Object Storage, Allocation and Destructors Some objects

More information

J a v a Quiz (Unit 3, Test 0 Practice)

J a v a Quiz (Unit 3, Test 0 Practice) Computer Science S-111a: Intensive Introduction to Computer Science Using Java Handout #11 Your Name Teaching Fellow J a v a Quiz (Unit 3, Test 0 Practice) Multiple-choice questions are worth 2 points

More information

IS0020 Program Design and Software Tools Midterm, Feb 24, 2004. Instruction

IS0020 Program Design and Software Tools Midterm, Feb 24, 2004. Instruction IS0020 Program Design and Software Tools Midterm, Feb 24, 2004 Name: Instruction There are two parts in this test. The first part contains 50 questions worth 80 points. The second part constitutes 20 points

More information

Compiler Construction

Compiler Construction Compiler Construction Lecture 1 - An Overview 2003 Robert M. Siegfried All rights reserved A few basic definitions Translate - v, a.to turn into one s own language or another. b. to transform or turn from

More information

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas CS 110B - Rule Storage Classes Page 18-1 Attributes are distinctive features of a variable. Data type, int or double for example, is an attribute. Storage class is another attribute. There are four storage

More information

7.7 Case Study: Calculating Depreciation

7.7 Case Study: Calculating Depreciation 7.7 Case Study: Calculating Depreciation 1 7.7 Case Study: Calculating Depreciation PROBLEM Depreciation is a decrease in the value over time of some asset due to wear and tear, decay, declining price,

More information

Appendix K Introduction to Microsoft Visual C++ 6.0

Appendix K Introduction to Microsoft Visual C++ 6.0 Appendix K Introduction to Microsoft Visual C++ 6.0 This appendix serves as a quick reference for performing the following operations using the Microsoft Visual C++ integrated development environment (IDE):

More information

For the next three questions, consider the class declaration: Member function implementations put inline to save space.

For the next three questions, consider the class declaration: Member function implementations put inline to save space. Instructions: This homework assignment focuses on basic facts regarding classes in C++. Submit your answers via the Curator System as OQ4. For the next three questions, consider the class declaration:

More information

6. Control Structures

6. Control Structures - 35 - Control Structures: 6. Control Structures A program is usually not limited to a linear sequence of instructions. During its process it may bifurcate, repeat code or take decisions. For that purpose,

More information

Stacks. Linear data structures

Stacks. Linear data structures Stacks Linear data structures Collection of components that can be arranged as a straight line Data structure grows or shrinks as we add or remove objects ADTs provide an abstract layer for various operations

More information

C++FA 5.1 PRACTICE MID-TERM EXAM

C++FA 5.1 PRACTICE MID-TERM EXAM C++FA 5.1 PRACTICE MID-TERM EXAM This practicemid-term exam covers sections C++FA 1.1 through C++FA 1.4 of C++ with Financial Applications by Ben Van Vliet, available at www.benvanvliet.net. 1.) A pointer

More information

QUIZ-II QUIZ-II. Chapter 5: Control Structures II (Repetition) Objectives. Objectives (cont d.) 20/11/2015. EEE 117 Computer Programming Fall-2015 1

QUIZ-II QUIZ-II. Chapter 5: Control Structures II (Repetition) Objectives. Objectives (cont d.) 20/11/2015. EEE 117 Computer Programming Fall-2015 1 QUIZ-II Write a program that mimics a calculator. The program should take as input two integers and the operation to be performed. It should then output the numbers, the operator, and the result. (For

More information

Chapter 8 Selection 8-1

Chapter 8 Selection 8-1 Chapter 8 Selection 8-1 Selection (Decision) The second control logic structure is selection: Selection Choosing between two or more alternative actions. Selection statements alter the sequential flow

More information

Variables, Constants, and Data Types

Variables, Constants, and Data Types Variables, Constants, and Data Types Primitive Data Types Variables, Initialization, and Assignment Constants Characters Strings Reading for this class: L&L, 2.1-2.3, App C 1 Primitive Data There are eight

More information

Operator Overloading. Lecture 8. Operator Overloading. Running Example: Complex Numbers. Syntax. What can be overloaded. Syntax -- First Example

Operator Overloading. Lecture 8. Operator Overloading. Running Example: Complex Numbers. Syntax. What can be overloaded. Syntax -- First Example Operator Overloading Lecture 8 Operator Overloading C++ feature that allows implementer-defined classes to specify class-specific function for operators Benefits allows classes to provide natural semantics

More information

1. The First Visual C++ Program

1. The First Visual C++ Program 1. The First Visual C++ Program Application and name it as HelloWorld, and unselect the Create directory for solution. Press [OK] button to confirm. 2. Select Application Setting in the Win32 Application

More information

5 Arrays and Pointers

5 Arrays and Pointers 5 Arrays and Pointers 5.1 One-dimensional arrays Arrays offer a convenient way to store and access blocks of data. Think of arrays as a sequential list that offers indexed access. For example, a list of

More information

JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system.

JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system. http://www.tutorialspoint.com/java/java_quick_guide.htm JAVA - QUICK GUIDE Copyright tutorialspoint.com What is Java? Java is: Object Oriented Platform independent: Simple Secure Architectural- neutral

More information

VB.NET Programming Fundamentals

VB.NET Programming Fundamentals Chapter 3 Objectives Programming Fundamentals In this chapter, you will: Learn about the programming language Write a module definition Use variables and data types Compute with Write decision-making statements

More information

Phys4051: C Lecture 2 & 3. Comment Statements. C Data Types. Functions (Review) Comment Statements Variables & Operators Branching Instructions

Phys4051: C Lecture 2 & 3. Comment Statements. C Data Types. Functions (Review) Comment Statements Variables & Operators Branching Instructions Phys4051: C Lecture 2 & 3 Functions (Review) Comment Statements Variables & Operators Branching Instructions Comment Statements! Method 1: /* */! Method 2: // /* Single Line */ //Single Line /* This comment

More information

F ahrenheit = 9 Celsius + 32

F ahrenheit = 9 Celsius + 32 Problem 1 Write a complete C++ program that does the following. 1. It asks the user to enter a temperature in degrees celsius. 2. If the temperature is greater than 40, the program should once ask the

More information

Computer Programming C++ Classes and Objects 15 th Lecture

Computer Programming C++ Classes and Objects 15 th Lecture Computer Programming C++ Classes and Objects 15 th Lecture 엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University Copyrights 2013 Eom, Hyeonsang All Rights Reserved Outline

More information

Sources: On the Web: Slides will be available on:

Sources: On the Web: Slides will be available on: C programming Introduction The basics of algorithms Structure of a C code, compilation step Constant, variable type, variable scope Expression and operators: assignment, arithmetic operators, comparison,

More information

Java Interview Questions and Answers

Java Interview Questions and Answers 1. What is the most important feature of Java? Java is a platform independent language. 2. What do you mean by platform independence? Platform independence means that we can write and compile the java

More information

Lecture 5: Java Fundamentals III

Lecture 5: Java Fundamentals III Lecture 5: Java Fundamentals III School of Science and Technology The University of New England Trimester 2 2015 Lecture 5: Java Fundamentals III - Operators Reading: Finish reading Chapter 2 of the 2nd

More information

Introduction to Programming (in C++) Loops. Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC

Introduction to Programming (in C++) Loops. Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC Introduction to Programming (in C++) Loops Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC Example Assume the following specification: Input: read a number N > 0 Output:

More information

Example. Introduction to Programming (in C++) Loops. The while statement. Write the numbers 1 N. Assume the following specification:

Example. Introduction to Programming (in C++) Loops. The while statement. Write the numbers 1 N. Assume the following specification: Example Introduction to Programming (in C++) Loops Assume the following specification: Input: read a number N > 0 Output: write the sequence 1 2 3 N (one number per line) Jordi Cortadella, Ricard Gavaldà,

More information

java.util.scanner Here are some of the many features of Scanner objects. Some Features of java.util.scanner

java.util.scanner Here are some of the many features of Scanner objects. Some Features of java.util.scanner java.util.scanner java.util.scanner is a class in the Java API used to create a Scanner object, an extremely versatile object that you can use to input alphanumeric characters from several input sources

More information

Arrays in Java. Working with Arrays

Arrays in Java. Working with Arrays Arrays in Java So far we have talked about variables as a storage location for a single value of a particular data type. We can also define a variable in such a way that it can store multiple values. Such

More information

Keywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void

Keywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void 1. Explain C tokens Tokens are basic building blocks of a C program. A token is the smallest element of a C program that is meaningful to the compiler. The C compiler recognizes the following kinds of

More information

Conditions & Boolean Expressions

Conditions & Boolean Expressions Conditions & Boolean Expressions 1 In C++, in order to ask a question, a program makes an assertion which is evaluated to either true (nonzero) or false (zero) by the computer at run time. Example: In

More information

CS106A, Stanford Handout #38. Strings and Chars

CS106A, Stanford Handout #38. Strings and Chars CS106A, Stanford Handout #38 Fall, 2004-05 Nick Parlante Strings and Chars The char type (pronounced "car") represents a single character. A char literal value can be written in the code using single quotes

More information

Chapter 5 Functions. Introducing Functions

Chapter 5 Functions. Introducing Functions Chapter 5 Functions 1 Introducing Functions A function is a collection of statements that are grouped together to perform an operation Define a function Invoke a funciton return value type method name

More information

Sequential Program Execution

Sequential Program Execution Sequential Program Execution Quick Start Compile step once always g++ -o Realtor1 Realtor1.cpp mkdir labs cd labs Execute step mkdir 1 Realtor1 cd 1 cp../0/realtor.cpp Realtor1.cpp Submit step cp /samples/csc/155/labs/1/*.

More information

C++ Language Tutorial

C++ Language Tutorial cplusplus.com C++ Language Tutorial Written by: Juan Soulié Last revision: June, 2007 Available online at: http://www.cplusplus.com/doc/tutorial/ The online version is constantly revised and may contain

More information

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013 Oct 4, 2013, p 1 Name: CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013 1. (max 18) 4. (max 16) 2. (max 12) 5. (max 12) 3. (max 24) 6. (max 18) Total: (max 100)

More information

CS193D Handout 06 Winter 2004 January 26, 2004 Copy Constructor and operator=

CS193D Handout 06 Winter 2004 January 26, 2004 Copy Constructor and operator= CS193D Handout 06 Winter 2004 January 26, 2004 Copy Constructor and operator= We already know that the compiler will supply a default (zero-argument) constructor if the programmer does not specify one.

More information

First Java Programs. V. Paúl Pauca. CSC 111D Fall, 2015. Department of Computer Science Wake Forest University. Introduction to Computer Science

First Java Programs. V. Paúl Pauca. CSC 111D Fall, 2015. Department of Computer Science Wake Forest University. Introduction to Computer Science First Java Programs V. Paúl Pauca Department of Computer Science Wake Forest University CSC 111D Fall, 2015 Hello World revisited / 8/23/15 The f i r s t o b l i g a t o r y Java program @author Paul Pauca

More information

Introduction to Java Applications. 2005 Pearson Education, Inc. All rights reserved.

Introduction to Java Applications. 2005 Pearson Education, Inc. All rights reserved. 1 2 Introduction to Java Applications 2.2 First Program in Java: Printing a Line of Text 2 Application Executes when you use the java command to launch the Java Virtual Machine (JVM) Sample program Displays

More information

Calling the Function. Two Function Declarations Here is a function declared as pass by value. Why use Pass By Reference?

Calling the Function. Two Function Declarations Here is a function declared as pass by value. Why use Pass By Reference? Functions in C++ Let s take a look at an example declaration: Lecture 2 long factorial(int n) Functions The declaration above has the following meaning: The return type is long That means the function

More information

Illustration 1: Diagram of program function and data flow

Illustration 1: Diagram of program function and data flow The contract called for creation of a random access database of plumbing shops within the near perimeter of FIU Engineering school. The database features a rating number from 1-10 to offer a guideline

More information

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner. Handout 1 CS603 Object-Oriented Programming Fall 15 Page 1 of 11 Handout 1 Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner. Java

More information

Chapter 2 Introduction to Java programming

Chapter 2 Introduction to Java programming Chapter 2 Introduction to Java programming 1 Keywords boolean if interface class true char else package volatile false byte final switch while throws float private case return native void protected break

More information

Lecture 22: C Programming 4 Embedded Systems

Lecture 22: C Programming 4 Embedded Systems Lecture 22: C Programming 4 Embedded Systems Today s Goals Basic C programming process Variables and constants in C Pointers to access addresses Using a High Level Language High-level languages More human

More information

JavaScript: Control Statements I

JavaScript: Control Statements I 1 7 JavaScript: Control Statements I 7.1 Introduction 2 The techniques you will learn here are applicable to most high-level languages, including JavaScript 1 7.2 Algorithms 3 Any computable problem can

More information

UEE1302 (1102) F10 Introduction to Computers and Programming

UEE1302 (1102) F10 Introduction to Computers and Programming Computational Intelligence on Automation Lab @ NCTU UEE1302 (1102) F10 Introduction to Computers and Programming Programming Lecture 03 Flow of Control (Part II): Repetition while,for & do..while Learning

More information

The University of Alabama in Huntsville Electrical and Computer Engineering CPE 112 01 Test #4 November 20, 2002. True or False (2 points each)

The University of Alabama in Huntsville Electrical and Computer Engineering CPE 112 01 Test #4 November 20, 2002. True or False (2 points each) True or False (2 points each) The University of Alabama in Huntsville Electrical and Computer Engineering CPE 112 01 Test #4 November 20, 2002 1. Using global variables is better style than using local

More information

Chapter 5. Selection 5-1

Chapter 5. Selection 5-1 Chapter 5 Selection 5-1 Selection (Decision) The second control logic structure is selection: Selection Choosing between two or more alternative actions. Selection statements alter the sequential flow

More information

Lecture 2 Notes: Flow of Control

Lecture 2 Notes: Flow of Control 6.096 Introduction to C++ January, 2011 Massachusetts Institute of Technology John Marrero Lecture 2 Notes: Flow of Control 1 Motivation Normally, a program executes statements from first to last. The

More information

Chapter 2: Elements of Java

Chapter 2: Elements of Java Chapter 2: Elements of Java Basic components of a Java program Primitive data types Arithmetic expressions Type casting. The String type (introduction) Basic I/O statements Importing packages. 1 Introduction

More information

UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming

UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming 1 2 Foreword First of all, this book isn t really for dummies. I wrote it for myself and other kids who are on the team. Everything

More information

C++ INTERVIEW QUESTIONS

C++ INTERVIEW QUESTIONS C++ INTERVIEW QUESTIONS http://www.tutorialspoint.com/cplusplus/cpp_interview_questions.htm Copyright tutorialspoint.com Dear readers, these C++ Interview Questions have been designed specially to get

More information

Building Java Programs

Building Java Programs Building Java Programs Chapter 3 Lecture 3-3: Interactive Programs w/ Scanner reading: 3.3-3.4 self-check: #16-19 exercises: #11 videos: Ch. 3 #4 Interactive programs We have written programs that print

More information

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals 1 Recall From Last Time: Java Program import java.util.scanner; public class EggBasket { public static void main(string[]

More information

Multichoice Quetions 1. Atributes a. are listed in the second part of the class box b. its time is preceded by a colon. c. its default value is

Multichoice Quetions 1. Atributes a. are listed in the second part of the class box b. its time is preceded by a colon. c. its default value is Multichoice Quetions 1. Atributes a. are listed in the second part of the class box b. its time is preceded by a colon. c. its default value is preceded by an equal sign d. its name has undereline 2. Associations

More information

Common Data Structures

Common Data Structures Data Structures 1 Common Data Structures Arrays (single and multiple dimensional) Linked Lists Stacks Queues Trees Graphs You should already be familiar with arrays, so they will not be discussed. Trees

More information

COMPUTER SCIENCE 1999 (Delhi Board)

COMPUTER SCIENCE 1999 (Delhi Board) COMPUTER SCIENCE 1999 (Delhi Board) Time allowed: 3 hours Max. Marks: 70 Instructions: (i) All the questions are compulsory. (ii) Programming Language: C++ QUESTION l. (a) Why main function is special?

More information

Unit 6. Loop statements

Unit 6. Loop statements Unit 6 Loop statements Summary Repetition of statements The while statement Input loop Loop schemes The for statement The do statement Nested loops Flow control statements 6.1 Statements in Java Till now

More information

Programming Languages CIS 443

Programming Languages CIS 443 Course Objectives Programming Languages CIS 443 0.1 Lexical analysis Syntax Semantics Functional programming Variable lifetime and scoping Parameter passing Object-oriented programming Continuations Exception

More information

The if Statement and Practice Problems

The if Statement and Practice Problems The if Statement and Practice Problems The Simple if Statement Use To specify the conditions under which a statement or group of statements should be executed. Form if (boolean-expression) statement; where

More information

Recognizing PL/SQL Lexical Units. Copyright 2007, Oracle. All rights reserved.

Recognizing PL/SQL Lexical Units. Copyright 2007, Oracle. All rights reserved. What Will I Learn? In this lesson, you will learn to: List and define the different types of lexical units available in PL/SQL Describe identifiers and identify valid and invalid identifiers in PL/SQL

More information

The While Loop. Objectives. Textbook. WHILE Loops

The While Loop. Objectives. Textbook. WHILE Loops Objectives The While Loop 1E3 Topic 6 To recognise when a WHILE loop is needed. To be able to predict what a given WHILE loop will do. To be able to write a correct WHILE loop. To be able to use a WHILE

More information

Informatica e Sistemi in Tempo Reale

Informatica e Sistemi in Tempo Reale Informatica e Sistemi in Tempo Reale Introduction to C programming Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa October 25, 2010 G. Lipari (Scuola Superiore Sant Anna)

More information

1 Description of The Simpletron

1 Description of The Simpletron Simulating The Simpletron Computer 50 points 1 Description of The Simpletron In this assignment you will write a program to simulate a fictional computer that we will call the Simpletron. As its name implies

More information

Ch 7-1. Object-Oriented Programming and Classes

Ch 7-1. Object-Oriented Programming and Classes 2014-1 Ch 7-1. Object-Oriented Programming and Classes May 10, 2014 Advanced Networking Technology Lab. (YU-ANTL) Dept. of Information & Comm. Eng, Graduate School, Yeungnam University, KOREA (Tel : +82-53-810-2497;

More information

Introduction to Data Structures

Introduction to Data Structures Introduction to Data Structures Albert Gural October 28, 2011 1 Introduction When trying to convert from an algorithm to the actual code, one important aspect to consider is how to store and manipulate

More information

Subtopics - Functions Function Declaration Function Arguments Return Statements and values. By Hardeep Singh

Subtopics - Functions Function Declaration Function Arguments Return Statements and values. By Hardeep Singh Subtopics - Functions Function Declaration Function Arguments Return Statements and values FUNCTIONS Functions are building blocks of the programs. They make the programs more modular and easy to read

More information

Fondamenti di C++ - Cay Horstmann 1

Fondamenti di C++ - Cay Horstmann 1 Fondamenti di C++ - Cay Horstmann 1 Review Exercises R10.1 Line 2: Can't assign int to int* Line 4: Can't assign Employee* to Employee Line 6: Can't apply -> to object Line 7: Can't delete object Line

More information

Syllabus OBJECT ORIENTED PROGRAMMING C++

Syllabus OBJECT ORIENTED PROGRAMMING C++ 1 Syllabus OBJECT ORIENTED PROGRAMMING C++ 1. Introduction : What is object oriented programming? Why do we need objectoriented. Programming characteristics of object-oriented languages. C and C++. 2.

More information

An Incomplete C++ Primer. University of Wyoming MA 5310

An Incomplete C++ Primer. University of Wyoming MA 5310 An Incomplete C++ Primer University of Wyoming MA 5310 Professor Craig C. Douglas http://www.mgnet.org/~douglas/classes/na-sc/notes/c++primer.pdf C++ is a legacy programming language, as is other languages

More information

Pemrograman Dasar. Basic Elements Of Java

Pemrograman Dasar. Basic Elements Of Java Pemrograman Dasar Basic Elements Of Java Compiling and Running a Java Application 2 Portable Java Application 3 Java Platform Platform: hardware or software environment in which a program runs. Oracle

More information

Embedded SQL. Unit 5.1. Dr Gordon Russell, Copyright @ Napier University

Embedded SQL. Unit 5.1. Dr Gordon Russell, Copyright @ Napier University Embedded SQL Unit 5.1 Unit 5.1 - Embedde SQL - V2.0 1 Interactive SQL So far in the module we have considered only the SQL queries which you can type in at the SQL prompt. We refer to this as interactive

More information

Formatting Numbers with C++ Output Streams

Formatting Numbers with C++ Output Streams Formatting Numbers with C++ Output Streams David Kieras, EECS Dept., Univ. of Michigan Revised for EECS 381, Winter 2004. Using the output operator with C++ streams is generally easy as pie, with the only

More information