0% found this document useful (0 votes)
66 views

Course Websites: CS201 Page Link at My Website

Here are the key elements identified in the example program: Literals: "Please enter your name: " myname Identifiers: radius area myname Keywords: int float string cout cin main Symbols: << >> ; {} = * 3.14159 Variables: radius area myname Expressions: radius * radius * 3.14159 This program prompts the user to enter their name and a radius value. It then calculates and displays the area of a circle using the radius input by the user.

Uploaded by

Tamer A. Dakkak
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
66 views

Course Websites: CS201 Page Link at My Website

Here are the key elements identified in the example program: Literals: "Please enter your name: " myname Identifiers: radius area myname Keywords: int float string cout cin main Symbols: << >> ; {} = * 3.14159 Variables: radius area myname Expressions: radius * radius * 3.14159 This program prompts the user to enter their name and a radius value. It then calculates and displays the area of a circle using the radius input by the user.

Uploaded by

Tamer A. Dakkak
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 22

Course websites

CS201 page link at my website:


http://myweb.sabanciuniv.edu/gulsend

Lecture slides
Assistants Information
Recitations
Office Hours
Make-up Rules
Plagiarism
Chapter 2
Writing and Reading C++ Programs
A programming language has syntax and semantics like any
natural language
Syntax is the set of rules like spelling and grammar in natural
languages
English: syntax spelled, sentences start with subject
followed by verb
C++: main spelled, programs start with main() followed by {
Semantics is the meaning
English: water means H2O
C++: int means integer, + means add

Approaches of learning programming languages


Template based
Examine example programs and make analogies
Like a child learns how to speak
First learn syntax and semantics, then start by writing small
programs, ...
Like learning a foreign language
Which one do you prefer? We will follow the second method
First C++ Program
Hello world program

#include <iostream>
using namespace std;
/* traditional first program */
int main()
{
cout << "Hello world" << endl; // display
return 0;
}

This program must be


Typed and saved in a file <name>.cpp (hello.cpp)
Compiled (syntax checked): hello.cpp hello.obj
Linked (combined with iostream library) : hello.obj hello.exe
Run (execute) hello.exe
Format of a C++ Program
#include statements
#include <iostream>
using namespace std; comment

/* traditional first program */


int main()
int main()
{ {
cout << "Hello world" C++ statement 0; comment
<< endl; // display
C++ statement 1;
return 0;
}
C++ statement (n-1);
}
Format of a C++ Program
#include statements make libraries of classes and functions
available to the program
Utility functions and tools that make the programmers life
easier are defined in libraries
Helps programmers develop code independently in a
standard way and reuse common operations
Compiler needs access to interface (definition), what the
functions look like, but not to the implementation of those
functions
This is in the #included file
e.g. #include <iostream>
for input/output functions
all programs that use standard C++ libraries should have

using namespace std;


Format of a C++ Program
Comments make programs readable by humans (and by assistants!)
Easier maintenance
Try to use natural language, do not repeat the code!
Bad example
area = pi * r * r; /* area is pi*r*r */
Better example
area = pi * r * r; /* calculate area */
Best example
area = pi * r * r; /* calculate area of a circle
of radius r */
Two ways of commenting
Using // make the rest of the line comment
area = pi * r * r; // calculate area
Between /* and */
/*
Calculate area of a circle of radius r
*/
area = pi * r * r;
Compiler disregards comments
Comments in your homework affect your grades
In VC++, comments are in green
Format of a C++ Program
Execution of the program begins with main
Each program must have a main function
Execution of C++ programs is organized as a
sequence of statements
Statements execute sequentially one after another
statement 0, statement 1, , statement (n-1)
Branching, repetition are possible (we will see them later)
The main function returns a value to the operating
system or the environment in which it is executed
return 0
Why 0? Because 0 means no problems (errors)
encountered!
Format of a C++ Program
Each statement ends with a ; (semicolon)
except #include and function headers like main()
Each statement has optional line break after the ;
int main()
{
// This is valid code too
cout << "Hello world" << endl; return 0;
}
Blanks (spaces) are optional but makes code much
more readable (we will see its rules)
cout<<"Hello world"<<endl;
Rules of C++
Now some syntax rules and definitions
ABC of C++

What is a literal?
Reserved words (keywords)
What is an identifier?
Variables and basic types
Symbols and compound symbols
Where to use blanks, line breaks?
Basic Input/Output
Literals
Fixed (constant) values
They cannot be changed during programs execution
They can be output by cout
Different format for different types:
String literals
Sequences of characters
Within double quotes (quotes are not part of the string)
Almost any character is fine (letters, digits, symbols)
"Hello world!"
" 10 > 22 $&*%? "
Numeric literals
Integer
3 454 -43 +34
Real
3.1415 +45.44 -54.6 1.2334e3
1.2334e3 is 1.2334 times 10 to the power 3 (scientific notation)
Identifiers
Names of programmer defined elements in a program
Names of variables, functions and parameters
Examples:
number1 valid
number_1 valid
mySum valid
my_sum_1 valid
1number not valid
Syntax (rules):
1. Sequence of letters (a .. z, A ..Z), digits (0 ..9) or underscore
2. Cannot start with a digit
3. Case sensitive (number1 and Number1 are not the same)
Pick meaningful names to improve readability and
understandability of your program (be consistent)
Hungarian notation
Reserved Words (Keywords)
Special and fixed meanings
built-in in C++ language
no need to have libraries to use them
You cannot use a reserved word as a user-defined identifier
Cannot be changed by programmer
int
return
Full list is Table 2.1 of the textbook
Full list also in MSDN:
http://msdn.microsoft.com/en-us/library/aa245310(VS.60).aspx

In MS VC++, reserved words are automatically blue


Variables and Types
Variables are used to store data values that can
change during the program
Input (cin) data is stored in variables
Results are stored in variables
Named memory locations of certain sizes
Memory
Must be defined before they can be used
number1 age
Often initialized before use
Syntax: sum

type name; identifier


myName
type name1, name2, , namek;
Common types: last_name
int number1, age, sum;
area
string myName, last_name;
float area, distance; distance
Symbols
Non-digit and non-letter characters with special meanings
Mostly used as operators (some examples below, full list later)

Symbol Meaning Example


+ addition, sign 12 + 2, +67
- subtraction, minus 37 5, -8
* multiplication 3 * 5 * number
/ division 5.2 / 1.5
% modulus/remainder 7%2
= assignment sum = x + 5;

Compound symbols (two consecutive symbols one meaning),


examples below, full list later
Symbol Meaning Example
/* comment start /* calculates
*/ comment end area */
<< stream output cout << "Hello";
>> stream input cin >> number;
== equality comparison number == 0
Arithmetic Operations
Operators: + - * / %
Operands: values that operator combines
variables or literals
Combination of operators and operands is called
expression
Syntax and semantics for arithmetic operations:
Addition Multiplication Division Modulus
Subtraction
23 + 4 23 * 4 21 / 4 is 5 21 % 4 is 1
x + y x * 3.0 21 / 4.0 is 18 % 2 is 0
5.25
d 14.0 + 23 d * 23.1 * 4 x / 4 x % 4
5 - 3 + 2 5 3 * 2 x / y x % y

See Figure 3.4 in the book.


Assignment Operator
Stores a new value in a variable
Memory
variable = expression;
number
The value of expression becomes name
the value of variable 45
int number; value
number = 40; nam
number = number + 5; eGulsen
string name;
name = "Gulsen";
number * 4 = 56; wrong syntax
Previous value of variable is lost
Be careful about the types of left and right
hand sides
they must match
compiler may or may not warn you
int a = 32.6;
Example Program
Write a program to calculate the area of a circle
program first input a name and print a greeting
input the radius
calculate and display area
identify literals, identifiers, keywords, symbols, variables and expressions

#include <iostream>
#include <string>
using namespace std;

// area calculation program

int main()
{
int radius;
float area;
string myname;
cout << "Please enter your name: ";
cin >> myname;
cout << "Hello " << myname
<< "! Welcome to my area calculation program" << endl;
cout << "Please enter the radius of your circle: ";
cin >> radius;
area = 3.14 * radius * radius;
cout << "the area is: " << area << endl;
return 0;
}
Issues with the Example
Program
What happens if the user enters a real number for
radius?
wrong result
solution: real radius
Can we combine?
cout << "Hello " << myname
<< "! Welcome to my area calculation program" << endl;
cout << "Please enter the radius of your circle: ";
Can we eliminate the variable area?
area = 3.14 * radius * radius;
cout << "the area is: " << area << endl;
Where to use Blanks
(Newline)
You must have at least one blank
between two words (identifiers or keywords)
e.g. int number;
between a word and numeric literal
e.g. return 0;
You cannot have a blank
within a word (e.g. float)
within a compound symbol (e.g. <<)
within a literal (e.g. 3.145)
except string literals, in string literals blanks are blanks
At all other places
blanks are optional and increases readability
area = 3.14*radius * radius;
Several blanks are functionally same as single blank
except within string literals (e.g. "Hello world")
Newlines can be used whenever blank can be used
Stream Output
Output is necessary for our programs
Standard output stream cout is the monitor (read see-out)
cout is implemented in the iostream library
Output is sent to stream by the << operator
cout << "Hello world! ";
What can be output?
String literals between " ", expressions and variables
More than one output could be sent to the stream
cout << "Hello" << " world!" << endl;
endl means end of line
causes next output to be displayed in next line

cout << "Hello world" << endl << " and universe" << endl;
int sum = 10 + 2; Hello world
cout << "sum = " << sum << endl; and universe
cout << 45 << " km. = ";
cout << 45 * 0.62 << " miles" sum = 12
<< endl; 45 km. = 27.9 miles
Stream Input
Input is also necessary for our programs
Standard input stream cin is the keyboard (read see-in)
cin is also implemented in the iostream library
You can input only to variables
Input is read from the stream by the >> operator
cin >> number;
More than one input could be read from the stream
cin >> variable1 >> variable2 >> variable3 ;

Data will be read into the variables in the same order they
are in the cin statement
int a, b, anynumber;
cin >> b >> anynumber >> a;
first the value for b, then the value for anynumber, then the
value of a must be entered by the user using the keyboard
Stream Input
You have to have at least one blank between any two input
entry
Multiple blanks are OK
You may input values at several lines for a single cin
statement
You cannot display something using cin statement

Type match between variable and the corresponding input


value
If mismatch then the input entry fails for the rest of the
program
But the values read up to that point are kept in the variables

You might also like