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

Lecture 4 - Variables Data Types

The document provides an overview of the fundamentals of computer programming using C++, including the basic structure of C++, variable declarations, literals, data types, and constants. It explains how to declare and initialize variables, the differences between variables and literals, and the importance of constants in programming. Additionally, it covers C++ operators, user input/output, and escape sequences.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

Lecture 4 - Variables Data Types

The document provides an overview of the fundamentals of computer programming using C++, including the basic structure of C++, variable declarations, literals, data types, and constants. It explains how to declare and initialize variables, the differences between variables and literals, and the importance of constants in programming. Additionally, it covers C++ operators, user input/output, and escape sequences.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 46

SCHOOL OF ELECTRICL ENGINEERING &

COMPUTER SCIENCE (SEECS)

Computer Programming (CS 107)


Sara Tariq Sheikh
Recap!
Key Points

Fundamentals of Computer Programming 2


Basic Structure of C++

Component Description Example

Includes necessary libraries using


Preprocessor Directives #include <iostream>
#include.

Allows using standard functions


Namespace Declaration using namespace std;
without std::.

The entry point where program


main() Function int main() { ... }
execution starts.

Defines variables of different data


Variable Declarations int num = 10;
types.
Input & Output (I/O) cout for output, cin for input. cout << "Enter a number: "; cin >>
num;

Basic Structure of C++


Basic Structure of C++

Component Description Example

Code executes inside {}; performs


Statements & Expressions sum = a + b;
operations.

Indicates successful execution of the


Return Statement return 0;
program.

Used for code explanations; ignored


Comments // Single-line or /* Multi-line */
by the compiler.

Basic Structure of C++


Example

#include <iostream> // Preprocessor Directive


using namespace std; // Namespace Declaration

int main() { // Main Function


int num; // Variable Declaration
cout << "Enter a number: /n "; // Output
cin >> num; // Input
cout << "You entered: " << num << endl; // Output Statement
return 0; // Return Statement
}

Basic Structure of C++


Today’s Agenda

• Literals

• Variables

• Data Types

Getting Started with C++ 6


Literals

Getting Started with C++ 7


Literals

• A literal in C++ is a constant value assigned directly to a variable.


• These values are fixed during program execution and do not
change.
• It can be alphabets/letters, numbers, or some keywords
• E.g. "Hello", 7.5, 4400, true, false
• It can also be in other languages " ‫ "َعَر ِبّي‬,"‫"اردو‬, " 日本語 "
• Cannot be directly used. It requires changing encoding of .cpp file

Getting Started with C++ 8


Types of Literals

Literal Type Example Description


Whole numbers without decimal
Integer Literals 10, 255, -89
points.
Numbers with decimals or in scientific
Floating-Point Literals 3.14, -0.001, 2.5E3
notation.
Single characters enclosed in single
Character Literals 'A', '9', '$'
quotes.
Sequence of characters enclosed in
String Literals "Hello", "C++", "123"
double quotes.
Boolean Literals true, false Represents truth values.
Null Pointer Literal nullptr Represents a null pointer.

Getting Started with C++ 9


Examples
#include <iostream>
using namespace std;

int main() {
int age = 25; // Integer literal
double pi = 3.14159; // Floating-point literal
char grade = 'A'; // Character literal
string name = “Sara"; // String literal
bool isPassed = true; // Boolean literal

cout << "Age: " << age << endl;


cout << "Pi: " << pi << endl;
cout << "Grade: " << grade << endl;
cout << "Name: " << name << endl;
cout << "Passed: " << isPassed << endl;

return 0;
}
Getting Started with C++ 10
Variables
• Variables are containers (locations in computer memory) to store
values
• Variables are defined using names (also known as identifiers) and
their data types
• The equal sign (=) is used to assign values to variables
• Example:
int age = 15;
15
Reserved memory for variable “age”
Data Type Value

Variable Name

RAM
Getting Started with C++ 11
Syntax

type variableName = value;

int a = 10;

Getting Started with C++ 12


Variable Declaration

• Declaring a variable means specifying both the variable’s name


and its data type.

• The declaration tells the compiler to associate a name with a


memory location whose contents are of a specific type (for
example, char or string).

Getting Started with C++ 13


Getting Started with C++ 14
Variable Declaration

• char letter, middleInitial, ch;


