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

2. C-- Introduction

C++ is a versatile programming language developed by Bjarne Stroustrup in the 1980s, known for its object-oriented features suitable for system programming and game development. The document covers the basic structure, syntax, data types, operators, and variable handling in C++, providing examples and explanations for each topic. It also includes exercises to practice coding skills and understand concepts like string handling and arithmetic operations.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

2. C-- Introduction

C++ is a versatile programming language developed by Bjarne Stroustrup in the 1980s, known for its object-oriented features suitable for system programming and game development. The document covers the basic structure, syntax, data types, operators, and variable handling in C++, providing examples and explanations for each topic. It also includes exercises to practice coding skills and understand concepts like string handling and arithmetic operations.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 48

C++ Introduction

CS 111 - Computer Programming


What is C++?
• C++ is a highly efficient and versatile language, evolving from its predecessor C.

• It was developed by Bjarne Stroustrup in the early 1980s.

• C++ is particularly known for its powerful object-oriented features, making it a


top choice for system programming, game development, and complex
applications.
C++ Basic Structure
The structure of a typical C++ program includes:

• Header Files: Include statements for accessing standard library functions and
classes.

• Namespace Declaration: Commonly using namespace std; to avoid prefixing


with std::

• Function Definitions: Including the main() function where the execution starts.

• Statements and Expressions: To perform operations and computations.


C++ Syntax
let us work with input and
output objects.

means that we
can use names
blank line for for objects and
readability variables from
the standard
library.
This is called a
function. Any code
inside its curly
brackets {} will be
executed.

an object used together


