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

Lecture 01- Introduction to c++ Programming spring 2025

This document provides an introduction to Object Oriented Programming using C++ for a Spring 2025 course. It covers C++ programming basics, including programming style, structure of a C++ program, compilation process, and control structures. The document also includes examples and explanations of basic C++ syntax and operations, such as variable declaration, input/output, and control flow statements.

Uploaded by

Usman
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Lecture 01- Introduction to c++ Programming spring 2025

This document provides an introduction to Object Oriented Programming using C++ for a Spring 2025 course. It covers C++ programming basics, including programming style, structure of a C++ program, compilation process, and control structures. The document also includes examples and explanations of basic C++ syntax and operations, such as variable declaration, input/output, and control flow statements.

Uploaded by

Usman
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

Object Oriented Programming

Introduction

Lecture 1
Spring 2025

CS1004 - Spring 2025 1


Lecture Contents
• C++ Programming basics
• Control structures
• Arrays

CS1004 - Spring 2025 2


Programming Style
• C++ is a free-format language, which means that:
• Extra blanks (spaces) or tabs before or after identifiers/operators are ignored

• Blank lines are ignored by the compiler just like comments

• Code can be indented in any way

• There can be more than one statement on a single line

• A single statement can continue over several lines

CS1004 - Spring 2025 3


Programming Style (cont. )
• In order to improve the readability of your program, use the following conventions:
• Start the program with a header that tells what the program does

• Use meaningful variable names and Camel notation

• Document each variable declaration with a comment telling what the variable is used for

• Place each executable statement on a single line

• A segment of code is a sequence of executable statements that belong together


• Use blank lines to separate different segments of code

• Document each segment of code with a comment telling what the segment does.

4
CS1004 - Spring 2025
Structure of a C++ Program
• A C++ program is a collection of definitions and declarations:
• data type definitions

• global data declarations

• function definitions (subroutines)

• class definitions

• a special function called

• main() (where the action starts)

CS1004 - Spring 2025 6


C++ program execution process
• How many stages does a c++ program goes through
before it is executed?

CS1004 - Spring 2025 9


Making Software Load into
memory and
Compiler
start execution
Problem “Turbo C” in DOS
“gcc” or “g++” in Linux
“Visual C++” in windows Executable file
Develop “Borland” in
Algorithm DOS/Windows.
Compile the code
Express Algorithm in the
form of pseudo code or
flow chart Write algorithm in
C/C++/Java … Language

Writing code in “C++” language means, we must have to


follow a certain rules of “C++” language.
This is called syntax of “C++” language.
CS1004 - Spring 2025 10
Basics of a Typical C++ Environment
Program is created in
Editor Disk the editor and stored
Phases of C++ Programs: on disk.

Preprocessor Preprocessor program


Disk processes the code.
1. Edit
Compiler creates
Compiler Disk object code and stores
it on disk.
2. Preprocess Linker links the object
code with the libraries,
Linker Disk creates a.out and
stores it on disk
3. Compile Primary
Memory
Loader

4. Link Loader puts program


in memory.
Disk ..

5. Load ..
..