• Preferable to declare each variable using a separate statement.
• Makes it easier to modify a program - to add new variables to the
list or delete ones no longer required.
• Allows you to attach comments to the right of each declaration

Getting Started with C++ 15


Variables
• Declaration
int age, height, weigth;
string fullName;
• Tell compiler about the existence of a variable and its location
• Specify the variable name and its data type
• Initialization
• Assigning a value to a variable
age = 35;
fullName = "Sana Khan";
• Combining declaration and initialization
int x, y = 12, z;
string name = "Shah", roll_number;
Getting Started with C++ 16
Variables

• Declare and initialize a variable.


• Assign a value.
• Print it to screen.

Getting Started with C++ 17


Solution

int num;
num = 15;
cout << num;

What will happen if a assign a new value to num?

Getting Started with C++ 18


Variable Vs Literal

• A variable is a named storage location that can hold different


values during program execution.
• A literal is a fixed constant value assigned directly in the code.

int x = 10; // 'x' is a variable, '10' is a literal

Getting Started with C++ 19


Declaring Multiple Variables
int x = 5, y = 6, z = 50;
cout << x + y + z;

int x, y, z;
x = y = z = 50;
cout << x + y + z;

Getting Started with C++ 20


Variable Names – Restrictions
• Can only contain alpha-numeric characters (A-z, 0-9) and
underscores (_)

• Must start with a letter (A-z) or an underscore (_)


• Cannot start with a number

• Case-sensitive
• age, Age and AGE are three different variables

• Keywords/Reserved words can not be used as variable name

