CS503 Lec1

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 32

CS 503: C++ programming language

Course Materials:
1. Lecture notes
2. Textbooks:
a. Robert Lafore: Object-Oriented Programming in C++, 4 th edition, Sams Publishing, 2002.
b. D.S. Malik: C++ Programming: From Problem Analysis to Program Design, Cengage Learning, 2013.

3.

Other recommended references:


a. Richard L. Halterman: Fundamentals of C++ Programming, 2015.
b. Deitel, P., and Deitel H.: C++ How To Program, 9 th edition, Pearson Education, 2013.

Topics:
1. C++ Programming Basics
2. Decisions and Loops
3. Functions
4. Structs
5. Arrays
6. Pointers
7. Overloading
8. Objects, Classes, and inheritance
9. Streams and Files
Student Assessment:
1.
2.
3.
4.

Midterm exam (6/4/2015, 20 points).


Practical quizzes (10 points).
Non-credit homework for your practice and we can discuss it in the next lecture.
The final exam (70 points).

I recommend that you type all of the examples in every lecture, even
when they are very simple. Keying stuff makes it less likely that you
will forget things later. Dont be afraid to experiment with the code.
Making mistakes is very educational in programming. The more
mistakes you make early, the more you are likely to learn.
The best way to learn to program is by writing programs! At the end of
each lecture and lap, you will find some exercises and/or a quiz.
Please answer them and evaluate your work. The later lectures build
on what you have learned in the earlier ones, so be certain you fully
understand the material before moving on.
The exercises further reinforce learning and challenge students to write
C++ programs with a specified outcome.

Lecture 1:

THE BASIC ELEMENTS OF C++


This lecture explains the basic elements of C++. After completing this
lecture, students become familiar with the basics of C++ and are
ready to write programs that are complicated enough to do some
computations. These programs teach problem-solving skills.

Getting Started
Your Development Environment: this will be explained in the laps.
Source files are text files and have extension .CPP
Executable files have the .EXE extension
Compilers take source code and transform it into executable files, which
your computer can run as it does with other programs.

Getting Started (Cont.)


The steps to create an executable file are:
1. Create a source code file with a .cpp extension.
2.

Compile the source code into an object file


with the .obj or .o extension.

3.

Link your object file with any needed libraries


to produce an executable program.

Basic Program Construction

// first.cpp

// The first program in C++

Comments

3 #include <iostream>
4 Using namespace std;

Written between /* and */ or following a //.

int main()

Improve program readability and do not cause the


computer to perform any action.

preprocessor directive
cout << "Welcome to C++!\n";

8
9

return 0;

10 }

Welcome to C++!

// indicate that the

#include <iostream> tells the preprocessor to


include the contents of the file <iostream>, which
includes input/output operations (such as printing to
program ended successfully
the screen).
C++ programs contain one or more functions, one of
which must be main
Parenthesis are used to indicate a function

Prints the string of characters


contained
between
the an integer value.
int means
that main
"returns"
quotation marks.
return 0 means that the program
terminated normally.
A left
bracethe
{ <<
begins
the body
The entire line, including
cout,
operator,
theof every function
a right brace
} ends
it.
string "Welcome toand
C++!\n"
and the
semicolon
(;), is called a statement.
All statements must end with a semicolon.

Comments
- They help understand the code by providing explanation about it, and
- help you remember the key details of your program in future.

Should concentrate on the big picture, clarifying your reasons for


using a certain statement.

The compiler ignores the comments, so they do not add


to the file size or execution time of the executable
program.

Comments (Cont.)
Comment Syntax
1. Start with a double slash symbol // and terminate at the end of the line.
(This is one of the exceptions to the rule that the compiler ignores whitespace).

Can start at the beginning of the line or on the same line following a program statement.

EX:
// demonstrates comments // at the beginning of the line
#include <iostream>
// following a program statement

using namespace std;


int main()
{
cout << Hello world\n;
return 0;
}

// preprocessor directive
// using directive
// function name main
// start the function body
// statement
// statement
// end of the function body

Comments (Cont.)
2. Begins with the /* and ends with */

(not with the end of the line).

EX:
/*
This is an old-style comment.
But it is a good approach to make a comment of large text since it
saves inserting // in every line.
It has advantages in special situations. You can write a multi-line
comment with only 2 comment symbols that are: /* and */
*/

Directives
1. Preprocessor Directives: is an instruction to the compiler. It starts with #.