with the insertion ends the main function.
operator (<<) to
output/print text.
Preprocessor Directives
• Preprocessor directives (those that begin by #), they are not statements.

• They are lines read and processed by the preprocessor before proper
compilation begins.

• Preprocessor directives must be specified in their own line and, because they
are not statements, do not have to end with a semicolon (;).
Headers
Header files in C++ contain declarations of functions and classes. Some
commonly used headers are:

<iostream>: For standard input and output stream objects like cin and cout.
<vector>: For using the vector container.
<string>: To use the string class.
<algorithm>: For common algorithms like sort, search, etc.
<cmath>: For mathematical functions.
C++ Statements
• In a programming language, these programming instructions are called
statements.

• The following statement "instructs" the compiler to print the text "Hello World"
to the screen:
Output
cout << "Hello World!";

cout << "Hello World!";


cout << "Have a good day!";
return 0;
C++ Statements

Output

cout << "Hello World! \n";


cout << "Have a good day!";
return 0;

cout << "Hello World!“ << endl;


cout << "Have a good day!";
return 0;
C++ Comments
Comments in C++:
• Single-Line Comments: Start with //.
• Multi-Line Comments: Enclosed between /* and */.

// This is a comment
cout << "Hello World!";
Single-line Comments
cout << "Hello World!"; // This is a comment

Multi-line Comments
/* The code below will print the words Hello World!
to the screen, and it is amazing */
cout << "Hello World!";
Standard Output (cout)
cout is used in conjunction with the insertion operator, which is written as
<< (two "less than" signs).

cout << "Hello World!";


cout << "120";
cout << “x”;
Standard Input (cin)
cin applying the overloaded operator of extraction, which is written as
>> (two “greater than" signs).

int age;

cout << "Enter your age: ";


cin >> age;
cout << "You are " << age << " years old.";
Try this! (Codechum)
Try this! (Codechum)
Basic Data Types
The data type specifies the size and type of information the variable will store:

Data Type Size Description

int 4 bytes Stores whole numbers, without decimals.

Stores fractional numbers, containing one or more decimals.


float 4 bytes
Sufficient for storing 7 decimal digits
Stores fractional numbers, containing one or more decimals.
double 8 bytes
Sufficient for storing 15 decimal digits

boolean 1 byte Stores true or false values

char 1 byte Stores a single character/letter/number, or ASCII values


Numeric Types
int float double
int num = 1000; float num = 5.75; double num = 19.99;
cout << num; cout << num; cout << num;

Note:
float precision ~6 to 7 decimal places
double precision ~15 to 16 decimal places

3.141592 3.141592653589793
• A float can store fewer decimal places (~6-7), leading to small
errors.
• A double is more precise (~15-16 decimal places) and is used in
most calculations requiring accuracy.
Boolean Type
• A boolean data type is declared with the bool keyword, take the values
true or false.
• When the value is returned, true = 1 and false = 0.
• Boolean values are mostly used for conditional testing.

bool isCodingFun = true;


bool isFishTasty = false;
cout << isCodingFun; // Outputs 1 (true)
cout << isFishTasty; // Outputs 0 (false)
Character Type
• The smallest integral data type.
• Used for characters: letters, digits, and special symbols.
• Each character is enclosed in single quotes.
'A', 'a', '0', '*', '+', '$', '&'
• A blank space is a character and is written ' ', with a space left between
the single quotes.

char myGrade = 'B';


cout << myGrade;
String Type
• The string type is used to store a sequence of characters (text).
• String values must be surrounded by double quotes “ ”.
• Each character has relative position in string.
• Position of first character is 0
• Length of a string is number of characters in it
• Example: length of "William Jacob" is 13.

// Include the string library


string greeting = "Hello"; #include <string>
cout << greeting; // Create a string variable
string greeting = "Hello";
// Output string value
cout << greeting;
Challenge 1: A. Identify the data type used.
1. float myFloatNum = 5.99;
2. int myNum = 5;
3. double myDoubleNum = 9.98;
4. char myLetter = 'D';
5. bool myBoolean = true;
6. string myText = "Hello";
Identifiers
• All C++ variables must be identified with unique names.
• These unique names are called identifiers.
• Identifiers can be short names (like x and y) or more descriptive names (age,
sum, totalVolume).

Note: It is recommended to use descriptive names in order to create


understandable and maintainable code.

Data Types int a; Identifiers


int & float float mynumber; a & mynumber
Rules for Identifiers
• Can contain letters (A-Z, a-z), digits (0-9), and underscores (_).

• Cannot start with a digit (e.g., 1value is invalid).

• Cannot be a reserved word (e.g., int, float, if, while, etc.).

• Case-sensitive (age and Age are different identifiers).

GOOD: spam Eggs Spam23 _speed


BAD: 23spam #sign var.12 a?b
DIFFERENT: spam Spam SPAM sPam
Reserved Words
Cannot be use as variable names / identifiers.
and and_eq asm auto bitand
bitor bool break case catch
char class const const_cast continue
default delete do double dynamic_cast
else enum explicit export extern
false float for friend goto
if inline int long mutable
namespace new not not_eq operator
or or_eq private protected public
register reinterpret_cast return short signed
sizeof static static_cast struct switch
template this throw true try
typedef typeid typename union unsigned
using virtual void volatile wchar_t
while xor xor_eq
Variables
• Variables are containers for storing data values.
• A variable is a storage location in memory with a name (identifier) and a data
type.
To create a variable, specify the type, identifier and assign it a value:

type identifier = value;

Try this!
Create a variable called myNum of type int and assign it the value 15.

int myNum = 15;


cout << myNum;
Declaring Variables
You can also declare a variable without assigning the value, and assign the value
later:

int myNum;
myNum = 15;
cout << myNum;

Note that if you assign a new value to an existing variable, it will overwrite the previous
value:

int myNum = 15; // myNum is 15


myNum = 10; // Now myNum is 10
cout << myNum; // Outputs 10
Other Types
int myNum = 5; // Integer (whole number without decimals)
double myFloatNum = 5.99; // Floating point number (with decimals)
char myLetter = 'D'; // Character
string myText = "Hello"; // String (text)
bool myBoolean = true; // Boolean (true or false)
Display Variables
• The cout object is used together with the << operator to display variables.
• To combine both text and a variable, separate them with the << operator:

int myAge = 35;


cout << "I am " << myAge << " years old.";

Add Variables Together


• To add a variable to another variable, you can use the + operator:

int x = 5;
int y = 6;
int sum = x + y;
cout << sum;
C++ Constants
When you do not want others (or yourself) to change existing variable values, use
the const keyword.

You should always declare the variable as constant when you have values that are
unlikely to change:

const int minutesPerHour = 60;


const float PI = 3.14;
Try this!
// Student data
int studentID = 15;
int studentAge = 23;
float studentFee = 75.25;
char studentGrade = 'B';

// Print variables
cout << "Student ID: " << studentID << "\n";
cout << "Student Age: " << studentAge << "\n";
cout << "Student Fee: " << studentFee << "\n";
cout << "Student Grade: " << studentGrade << "\n";
Practice Exercise 2: (not graded)

Problem:
Calculate the area of a rectangle given its length and width.

Task:
1. Create an Algorithm
2. Create an IPO (Input-Process-Output) Chart
3. Draw a Flowchart
4. Write the C++ Code
Practice Exercise 2: (not graded)
Expected Output:
OPERATORS
Arithmetic Operators
• Arithmetic operators are fundamental elements of any programming
language, including C++.

• They allow you to perform mathematical operations on numeric values.


Basic Arithmetic Operators
Arithmetic Operators
int main() {
int a = 10, b = 5;
int sum = a + b; // Addition
int difference = a - b; // Subtraction
int product = a * b; // Multiplication
int quotient = a / b; // Division
int remainder = a % b; // Modulus
int increment = ++a; // Increment Output:
int decrement = --b; // Decrement

cout << "Sum: " << sum << endl;


cout << "Difference: " << difference << endl;
cout << "Product: " << product << endl;
cout << "Quotient: " << quotient << endl;
cout << "Remainder: " << remainder << endl;
cout << "Increment: " << increment << endl;
cout << "Decrement: " << decrement << endl;
}
Operator Precedence
• All operations inside of () are evaluated first.

• *, /, and % are at the same level of precedence and are evaluated next.

• + and - have the same level of precedence and are evaluated last.

• When operators are on the same level


Performed from left to right (associativity)
Example
int result = 5 + 2 * 3 - 4 / 2;

Multiplication and Division (evaluated first):


2*3=6
4/2=2
The expression becomes: 5 + 6 - 2

Addition and Subtraction (evaluated next):


5 + 6 = 11
11 - 2 = 9

Final result:
The value of result will be 9.
Assignment Operator
• Assignment operators are used to assign values to variables in programming
languages, including C++.

• They provide a concise and efficient way to update the value of a variable
based on a computation or another variable's value.
Example
STRING HANDLING
String Concatenation
• String concatenation is the process of combining two or more strings into a
single string.
String Copying
• String copying involves copying the contents of one string to another. In C++,
you can simply assign one string to another using the assignment operator
(=).
Practice Exercise 2: (not graded)
Simple Average Calculator

Instructions:
Prompt the user to enter three numbers.
Use arithmetic operators to calculate the sum and average.
Sum = number1 + number2 + number3
Average = Sum ÷ 3.

Display the sum and average using cout.


Bitwise Operator
• Bitwise operators are used to manipulate individual bits of binary numbers in
computer programming.

• These operators operate on the binary representation of numbers at a bit-


level, allowing you to perform operations like bit manipulation, bit testing, and
shifting.
Bitwise Operators
Bitwise Operators
Bitwise Operators
Bitwise Operators

You might also like