ENGR112 - Lecture 3
ENGR112 - Lecture 3
C++ Basics
Content: Today we will see
n Some basic rules about C++ coding
n The form of a C++ program
n How to display text messages in C++
n Some common errors in C++ coding
n Some good practices
My First Program
n Write a C++ program that displays the
following message on the screen
int main()
{
cout << “ Welcome to ENGR 112 ! ” ;
return 0;
}
ENGR 112
1 // Fig. 1.5: fig01_05.cpp
2 // Printing multiple lines with a single statement
3 #include <iostream>
4 using namespace std;
5 // function main begins program execution
Using newline characters to print
6 int main() on multiple lines.
7 {
8 cout << “Welcome\nto\n\nENGR 112\n";
9
10 return 0; // indicate that program ended successfully
11
12 } // end function main
Welcome
to
ENGR 112
Escape Sequences
n Rule: all escape sequences must be within the quotations
Escape Description Example Output
Sequen
\n Newline. Position the screen cursor cout<<“Hello \n World”; Hello
to the beginning of the next line. World
\t Horizontal tab. Move the screen cout<<“Hello \t World”; Hello World
cursor to the next tap stop.
\r Carriage return. Position the cout<<“Hello \r Word”; Word
screen cursor to the beginning of
the current line.
\a Alert. Sound the system bell cout<<“Hello \a”; Beep
\\ Backslash. Used to print backslash cout<<“hello \\ World”; Hello \ World
character
\” Double quote. Used to print double cout<<“\”hello\” ”; “hello”
quote character
21
1 // Fig. 1.5: fig01_05.cpp
2 // Printing multiple lines with a single statement
3 #include <iostream>
4 using namespace std;
5 // function main begins program execution
6 int main()
7 {
8 cout << "Welcome”<<endl<<“to\n”;
9 cout << endl<<“ENGR 112”<<endl;
11
12 } // end function main
Welcome
to
ENGR 112
Program Errors
1 /* Please find out the ERRORS,
2 Enjoy………………………*/
3 #include (isotream);
4 using name space std
5 // function main begins program execution
6 int main{ }
7 {
8 Cout >> “C++ “,
9 cout >> “is fun! “,
10 cout >> “endl”;
11
12 return ; // indicate that program ended successfully
13 } // end function main
Program Errors
1 /* Program without Errors,
2 Enjoy………………………*/
3 #include <iostream>
4 using namespace std;
5 // function main begins program execution
6 int main()
7 {
8 cout << “ C++ “;
9 cout << “is fun! “;
10 cout << endl;
11
12 return 0; // indicate that program ended successfully
13 } // end function main
C++ is fun!
What makes a bad program?
n Writing Code without detailed analysis and
design
Mohamed
Abdul-Aziz
Exercise: solution
n Analysis:
n Output : text showing Name and
Surname in separate lines
n Input: None
n Process: Display the text mentioned
above
Exercise: solution (cont)
1 /* Program displaying name and surname */
2 #include <iostream>
4 using namespace std;
5 // function main begins program execution
6 int main()
7 {
8 cout << “Mohamed“;
10 cout << endl ;
11 cout << “Abdul-Aziz“;