EX: #include <iostream>


The preprocessor directive #include tells the compiler to insert another file into
your source file. It will be replaced by the contents of the indicated file.
The file usually included by #include is called a header file. EX: IOSTREAM
that is concerned with basic input/output operations, and contains the
declarations that are needed by the cout and the << operator.
Without these declarations, the compiler wont recognize cout and will think <<
is being used incorrectly.

A preprocessor (that is a part of the compiler) deals with these directives


before it begins the real compilation process.

Directives (Cont.)
2. The using directive
NOTE: A namespace is a part of the program in which certain names are recognized and
are unknown outside of this namespace.

The directive using namespace std; says that all the program statements
that follow are within the std namespace.
EX: cout is declared within this namespace.

If we dont use the using directive, we will need to add the std many times.
EX: std::cout << "Welcome to C++!\n";
To avoid adding std:: dozens of times in programs, we use the using directive.

Always start with main( )


The program may consist of many functions, classes, and other program
elements. But on startup, control always goes to main( ). If there is no
function called main( ) in your program, an error will be reported when
you run the program. In most C++ programs, main( ) calls member
functions and other standalone functions.

Function name
The parentheses ( ) following the word main are the distinguishing feature
of a function. Theyre used to hold function arguments- values passed
from the calling program to the function.

Braces and the function body


The body of a function is surrounded by braces { }. They surround a
block of program statements.
Every function must use this pair of braces around the function body.

Program Statements
Program statements are instructions to the computer to do something. such
as adding two numbers or printing a sentence.
A semicolon ; signals the end of the statement. This is a crucial part of the
syntax but easy to forget.
If you leave the semicolon, the compiler will often (although not always)
signal an error. See the next slide.
EX:

cout << "Welcome to C++!\n";

White space
The end of a line isnt important to a C++ compiler.
You can put several statements on one line, separated by any number of spaces or tabs,

or you can run a statement over 2 or more lines. Its all the same to the compiler.
EX:
The previous example can be written this way:
#include <iostream>
using
namespace std;
int main () { cout
<<
Hello world !\n
; return
0;}
It will be compiled correctly but it is hard to read.

White space (Cont.)


There are several exceptions to the rule that whitespace is invisible to the
compiler:
1. #include line must be written on one line.

2. Also, string constants, such as Every age has a language of its own,
cannot be broken into separate lines. (If you need a long string constant,
you can insert a backslash (\) at the line break or divide the string into
two separate strings, each surrounded by quotes.)

Common Escape Sequences

The name reflects the fact that the backslash causes an escape from the normal way characters are
interpreted. EX: t is interpreted not as the character t but as the tab character.
Escape sequences can be used as separate characters or embedded in string constants.
Escape
Sequence

Name

Description

\n

New line

Causes the cursor to go to the next line for subsequent


printing

\t

Horizontal tab Causes the cursor to skip over to the next tab stop

\a

Alarm

Causes the computer to beep

\b

Backspace

Causes the cursor to move left one position

\r

Return

Causes the cursor to go to the beginning of the current line,


not the next line.

\\

Backslash

Causes a backslash to be printed

\'

Single quote

Causes a single quotation mark to be printed

\"

Double quote

Causes a double quotation mark to be printed

There are multiple ways to print text as follows.

// first.cpp

// Printing a line with multiple statements

#include <iostream>

using namespace std;

int main()

1. Load <iostream>
2. main

cout << "Welcome ";

//note the space after Welcome

cout << "to C++!\n";

9
10

return 0;

// indicate that program ended successfully

2.1 Print "Welcome"


2.2 Print "to C++!"
2.3 newline

11 }

2.4 exit (return 0)


Program Output

Welcome to C++!

Unless new line '\n' is specified, the text continues


on the same line.

// first.cpp

// Printing multiple lines with a single statement

#include <iostream>

1. Load <iostream>

2. main

int main()

2.1 Print "Welcome"

std::cout << "Welcome\nto\n\nC++!\n";

2.3 Print "to"

8
9

2.2 newline

return 0;

// indicate that program ended successfully

10 }

2.4 newline
2.5 newline
2.6 Print "C++!"

Welcome
to

2.7 newline

C++!

2.8 exit (return 0)


Multiple lines can be printed with one
statement.

Program Output

More Useful Programs