• Whitespace (space, tabs) and special characters (#,$,%,*, etc.)


cannot be used in variable name
Getting Started with C++ 21
Variable Names – Best Practices
• Choose meaningful names for variables

• Separate words with underscores to improve readability


• OR use camel case style (e.g., fullName)

• Starting with uppercase letters is not a good practice


• Class names are recommended to start with uppercase letters

• Starting with underscore is not a good practice


• Internal class variable are recommended to start with a single underscore

Getting Started with C++ 22


Constants
• Constants are variables whose values cannot be modified once
they are defined in the program

• In C++, the const keyword is used to define the constants

• Example:
const int NUM = 5; ✔

const int NUM; ✘

const int NUM; ✘


NUM = 5;

Getting Started with C++ 23


Constants

• Similar to Mathematics, a value of a constant never changes


• All single characters (enclosed in single quotes) and strings
(enclosed in double quotes) are constants e.g. ‘5’, “Enter a
number:” etc.
• We use constants when we do not want ourselves or others to
modify this value.
• These values are unchangeable and read-only.

Getting Started with C++ 24


Example – Expected Output?
#include <iostream>
using namespace std;

int main() {
const int myNum = 15;
myNum = 10;
cout << myNum;
return 0;
}
error: assignment of read-only variable 'myNum'

Getting Started with C++ 25


When should variables be declared as constants?

• Always declare the variable as constant when you have values that
are unlikely to change
• For example:
const int minutesPerHour = 60;
const float PI = 3.14;

Getting Started with C++ 26


Data Types

C++ Data Types

Primary Derived User-Defined

Integer Function Class

Character Array Structure

Boolean Pointer Union

Floating Point Reference Enum

Double Floating Point Typedef

Void

Wide Character

Getting Started with C++ 27


float vs. double

• The precision of a floating point value indicates how many digits the
value can have after the decimal point.
• The precision of float is only six or seven decimal digits, while
double variables have a precision of about 15 digits.
• Therefore, it is safer to use double for most calculations.

Getting Started with C++ 28


Primary Data Types
• Built-in or predefined data types that can be used directly
Memory
Data Type Keyword Possible Values
Required
Integer int 4 bytes -2,147,483,648 to 2,147,483,647
Unsigned Integer unsigned int 4 bytes 0 to 4,294,967,295
Character char 1 byte -128 to 127
Unsigned Character unsigned char 1 byte 0 to 255
Boolean bool 1 byte true or false
Floating Point float 4 bytes 3.4x10-38 to 3.4x1038
Double Floating Point double 8 bytes 1.7x10-308 to 1.7x10308
Wide Character wchar_t 2 bytes 0 to 65,536

C++ language provide the sizeof() function to check the size of the data types
29
Getting Started with C++
Keywords
Keywords in C++

• Keywords are the reserved

https://www.oreilly.com/library/view/sams-teach-yourself/0672327112/apb.html
words in a language

• Define the syntax and


structure of the language

• Cannot be used as an
identifier (variable name or
function name)
Getting Started with C++ 30
User Input/Output
• #include <iostream> is a header file that lets us work with input and
output objects
#include <iostream>
using namespace std;
• Output using cout int main() {
• cout is pronounced "see-out" string fullName;

cout << "Type your full name: ";


• Input using cin cin >> fullName;
• Pronounced "see-in“
cout << "Welcome " << fullName
<< " to NUST.\n";

return 0;
}
Getting Started with C++ 31
Escape Sequences in C++
• Sequences of characters to insert special characters in a string
• Starts with a backslash ( \ )
Escape Sequence Name Description
\\ Backslash Inserts a backslash character.
\’ Single quote Displays a single quotation mark.
\” Double quote Displays double quotation marks.
\? Question mark Displays a question mark.
\a Alert (bell) Generates a bell sound in the C++ program.
\b Backspace Moves the cursor one place backward.
\f Form feed Moves the cursor to the start of the next logical page.
\n New line Moves the cursor to the start of the next line.
\r Carriage return Moves the cursor to the start of the current line.
Inserts some whitespace to the left of the cursor and moves the cursor
\t Horizontal tab
accordingly.
\v Vertical tab Inserts vertical space.
\0 Null character Represents the NULL character.
\ooo Octal number Represents an octal number.
\xhh Hexadecimal number Represents a hexadecimal number.

https://www.geeksforgeeks.org/cpp-escape-sequences/
Getting Started with C++ 32
Escape Sequences in C++ - Examples
cout << "Welcome to \“EE\"\n You are in CS107.";
Welcome to “EE"
You are in CS107 Class.

cout << "Welcome to \“EE\"\r CS107 Class";


CS107 Class “EE"

cout << "\t" << 5 << "\t" << "\x65" << endl;
cout << "\t" << 10 << "\t" << "\073";
5 e
10 ;
Getting Started with C++ 33
C++ Operators

• Operators are used to perform operations on variables and values.


• Example :
int sum1 = 100 + 50;
int sum2 = sum1 + 250;
int sum3 = sum2 + sum2;

Getting Started with C++ 34


Types

• Arithmetic
• Assignment
• Comparison
• Logical
• Bitwise

Getting Started with C++ 35


Arithmetic Operators

Getting Started with C++ 36


Assignment Operator

• Assignment operators are used to assign values to variables.


• For example,
int x = 10;

Getting Started with C++ 37


Assignment Operators

Getting Started with C++ 38


Examples

Getting Started with C++ 39


Determine the Output
#include <iostream>
using namespace std;

int main() {
int x = 5;
x %= 3;
cout << x;
return 0;
}

Getting Started with C++


Understanding x &= 3
Assuming x = 6
Step 1:
Convert 6 and 3 to their decimal equivalents

Decimal Binary Representation

6 110

3 011

Getting Started with C++ 41


Understanding x &= 3
Step 2:
The bitwise AND (&) operator compares corresponding bits of two
numbers:
• If both bits are 1, the result is 1.
• Otherwise, the result is 0.
6 = 110 3 = 011 x=x&3

1 0 0

1 1 1

0 1 0

Getting Started with C++ 42


Understanding x &= 3
Step 3:
Convert the binary back to its decimal form.

Binary Decimal

010 2

So, x &=3 is equal to 2, and 6 will now become 2.

Getting Started with C++ 43


Determine the Output
#include <iostream>
using namespace std;

int main() {
int x = 5;
x &= 3;
cout << x;
return 0;
}

Getting Started with C++


Where is this Operator Useful?

• Used to extract specific bits from a number while ignoring others.


• Example: Checking if a number is even or odd.
• Used to turn off certain bits while keeping others unchanged.

Getting Started with C++ 45


Additional Resources
• C++ Inbuilt Data Types (Go4Expert)
• C++ Escape Sequences (GeeksforGeeks)

• Programming and Problem Solving with C++, 7th Edition


• Chapter 3: Numeric Types, Expressions, and Output
• Section 3.1 Overview of C++ Data Types
• Section 3.2 Numeric Data Types
• Section 3.3 Declarations for Numeric Types

Getting Started with C++ 46

You might also like