Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS149D Elements of Computer Science

Similar presentations


Presentation on theme: "CS149D Elements of Computer Science"— Presentation transcript:

1 CS149D Elements of Computer Science
Ayman Abdel-Hamid Department of Computer Science Old Dominion University Lecture 14: 10/17/2002 Lecture 14: 10/17/2002 CS149D Fall 2002

2 Outline Simple C++ programs Program structure
A simple C++ program: Hello World Program! A longer C++ program: Compute distance between two points Lecture 14: 10/17/2002 CS149D Fall 2002

3 The main() function body
C++ Program Structure Global area The main() function body Another function Another function Lecture 14: 10/17/2002 CS149D Fall 2002

4 A Simple C++ Example White Space? /* Author: Ayman Abdel-Hamid */
// This is your first C++ program // The program will only print hello on the command line #include <iostream.h> #include <stdlib.h> int main() { cout << “Hello” ; return 0; } Comments Preprocessor directives White Space? Any C++ program must have a main function All C++ statements must end with a ; Lecture 14: 10/17/2002 CS149D Fall 2002

5 A Longer Example1/3 Problem Statement Input Output
Compute the straight line distance between two points in a plane Input A point has an x and y coordinates. We need 2 points Assume (x1, y1) = (1,5) & (x2, y2) = (4,7) Output The distance between the 2 points. How? (x1, y1) (x2, y2) x1 x2 y1 y2 side1 side2 distance Calculate side1 = x2 - x1 Calculate side2 = y2 - y1 Calculate distance = Square root (side12 + side22) Lecture 14: 10/17/2002 CS149D Fall 2002

6 A Longer Example2/3 Algorithm Assign x1 the value 1
Assign y1 the value 5 Assign x2 the value 4 Assign y2 the value 7 Assign side1 the value x2 –x1 Assign side2 the value y2-y1 Assign distance the value sqrt (side12 + side22) Write distance on the screen Stop Lecture 14: 10/17/2002 CS149D Fall 2002

7 A Longer Example3/3 // This program computes the distance between two points. A point has an x and y coordinate //Program from Etter Text, chapter 2, page 22 (also chapter 1, page 17) //Preprocessor directives #include <iostream.h> #include <stdlib.h> #include <math.h> int main() { // Define and initialize variables. double x1=1, y1=5, x2=4, y2=7, side_1, side_2, distance; // Compute length of sides of right triangle. side_1 = x2 - x1; side_2 = y2 - y1; distance = sqrt( side_1 * side_1 + side_2 * side_2 ); // Print distance. cout << "The distance between the two points is "<< distance << " cm." << endl; // Exit program. return EXIT_SUCCESS; } Lecture 14: 10/17/2002 CS149D Fall 2002


Download ppt "CS149D Elements of Computer Science"

Similar presentations


Ads by Google