Variables
Location in memory where a value can be stored for use by a program.
Must be declared with a name and a data type before they can be used.
Some common data types are:
int
- integer numbers
double - floating point numbers
char - characters
EX: int myvariable;
//Declares a variable named myvariable of type int
EX: int variable1, variable2; //Declares two variables, each of type int

You can place variable declarations anywhere in a program. Its not necessary to
declare variables before the first executable statement. However, its more
readable if commonly-used variables are located at the beginning of the program.

A variable with a name total and of type int in memory.

Variable names
Every variable has a name, a type, a size and a value.
The names given to variables are called identifiers.
Whenever a new value is placed into (assigned to) a variable, it replaces
the previous value the old value is destroyed.
Reading variables from memory does not change them.
The rules for writing identifiers:
You can use upper and lowercase letters, the digits from 1to 9, and the underscore _

The first character must be a letter or underscore.


The compiler distinguishes between upper and lowercase letters, so
Var is not the same as var or VAR.
You cant use a C++ keyword as a variable name. A keyword is a
predefined word with a special meaning such as int, class, if, while

Input with cin


The statement cin >> ftemp;

// ftemp is a variable

causes the program to wait for the user to type a number. The resulting
number will be placed in the variable ftemp.

Input with cin.

Assignment Statements
Assign value to a variable.
The equal sign = causes the value on the right to be assigned to the
variable on the left.
EX:
var1 = 20;

Operators

Arithmetic operators:

Rules of operator precedence:

Arithmetic calculations
Integer division truncates remainder
7 / 5 evaluates to 1

Modulus operator returns the remainder


7 % 5 evaluates to 2

Operator precedence
Some arithmetic operators act before others (EX: multiplication before addition).
Be sure to use parenthesis when needed

EX:
Find the average of three variables a, b and c
Do not use: a + b + c / 3
Use: (a + b + c ) / 3

// AddingTwoIntegerNumbers.cpp

// Addition program

#include <iostream>

//we didnt write using namespace std; so well repeat std::cout many times

1. Load <iostream>

int main()

2. main

int integer1, integer2, sum;

8
9

2.1 Initialize variables


integer1,
// prompt
and sum
Notice how std::cin is usedinteger2,
to get user input.

// declaration

std::cout << "Enter the first integer\n";

10

std::cin >> integer1;

// read an integer

11

std::cout << "Enter the second integer\n"; // prompt

12

std::cin >> integer2;

// read an integer

13

sum = integer1 + integer2;

// assignment of sum

14

std::cout << The sum is: " << sum << std::endl; // print sum

15
16

return 0;

// indicate that program ended

17 }

Enter first integer


45
Enter second integer
72
The sum is: 117

2.2 Print "Enter


first integer"
2.2.1 Get input

2.3 Print "Enter


second integer"
successfully
std::endl prints a newline.
2.3.1 Get input

2.4 Add variables and


put result into sum
Variables can be output using std::cout << variableName.
2.5 Print "Sum is"
2.5.1 Output sum
2.6 exit (return 0)

Homework:
Re write this program by adding using namespace

Program Output

5 minute question:
What is the output of the following program?
#include <iostream>
using namespace std;
int main()
{
int x = 5;
int y = 7;
cout << x + y / 2 << endl;
return 0;
}

5 minute question: (Cont.)


The answer is 8 because it will execute first y/2 that is equal 3
then will add to it x. 3 plus 5 results 8
The solution is:
#include <iostream>
using namespace std;
int main()
{
int x = 5;
int y = 7;
cout<<(x+y)/2; //will first execute the addition of x+y and then divide the result of the addition that is12 on 2.
return 0;
}

Sample questions:
1. What the following program does without running it?
#include <iostream>
using namespace std;
int main() {
int x = 5;
int y = 7;
cout << x + y << << x * y;
cout << endl;
return 0;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

2. What should be corrected in the following program?


include <iostream>
using namespace std;
int main() {
cout << "Hello World \n";
return 0;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

3. What is the output of: cout << \Run, Spot, run,\ she said.;

Self study example:


// fahren.cpp
// demonstrates cin, newline

#include <iostream>
using namespace std;
int main()
{
int ftemp;
//for temperature in fahrenheit
cout << Enter temperature in fahrenheit: ;
cin >> ftemp;
int ctemp;
ctemp = (ftemp - 32) * 5 / 9;
cout << Equivalent in Celsius is: << ctemp << \n;
return 0;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

Heres some sample interaction with the program:


Enter temperature in fahrenheit: 212
Equivalent in Celsius is: 100

You might also like