Primary
Memory
6. Execute CPU CPU takes each
instruction and
executes it, possibly
storing new data
values as the program
..
executes.
..
..
CS1004 - Spring 2025 11
C++ Compilation Process
• Compiler compiles a C/C++ program into
executable in 4 steps as shown in the diagram.
For example, a "gcc -o hello.exe hello.c" is
carried out as follows:
• Pre-processing: via the GNU C Preprocessor
(cpp.exe), which includes the headers
(#include) and expands the macros (#define).
• The resultant intermediate file "hello.i"
contains the expanded source code.
• Compilation: The compiler compiles the pre-
processed source code into assembly code for
a specific processor.
• The resultant assembly file is "hello.s".
• Assembly: The assembler (as.exe) converts the
assembly code
into machine code in the object file "hello.o".
• Linker: Finally, the linker (ld.exe) links the
object code with the library code to produce
an executable file "hello.exe".
CS1004 - Spring 2025 12
C++ Programming Examples

• Following are several examples


• The examples illustrate many important features of C++

• Each example is analyzed one statement at a time.

CS1004 - Spring 2025 15


1 // Fig. 1.2: fig01_02.cpp

2 // A first program in C++


Comments
3 #include <iostream>
Written between /* and */ or following a //.
4
Improve program readability and do not cause the
5 int main() computer to perform any action.
6 {
preprocessor directive
7 std::cout << "Welcome to C++!\n";
Message to the C++ preprocessor.
8
Lines beginning with # are preprocessor directives.
9 return 0; // indicate that program ended successfully
#include <iostream> tells the preprocessor to
10 } include
C++ the contents
programs containofone
theor <iostream>,
filemore which
functions, one of
includes
which be main operations (such as printing to
input/output
must
the screen).
Welcome to C++! Parenthesis are used to indicate a function
int means
Prints the string of characters that main
contained between the an integer value.
"returns"
quotation marks. More in Chapter 3.
return is a way to exit a function
from a function. A left
The entire line, including brace { begins
std::cout, the the
<< body of every function
return 0, in this case,
operator, and a right to
thatstring "Welcome
means the } ends it. and
braceC++!\n"
the program terminatedthe semicolon (;), is called a statement.
normally.

All statements must end with a semicolon.


CS1004 - Spring 2025 16
A Simple Program: Printing a Line of Text
• std::cout
• Standard output stream object
• “Connected” to the screen
• std:: specifies the "namespace" which cout belongs to
• std:: can be removed through the use of using statements

• <<
• Stream insertion operator
• Value to the right of the operator (right operand) inserted into output stream
(which is connected to the screen)
• std::cout << “Welcome to C++!\n”;
• \
• Escape character
• Indicates that a “special” character is to be output

CS1004 - Spring 2025 17


A Simple Program: Printing a Line of Text
Escape Sequence Description

\n Newline. Position the screen cursor to the


beginning of the next line.
\t Horizontal tab. Move the screen cursor to the next
tab stop.
\r Carriage return. Position the screen cursor to the
beginning of the current line; do not advance to the
next line.
\a Alert. Sound the system bell.
\\ Backslash. Used to print a backslash character.
\" Double quote. Used to print a double quote
character.

• There are multiple ways to print text


• Following are more examples

CS1004 - Spring 2025 18


1 // Fig. 1.4: fig01_04.cpp

2 // Printing a line with multiple statements

3 #include <iostream>

5 int main()

6 {

7 std::cout << "Welcome ";

8 std::cout << "to C++!\n";

10 return 0; // indicate that program ended successfully

11 }

Welcome to C++!

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


on the same line.

CS1004 - Spring 2025 19


Another Simple Program: Adding Two Integers

• 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

• char – characters

• Double – floating point numbers

• Example: int myvariable;


• Declares a variable named myvariable of type int

• Example: int variable1, variable2;


• Declares two variables, each of type int

CS1004 - Spring 2025 20


Another Simple Program: Adding Two Integers

• >> (stream extraction operator)


• When used with std::cin, waits for the user to input a value and stores the
value in the variable to the right of the operator
• The user types a value, then presses the Enter (Return) key to send the data to
the computer
• Example:
int myVariable;
std::cin >> myVariable;
• Waits for user input, then stores input in myVariable

• = (assignment operator)
• Assigns value to a variable
• Binary operator (has two operands)
• Example:
sum = variable1 + variable2;

CS1004 - Spring 2025 21


1 // Fig. 1.6: fig01_06.cpp
2 // Addition program
3 #include <iostream>
4
5 int main()
6 {
7 int integer1, integer2, sum; // declaration
8
9 std::cout << "Enter first integer\n"; // prompt
Notice how std::cin is used to get user
10 std::cin >> integer1; // read an integer
input.
11 std::cout << "Enter second integer\n"; // prompt
12 std::cin >> integer2; // read an integer
13 sum = integer1 + integer2; // assignment of sum
14 std::cout << "Sum is " << sum << std::endl; // print sum
15
16 return 0; std::endl
// indicate that program ended successfully flushes the buffer and
17 } prints a newline.

Enter first integer


45 Variables can be output using std::cout << variableName.
Enter second integer
72
Sum is 117

CS1004 - Spring 2025 22


Using declarations
• using statements
• Eliminate the need to use the std:: prefix

• Allow us to write cout instead of std::cout

• To use the following functions without the std:: prefix, write the
following at the top of the program

using std::cout;

using std::cin;

using std::endl;

CS1004 - Spring 2025 24


1 // Fig. 1.14: fig01_14.cpp
2 // Using if statements, relational
3 // operators, and equality operators
4 #include <iostream>
5
6 using std::cout; // program uses cout
7 using std::cin; // program uses cin Notice the using statements.
8 using std::endl; // program uses endl
9
10 int main()
11 {
12 int num1, num2;
13
14 cout << "Enter two integers, and I will tell you\n"
15 << "the relationships they satisfy: ";
16 cin >> num1 >> num2; // read two integers
Enter two integers, and I will tell you
17
the relationships they satisfy: 3 7
18 if ( num1 == num2 )
19 cout << num1 << " is equal to " << num2 << endl;
20
The if statements test the truth
21 if ( num1 != num2 ) of the condition. If it is true,
22 cout << num1 << " is not equal to " << num2 << endl; 3body of if
is not statement
equal to 7 is
23 executed. If not, body is
24 if ( num1 < num2 ) skipped.
25 cout << num1 << " is less than " << num2 << endl; 3 is less than 7
26 To include multiple statements
27 if ( num1 > num2 ) in a body, delineate them with
28 cout << num1 << " is greater than " << num2 << endl;
braces {}.
29
30 if ( num1 <= num2 )
31 cout << num1 << " is less than or equal to " 3 is less than or equal to 7
32 << num2 << endl; CS1004 - Spring 2025 25
33
34 if ( num1 >= num2 )

35 cout << num1 << " is greater than or equal to "

36 << num2 << endl;

37

38 return 0; // indicate that program ended successfully

39 }

Enter two integers, and I will tell you


the relationships they satisfy: 3 7
3 is not equal to 7
3 is less than 7
3 is less than or equal to 7

Enter two integers, and I will tell you


the relationships they satisfy: 22 12
22 is not equal to 12
22 is greater than 12
22 is greater than or equal to 12

Enter two integers, and I will tell you


the relationships they satisfy: 7 7
7 is equal to 7
7 is less than or equal to 7
7 is greater than or equal to 7

CS1004 - Spring 2025 26


Class Activity#1
• Write a program that generates the following output, using only one cout statement and proper
spacing

1900 2135
1950 2235
2000 2335
2050 2435

CS1004 - Spring 2025 27


Control Structures
• How many control structures are there?

CS1004 - Spring 2025 28


Control Structures
• Normally, statements in a program execute one after the other in the
order in which they’re written.
• Called sequential execution.
• Various C++ statements enable you to specify that the next statement
to execute may be other than the next one in sequence.
• Called transfer of control.
• All programs could be written in terms of only three control
structures
• the sequence structure
• the selection structure and
• the repetition structure

CS1004 - Spring 2025 29


Control Structures (if else and Switch)
• C++ provides three types of selection statements
• The if selection statement either performs (selects) an
action if a condition (predicate) is true or skips the action if the
condition is false.
• The if…else selection statement performs an action if a
condition is true or performs a different action if the condition is
false. Use if-else when the conditions involve complex logical
expressions or comparisons.
• The switch selection statement performs one of many
different actions, depending on the value of an integer
expression. Use switch-case when checking against discrete,
constant values (e.g., integer, character).

CS1004 - Spring 2025 30


Control Structures (if else and Switch)
• The if selection statement is a single-selection statement because it
selects or ignores a single action (or, as we’ll soon see, a single group
of actions).

• The if…else statement is called a double-selection statement because


it selects between two different actions (or groups of actions).

• The switch selection statement is called a multiple-selection


statement because it selects among many different actions (or groups
of actions).

CS1004 - Spring 2025 31


Control Structures (if selection statement)
• Programs use selection statements to choose among alternative courses of
action.
• For example, whether “student’s grade is greater than or equal to 60” is true or
false.
if ( grade >= 60 )
cout << "Passed";

• If true, “Passed” is printed and the next pseudocode statement in order is


“performed”
• If false, the print statement is ignored and the next statement in order is
performed.

CS1004 - Spring 2025 32


Control Structures (if-else selection statement
• Nested if…else statements test for multiple cases by placing
if…else selection statements inside other if…else selection
statements.

if ( studentGrade >= 90 ) // 90 and above gets "A"


cout << "A";
else
if ( studentGrade >= 80 ) // 80-89 gets "B"
cout << "B";
else
if ( studentGrade >= 70 ) // 70-79 gets "C"
cout << "C";
else
if ( studentGrade >= 60 ) // 60-69 gets "D"
cout << "D";
else // less than 60 gets "F"
cout << "F";

CS1004 - Spring 2025 33


Control Structures (Switch Selection Statement)
• Another alternative to if—else statement is Switch statement.

• The idea behind a switch statement is simple:


• an expression (sometimes called the condition) is evaluated to produce a value.

• If the expression’s value is equal to the value after any of the case labels, the
statements after the matching case label are executed.

• If NO matching value can be found and a default label exists, the statements
after the default label are executed instead.

CS1004 - Spring 2025 34


Control Structures (Switch Selection Statement)
int main(){
int num;
cout<<"Please Enter a number: ";
cin>>num;
switch (num) {
case 1:
cout << 1 << '\n’;
break;
case 2:
cout << 2 << '\n';
break;
case 3:
cout << 3 << '\n’;
break;
default:
cout<<"Default Case: "<<'\n';
}
std::cout<<"Switch Terminated: "<<std::endl;
return 0;}
CS1004 - Spring 2025 35
Class activity
• Will the below code be executed?
• What is the output of the below code?

#include <iostream>
using namespace std;
int main() {
int x = //enter 1-3;
switch (x) {
case 1:
case 2:
case 3:
cout << "Matched case 1, 2, or 3" << endl;
break;
default:
cout << "Default case" << endl;
}
return 0;
}

CS1004 - Spring 2025 36


Control Structures (repetition statements)
• C++ provides three types of repetition statements (also called looping statements
or loops) for performing statements repeatedly while a condition (called the loop-
continuation condition) remains true.
• These are the while, do…while and for statements.

• The while and for statements perform the action (or group of actions) in their
bodies zero or more times.

• The do…while statement performs the action (or group of actions) in its body at
least once.

CS1004 - Spring 2025 37


Control Structures (While repetition Statement)
• A repetition statement (also called a looping statement or a loop) allows you to
specify that a program should repeat an action while some condition remains
true.

• The statement contained in the While repetition statement constitutes the


body of the While, which can be a single statement or a block.

• Eventually, the condition will become false, the repetition will terminate, and
the first pseudocode statement after the repetition statement will execute.

CS1004 - Spring 2025 39


Control Structures (while repetition Statement)
• Consider a program segment designed to find the first power of 3 larger than 100.
Suppose the integer variable product has been initialized to 3.

• When the following while repetition statement finishes executing, product contains
the result:

int product = 3;

while ( product <= 100 )


product = 3 * product;

CS1004 - Spring 2025 40


Control Structures (Do while Statement)
• A do while statement is a looping construct that works just like a while loop,
except the statement always executes at least once.

• After the statement has been executed, the do-while loop checks the condition. If
the condition evaluates to true, the path of execution jumps back to the top of
the do-while loop and executes it again.

do

statement; // can be a single statement or a compound


statement

while (condition);

CS1004 - Spring 2025 41


Control Structures (Do while Statement)
int main() {
// selection must be declared outside of the do-while so we can use it
later
int selection;
do {
std::cout << "Please make a selection: \n";
std::cout << "1) Addition\n";
std::cout << "2) Subtraction\n";
std::cout << "3) Multiplication\n";
std::cout << "4) Division\n";
std::cin >> selection; }
while (selection != 1 && selection != 2 &&
selection != 3 && selection != 4);
// do something with selection here
// such as a switch statement
std::cout << "You selected option #" << selection << '\n';
return 0; }
CS1004 - Spring 2025 42
class activity: Control Structures (For Statement)
• Write a program that gives the following output:

i = 0, j=0
i = 0, j=1
i = 0, j=2
i = 0, j=3
i = 0, j=4
i = 1, j=0
i = 1, j=1
i = 1, j=2
i = 1, j=3
i = 1, j=4
i = 2, j=0
i = 2, j=1
i = 2, j=2
i = 2, j=3
i = 2, j=4
i = 3, j=0
i = 3, j=1
i = 3, j=2
i = 3, j=3
CS1004 - Spring 2025 44
i = 3, j=4
Control Structures (For Statement)

#include <iostream>
using namespace std;
int main() {
for (int i = 0; i < 5; ++i) {
for (int j = 0; j < 5; ++j) {
cout << "i = " << i << ", j = " << j << endl;
}
}
return 0;
}

CS1004 - Spring 2025 45


Control Structures (For Statement)
• Now modify the code on the previous slide such that it gives the below output:

i = 0, j = 0
i = 0, j = 1
i = 0, j = 2
i = 0, j = 3
i = 0, j = 4
i = 1, j = 0
i = 1, j = 1
i = 1, j = 2
i = 1, j = 3
i = 1, j = 4
i = 2, j = 0
i = 2, j = 1
i = 2, j = 2
i = 2, j = 3
Exited nested loops.

CS1004 - Spring 2025 46


Control Structures (For Statement)
#include <iostream>
using namespace std;
int main() {
bool exitLoops = false; // Flag to break out of outer loop
for (int i = 0; i < 5; ++i) {
for (int j = 0; j < 5; ++j) {
if (i == 2 && j == 3) {
exitLoops = true;
break; // Break out of the inner loop
}
cout << "i = " << i << ", j = " << j << endl;
}
if (exitLoops) break; // Check the flag and break the outer loop
}
cout << "Exited nested loops." << endl;
return 0;
}

CS1004 - Spring 2025 47


Control Structures (For Statement)
• Write code for the below desired output:

Processing i = 0…
Processing i = 1…
Processing i = 2…
Processing i = 3…
Processing i = 4…

CS1004 - Spring 2025 48


Control Structures (For Statement)
• Now modify your written code such that it gives the following output:

Processing i = 0…
Processing i = 1…
Skipped i = 2
Processing i = 3…
Processing i = 4…

CS1004 - Spring 2025 49


Control Structures (For Statement)
• Now modify your written code such that it gives the following output:

#include <iostream>
using namespace std;
Output:
int main() { Processing i = 0…
for (int i = 0; i < 5; ++i) { Processing i = 1…
if (i == 2) { Skipped i = 2
cout << "Skipped i = " << i << endl; Processing i = 3…
continue; // Skip the rest of the loop for `i = 2` Processing i = 4…
}
cout << "Processing i = " << i << endl;
}
return 0;
}

CS1004 - Spring 2025 50

You might also like