CSC 270 – Survey of Programming Languages C++ Lecture 1 : C++ As A Better C.

Slides:



Advertisements
Similar presentations
C++ Basics March 10th. A C++ program //if necessary include headers //#include void main() { //variable declaration //read values input from user //computation.
Advertisements

CPS120: Introduction to Computer Science INPUT/OUTPUT.
Lecture 2 Introduction to C Programming
Computer Programming Basics Assistant Professor Jeon, Seokhee Assistant Professor Department of Computer Engineering, Kyung Hee University, Korea.
Introduction to C Programming
Introduction to C++ Programming. A Simple Program: Print a Line of Text // My First C++ Program #include int main( ) { cout
Principles of Programming Fundamental of C Programming Language and Basic Input/Output Function 1.
Computer Science 1620 Loops.
1 Lecture-4 Chapter 2 C++ Syntax and Semantics, and the Program Development Process Dale/Weems/Headington.
Chapter 5: Control Structures II (Repetition)
1 9/1/06CS150 Introduction to Computer Science 1 What Data Do We Have? CS 150 Introduction to Computer Science I.
Introduction to Computer Programming Looping Around Loops I: Counting Loops.
Simplest program and Data Output Sen Zhang. The simplest program looks like a single person company! void main() { // this starts a comment line // here.
1 September 6, 2005CS150 Introduction to Computer Science I What Actions Do We Have Part 1 CS150 Introduction to Computer Science I.
Introduction to Computer Programming Loops N Decisions If/Else Counting Loops.
Computer Science 1620 Programming & Problem Solving.
1 Lecture 7 Chapter 3 Numeric Types, Expressions, and Output Dale/Weems/Headington.
Introduction To C++ Programming 1.0 Basic C++ Program Structure 2.0 Program Control 3.0 Array And Structures 4.0 Function 5.0 Pointer 6.0 Secure Programming.
Basic Elements of C++ Chapter 2.
© Janice Regan, CMPT 128, Sept CMPT 128: Introduction to Computing Science for Engineering Students C++ Basic Input and output.
Program A computer program (also software, or just a program) is a sequence of instructions written in a sequence to perform a specified task with a computer.
1 Programs Composed of Several Functions Syntax Templates Legal C++ Identifiers Assigning Values to Variables Declaring Named Constants String Concatenation.
Week 1 Algorithmization and Programming Languages.
Chapter 3 Assignment, Formatting, and Interactive Input C++ for Engineers and Scientists Third Edition.
C++ Programming: Basic Elements of C++.
Introduction to C++ Version 1.1. Topics C++ Structure Primitive Data Types I/O Casting Strings Control Flow.
Chapter 4: Subprograms Functions for Problem Solving Mr. Dave Clausen La Cañada High School.
C++ Basics C++ is a high-level, general purpose, object-oriented programming language.
I/O and Data Formatting Introduction to Class Concepts INFSY 307 Spring 2003 Lecture 3.
Chapter 3 Arithmetic Expressions, Function Calls, and Output
Input/Output Sujana Jyothi C++ Workshop Day 2. C++ I/O Basics 2 I/O - Input/Output is one of the first aspects of programming that needs to be mastered:
Chapter 3: Assignment, Formatting, and Interactive Input.
C++ for Engineers and Scientists Second Edition Chapter 3 Assignment, Formatting, and Interactive Input.
CPS120: Introduction to Computer Science Formatted I/O.
1 Chapter 2 C++ Syntax and Semantics, and the Program Development Process.
CHAPTER 2 PART #3 C++ INPUT / OUTPUT 1 st Semester 1436 King Saud University College of Applied studies and Community Service CSC1101 By: Fatimah Alakeel.
CHAPTER 2 PART #3 C++ INPUT / OUTPUT 1 st Semester King Saud University College of Applied studies and Community Service CSC1101 By: Fatimah.
1 CS161 Introduction to Computer Science Topic #4.
Structured Programming (4 Credits) HNDIT Week 2 – Learning Outcomes Design an algorithmic solution for simple problem such as computation of a factorial,
Programming Fundamentals. Summary of previous lectures Programming Language Phases of C++ Environment Variables and Data Types.
CS1201: PROGRAMMING LANGUAGE 2 FUNCTIONS. OVERVIEW What is a Function? Function Prototype Vs Decleration Highlight Some Errors in Function Code Parameters.
PROGRAM ESSENTIALS. TOKENS  SMALLEST UNITS OF A PROGRAM LANGUAGE  Special Symbols  Mathematical Operators  Punctuation  Word Symbols  Key Words.
Chapter 3 Assignment, Formatting, and Interactive Input C++ for Engineers and Scientists Third Edition.
1 Manipulators manipulators are used only in input and output statements endl, fixed, showpoint, setw, and setprecision are manipulators that can be used.
EEL 3801 C++ as an Enhancement of C. EEL 3801 – Lotzi Bölöni Comments  Can be done with // at the start of the commented line.  The end-of-line terminates.
Objective Write simple computer program in C++ Use simple Output statements Become familiar with fundamental data types.
 2003 Prentice Hall, Inc. All rights reserved Basics of a Typical C++ Environment C++ systems –Program-development environment –Language –C++
1 Lecture 2 - Introduction to C Programming Outline 2.1Introduction 2.2A Simple C Program: Printing a Line of Text 2.3Another Simple C Program: Adding.
COMP 2710 Software Construction C++ Basics 2 and Exercises Dr. Xiao Qin Auburn University These slides.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 3: Input/Output Samples.
C++ Basics Lecture 2.
Chapter 1.2 Introduction to C++ Programming
C++ Basic Input and Output (I/O)
Chapter 1.2 Introduction to C++ Programming
Chapter 1.2 Introduction to C++ Programming
What Actions Do We Have Part 1
Chapter 2 Introduction to C++ Programming
Chapter 1.2 Introduction to C++ Programming
CPS120: Introduction to Computer Science
CPS120: Introduction to Computer Science
Basics (Variables, Assignments, I/O)
Chapter 2 part #3 C++ Input / Output
Functions A function is a “pre-packaged” block of code written to perform a well-defined task Why? Code sharing and reusability Reduces errors Write and.
CS150 Introduction to Computer Science 1
Programs written in C and C++ can run on many different computers
What Actions Do We Have Part 1
Chapter 2 part #3 C++ Input / Output
C++ for Engineers and Scientists Second Edition
Introduction to Programming - 1
Chapter 1 c++ structure C++ Input / Output
Presentation transcript:

CSC 270 – Survey of Programming Languages C++ Lecture 1 : C++ As A Better C

A First Program #include using namespace std; intmain(void) { cout << "This is my first C++ program.“ << endl; return(0); } statements header open and close braces mark the beginning and end makes input and output available to us

Average3.cpp #include using namespace std; intmain(void) { intvalue1, value2, value3; floatsum, average; cout << "What is the first value? "; cin >> value1; // for comments cout << "What is the second value? "; cin >> value2;

cout << "What is the third value? "; cin >> value3; sum = value1 + value2 + value3; average = sum / 3; cout << "Average = " << average << endl; return(0); }

