Intro To C++ Language: Scalar Variables, Operators and Control Structures
Intro To C++ Language: Scalar Variables, Operators and Control Structures
• C++ is both!
• We will start with procedural and build up to
Object Oriented
C++ Spring 2000 C++ Intro 3
Hello World++
// Hello World program comment
Executable
C++ Program Program
y = square(x);
becomes y = (x * x);
z = square(y*x);
int main() {
int integer1, integer2, sum;
int main()
{
double fahr,celcius;
return 0;
}
C++ Spring 2000 C++ Intro 28
const
• You can add the const modifier to the
declaration of a variable to tell the compiler
that the value cannot be changed:
if (1-1)
cout << "I am false!\n";
if (grade>=90)
lettergrade = 'A';
if (lettergrade == 'F')
cout << "The system has failed you\n"
if (grade=100)
cout << "your grade is perfect -
RPI has decided to give you your
degree today!\n";
C++ Spring 2000 C++ Intro 42
Compound Statements
• Inside an if you can put a single statement or
a compound statement.
• A compound statement starts with "{", ends
with "}" and can contain a sequence of
statements (or control structures)
if (grade>=90) {
cout << "Nice job - you get an A\n";
acnt = acnt+1;
}
if(foo>10){x=y+100;cout<<x;}
if ( condition )
action if true
else
action if false
do
somestuff;
while ( condition );
C++ Spring 2000 C++ Intro 55
do example
i=1;
do
cout << "i is " << i++ << endl;
while (i <= 10);
cutoff -= 10;
con
update
if (lettergrade > 'F')
lettergrade = 'F';
( cond1 || cond2 )
if ((hw1==0) || (hw2==0))
cout << "You missed a homework!\n";
(! condition)
is true only when condition is false
C++ Spring 2000 C++ Intro 69
! example
bool done = false;
int i=1;
while (! done) {
cout << "i is " << i << endl;
i++;
if (i==100) done=true;
}
C++ Spring 2000 C++ Intro 70
Exercises
(informal - not to hand in)
• Try exercises 2.12 a,d and e.
• Don't just do on paper - create programs!
• Make sure you can create, compile and run
a C++ program.
• Send Dave email if you have problems:
[email protected]