Comments Our program is a bit longer than our previous programs and if we did not know how to calculate gross pay, we might not be able to determine this from the program alone. It is helpful as programs get much longer to be able to insert text that explains how the program works. These are called comments. Comments are meant for the human reader, not for the computer. In C++, anything on a line after a double slash ( // ) is considered a comment.

A program that uses a character variable #include using namespace std; // A very polite program that greets you by name intmain(void) { stringname; cout << "What is your name?\t"; cin >> name; cout << "Pleased to meet you, " << name << endl; return (0); }

Formatting float output in C++ cout and cin are examples of what are called stream input/output. Stream I/O uses a set of built-in values called format flags to determine how data is printed. We can changes these values by using setf(). For now, we will use it only to reformat float values.

setf and the ios flags When we wish to ensure that float is printed with a fixed decimal point and a certain number of decimal places we place: cout.setf(ios::showpoint); cout.setf(ios::fixed); cout.precision(2); Guarantees that trailing zeros appear Gives us two decimal places Float numbers are always written in regular notation (not scientific notation)

the width flag Every time we wish a number to be printed and to take up a fixed amount of place (not merely what it needs), we write: cout.width(15); This assures that the item being printed will occupy 15 spaces. Unlike the other flags changes that remain in effect once you call them, width must be reset each time you use it.

Changing the width NumberFormattingPrint as: 182 cout.width(2) 182 cout.width(3) 182 cout.width(5) `` cout.width(7) `` cout.width(4) -182 cout.width(5) ` cout.width(7) ```-182

Changing the width (continued) NumberFormattingPrint as: 23cout.width(1)23 cout.width(2)23 cout.width(6)….23 23cout.width(8)…… cout.width(4)11023 cout.width(6) cout.width(6) cout.width(10)…

Changing the precision NumberWidthPrecisionPrints as: cout.width(8) cout.precision(5);` cout.width(8) cout.precision(3);``` cout.width(8) cout.precision(2);```` cout.width(8) cout.precision(0);```````` cout.width(13) cout.precision(11); cout.width(12) cout.precision(11);

The revised Compound program #include using namespace std; //Calculate the interest that the Canarsie //Indians could have accrued if they had //deposited the $24 in an bank account at //5% interest. intmain(void) { const intpresent = 2000; intyear; const floatrate = 0.05; floatinterest, principle; //Set the initial principle at $24 principle = 24;

// For every year since 1625, add 5% //interest to the principle and print //out the principle //There has to be two fixed places for //the principle cout.setf(ios::showpoint); cout.setf(ios::fixed); cout.precision(2);

for (year = 1625; year < present; year++){ interest = rate * principle; principle = principle + interest; cout << "year = " << year ; // Use 15 places for printing the principle cout << "\tprinciple = "; cout.width(15); cout << principle << endl; } return(0); }

exit() exit() allows the user to let a program terminate if the program detects an unrecoverable error. The statement #include has to be included. A non-zero status value should be returned when the program terminates abnormally.

What Are References Parameters? Reference parameters do not copy the value of the parameter. Instead, they give the function being called a copy of the address at which the data is stored. This way, the function works with the original data. We call this passing by reference because we are making references to the parameters.

Rewriting power We can make the power function tell the main program about the change in y by placing am ampersand ( & ) between the data type and variable name: void power (float &y, float x, int n) { … … … }

power.cpp rewritten #include using namespace std; void power(float &y, float x, int n); // A program to calculate 4-cubed using a // function called power int main(void) { floatx, y; int n; x = 4.0; n = 3; y = 1.0; power(y, x, n); cout << "The answer is " << y << endl; }

// power() - Calculates y = x to the nth power void power(float &y, float x, int n) { y = 1.0; while (n > 0) { y = y * x; n = n - 1; } cout << "Our result is " << y << endl; }

// Find the average of three numbers using a // function int main(void) { int value1, value2, value3; float mean; //Get the inputs getvalue(value1); getvalue(value2); getvalue(value3); // Call the function that calculates the average // and then print it mean = find_average(value1, value2, value3); cout << "The average is " << mean << endl; }

// getvalue() - Input an integer value void getvalue(int &x) { cout << "Enter a value ?"; cin >> x; } // find_average() - Find the average of three // numbers float find_average(int x, int y, int z) { float sum, average; sum = (float) (x + y + z); average = sum / 3; return average; }

Enumeration Constants in C Instead of writing #defineNO0 #defineYES1 we can write enumboolean {NO, YES}; The first value is defined as 0, and each subsequent value is one greater, unless we explicitly state a value. enum escapes {BELL = '\a', BACKSPACE = '\b', TAB = '\t', NEWLINE = '\n', VTAB = '\v'}; enum months {JAN = 1, FEB, MAR, APR, MAY, JUN, JUL,AUG, SEP, OCT, NOV, DEC } /* FEB is 2, MAR is 3, etc. */

enum in C++ In C, the keyword enum must appear before the type when declaring variables: enum days {sun, mon, …, fri, sat}; enumdays today; This is NOT necessary in C++: days today;

struct in C++ Unlike C, the keyword struct is not required when declaring variables of a struct type: structmyDataType{ }; myDataTypemyData;

#define In, C we have used #define to define constants. The preprocessor replaces each occurrence of the name with its value. We can also use it to define simple functions #definesqr(x)((x)*(x)) We include parentheses to ensure its correct translation by the preprocessor.

const The compiler sees the program after the preprocessor is finished, so the error messages reflect the preprocessed code, not the original source code. The const statement ensures that the compiler produces error messages that reflect what was originally written: const float pi = ;

inline functions Functions call can take a large amount of time to execute. Inline functions avoid this by inserting the code for the function in the object code. inline float abs(x) { return (x>=0)? x: -x;} Because an inline function's code is physically inserted in the program each time its called, we limit its use to small functions.