0% found this document useful (0 votes)
12 views22 pages

Chapter - 2 Cp1 (Notion)

Chapter 2 discusses data types and variables in C++, detailing basic data types such as int, float, char, and bool, along with their memory considerations and variations. It emphasizes the importance of choosing the correct data type for efficient memory usage and accurate data processing. The chapter also includes examples of how to use these data types in programming.

Uploaded by

Elias
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views22 pages

Chapter - 2 Cp1 (Notion)

Chapter 2 discusses data types and variables in C++, detailing basic data types such as int, float, char, and bool, along with their memory considerations and variations. It emphasizes the importance of choosing the correct data type for efficient memory usage and accurate data processing. The chapter also includes examples of how to use these data types in programming.

Uploaded by

Elias
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

🧑🏽‍💻

Chapter - 2 | DATA TYPES AND


VARIABLES

Data Types and Values in C++


In C++, data types define the kind of data a variable can hold. The type of data
also determines how much memory is allocated and how the data is processed.
Here's an overview of the key data types in C++:

1. Basic Data Types:


int: Represents integers (whole numbers). Example: int a = 5;

float: Represents floating-point numbers (numbers with decimal points).


Example: float b = 3.14;

char: Represents a single character (such as a letter or symbol). Example: char


c = 'A';

bool: Represents boolean values, either true or false . Example: bool flag =
true;

2. Integer Modifiers:
The int data type can be modified to handle different ranges of values:

int: Standard integer (can store both positive and negative whole numbers).

unsigned int: Can store only positive whole numbers (without negative
values).

short: A smaller integer, typically using less memory than int (can store a
smaller range of values).

unsigned short: A smaller integer that stores only positive values.

Chapter - 2 | DATA TYPES AND VARIABLES 1


unsigned long: A larger integer that stores only positive values.

3. Memory Considerations:
Different data types consume different amounts of memory. For example:

An int might take 2 or 4 bytes depending on the system.

A char typically takes 1 byte.

A float typically takes 4 bytes.

The correct number of bytes must be accessed for accurate data processing.

Data Type Size (in bytes)


char 1 byte
int 4 bytes
unsigned int 4 bytes
float 4 bytes
double 8 bytes
bool 1 byte
long 4 bytes
long long 8 bytes

4. Why Data Types Matter:


Internal Representation: The data type determines how data is represented in
memory (as a sequence of bits).

Memory Allocation: Each data type allocates a specific amount of memory to


store values. This is important for efficient memory usage and preventing
errors when accessing memory.

By understanding the proper data types and their modifiers, you can ensure your
program stores and processes data correctly.

Chapter - 2 | DATA TYPES AND VARIABLES 2


1. Integer Data Type
The int data type in C++ is used to store whole numbers (integers), which can
be both positive and negative. Here's a breakdown of its variations:

Size and Range:

Typically, the size of int is 2 or 4 bytes depending on the system. On


most modern systems, it is 4 bytes.

Range for int :

Usually, from 2,147,483,648 to +2,147,483,647 when it takes 4 bytes


(32-bit system).

Variations:

short: This is a smaller integer data type, typically using 2 bytes. The
range is from 32,767 to +32,767.

unsigned short: This is a version of short that can store only positive
numbers, ranging from 0 to 65,535.

long: A larger integer, typically using 4 bytes on most modern systems.


The range is from 2,147,483,648 to +2,147,483,647.

Chapter - 2 | DATA TYPES AND VARIABLES 3


unsigned long: Similar to long , but only stores positive numbers, with a
range of 0 to 4,294,967,295.

Key Points:
short is used when the range of numbers is small (e.g., -32,767 to +32,767).

unsigned short is used when only positive numbers are needed and when you
want to store a larger range (e.g., 0 to 65,535).

long is used when a larger range is required, like when working with large
values.

2. Floating-Point Data Types


The float and double data types in C++ are used to store numbers with decimals
(floating-point numbers). Here's a breakdown:

float:

Typically stores numbers with 6 digits of precision.

It uses 4 bytes of memory.

Use cases: Ideal for storing measurements, fractions, and approximations


when high precision is not necessary.

double:

Provides about 16 to 17 digits of precision (about twice the precision of


float ).

Typically uses 8 bytes of memory.

Use cases: Used when higher precision is required, especially in scientific


calculations or when dealing with very large or small numbers.

Key Points:
float is good for rough approximations or when memory is a concern, as it
uses less memory.

double is used when you need more precision and accuracy in floating-point
calculations.

Chapter - 2 | DATA TYPES AND VARIABLES 4


Example:

float a = 3.14; // A float with 6 digits of precision


double b = 3.141592653589793; // A double with higher precis
ion

Note: Even though float is used for calculations, internally, all floating-point
numbers are treated as double during operations.

Summary
Use int for counting whole numbers.

Use float for approximations with decimals and when memory is limited.

Use double for higher precision and more accurate floating-point calculations.

Use short and long when you need to limit or expand the range of integers.

Choosing the right data type ensures better memory usage and accuracy in your
programs.

3. Char Data Type


In C++, the char data type is used to store single characters or character strings.
Here's an overview:

1. Single Character ( char ):

The char type is used to store a single character. This can be any letter,
number, or special character (such as a , 1 , @ , etc.).

Range: The char type typically holds a 1-byte value, which can represent an
ASCII value. It can store values from 127 to +127 (or 0 to 255 in the unsigned
version).

2. Character Strings:

A character string is a collection of single characters, represented as a


sequence of characters enclosed in double quotes ( " " ).

For example, "Hello" is a character string containing the characters 'H' ,


'e' , 'l' , 'l' , 'o' .

Chapter - 2 | DATA TYPES AND VARIABLES 5


Key Points:
Single character: 'A' , '1' , or '#' (enclosed in single quotes).

Character string: "A" , "123" , or "Hello World" (enclosed in double quotes).

Each char uses 1 byte of memory.

Character constants like 'A' refer to individual characters, while strings like
"A" refer to a collection of characters.

Example 1: Using char Data Type

#include<iostream.h>
main()
{
// Declare and initialize char variables
char ltr_1 = 'C', ltr_2 = ' ', ltr_3 = 'i', ltr_4 = 's',
ltr_5 = ' ',
ltr_6 = 'g', ltr_7 = 'r', ltr_8 = 'e', ltr_9 = 'a',
ltr_10 = 't', ltr_11 = '!';

// Output each character


cout << "\n" << ltr_1 << ltr_2 << ltr_3 << ltr_4 << ltr_5
<< ltr_6 << ltr_7
<< ltr_8 << ltr_9 << ltr_10 << ltr_11;
}

Output:

C is great!

In this example, the program uses separate char variables to store individual
characters of the string "C is great!". The characters are displayed in sequence to
form the sentence.

Example 2: Displaying a Character String

Chapter - 2 | DATA TYPES AND VARIABLES 6


Now, let's write a program to display the string "I Love ETHIOPIA!".

#include<iostream.h> // Include header for input/output strea


m

void main()
{
// Define individual characters for the string "I Love ET
HIOPIA!"
char charvar1 = 'I'; // 'I'
char charvar2 = ' '; // space
char charvar3 = 'L'; // 'L'
char charvar4 = 'o'; // 'o'
char charvar5 = 'v'; // 'v'
char charvar6 = 'e'; // 'e'
char charvar7 = ' '; // space
char charvar8 = 'E'; // 'E'
char charvar9 = 'T'; // 'T'
char charvar10 = 'H'; // 'H'
char charvar11 = 'I'; // 'I'
char charvar12 = 'O'; // 'O'
char charvar13 = 'P'; // 'P'
char charvar14 = 'I'; // 'I'
char charvar15 = 'A'; // 'A'
char charvar16 = '!'; // '!'

// Display the characters as a string


cout << charvar1 << charvar2 << charvar3 << charvar4 << c
harvar5 << charvar6
<< charvar7 << charvar8 << charvar9 << charvar10 <<
charvar11 << charvar12
<< charvar13 << charvar14 << charvar15 << charvar16;
}

Output:

Chapter - 2 | DATA TYPES AND VARIABLES 7


I Love ETHIOPIA!

This example shows how to store each character in its own char variable and then
display them to form a sentence.

Program 2: Example of Special char Characters


In C++, char can also be used for special characters like tabs ( \t ) or newlines
( \n ). Here’s an example:

#include<iostream.h> // Include header for input/output strea


m

void main()
{
char charvar1 = 'A'; // Define Char Variable as Character
char charvar2 = '\t'; // Define Char Variable as tab (hor
izontal tab)

// Display the Character and the tab


cout << charvar1; // Output 'A'
cout << charvar2; // Output tab character
cout << 'B'; // Output 'B' after tab
}

Output:

A B

The output shows the character 'A', followed by a tab (produced by \t ), and then
the character 'B' after the tab space.

Key Takeaways:
char is used to store a single character.

Chapter - 2 | DATA TYPES AND VARIABLES 8


Character strings are collections of characters enclosed in double quotes ( "
" ).

You can use special characters like tabs ( \t ) and newlines ( \n ) with char .

Each char variable occupies 1 byte of memory.

Let me know if you need more details or examples!

EXERCISE
Here is a C++ program that uses char data type and character strings to
display the required output:

#include<iostream.h> // Include the input/output header fi


le

void main()
{
// Output for "A) C D E F"
char letter1 = 'C';
char letter2 = 'D';
char letter3 = 'E';
char letter4 = 'F';

cout << letter1 << " " << letter2 << " " << letter3 <<
" " << letter4 << endl; // Print with spaces and move to
the next line

// Leave a line between the outputs


cout << endl;

// Output for "B) Her Unearth Beauty Blinded me that I


can’t see and appreciate the beauty of others"
char part1[] = "Her ";
char part2[] = "Unearth ";
char part3[] = "Beauty ";
char part4[] = "Blinded ";
char part5[] = "me ";

Chapter - 2 | DATA TYPES AND VARIABLES 9


char part6[] = "that ";
char part7[] = "I ";
char part8[] = "can’t ";
char part9[] = "see ";
char part10[] = "and ";
char part11[] = "appreciate ";
char part12[] = "the ";
char part13[] = "beauty ";
char part14[] = "of ";
char part15[] = "others";

cout << part1 << part2 << part3 << part4 << part5 << p
art6 << part7 << part8
<< part9 << part10 << part11 << part12 << part13
<< part14 << part15 << endl;

// Leave another line between the outputs


cout << endl;

// Output for "C) P R O G R A M"


char letter5 = 'P';
char letter6 = 'R';
char letter7 = 'O';
char letter8 = 'G';
char letter9 = 'R';
char letter10 = 'A';
char letter11 = 'M';

cout << letter5 << " " << letter6 << " " << letter7 <<
" " << letter8 << " "
<< letter9 << " " << letter10 << " " << letter11
<< endl;
}

Output:

Chapter - 2 | DATA TYPES AND VARIABLES 10


C D E F

Her Unearth Beauty Blinded me that I can’t see and appreci


ate the beauty of others

P R O G R A M

Explanation:
1. Part A: We use individual char variables for each character ( C , D , E , F ),
and print them with spaces in between using cout .

2. Part B: For the sentence, each word is stored in a separate char array
(character string), and we concatenate them using cout to form the full
sentence.

3. Part C: Similarly to Part A, each letter of the word "PROGRAM" is stored in


a char variable and displayed with spaces between them.

The program leaves a blank line between each output part as requested.

4. Bool Data Type


The bool data type in C++ is used to represent Boolean values, which can be
either true or false . These are essential in logic and control flow, helping to make
decisions in a program. Here's a breakdown of the key points:

1. Boolean Expressions: A Boolean expression evaluates to true or false . It


typically involves relational operators (like == , > , < ) or logical operators ( && ,
|| ).

2. Boolean Algebra: Named after George Boole, Boolean algebra is fundamental


to logic operations in programming and computing.

3. Boolean Values in C++:

false is represented by 0 (integer).

true is represented by any non-zero value (usually 1 ).

Chapter - 2 | DATA TYPES AND VARIABLES 11


C++ specifically uses bool type for clarity and readability when dealing
with logical values.

4. Example Program Using bool :

#include<iostream.h>
#include<conio.h>

int main() {
clrscr(); // Clears the screen
int b, n;

b = 10;
cout << "Enter the number n: ";
cin >> n;

if (b == n) {
cout << "This is executed." << endl;
} else {
cout << "This is not executed." << endl;
}

// Using relational operators


cout << "b > n is " << (b > n) << endl; // Evaluates to
1 (true) or 0 (false)
cout << "b < n is " << (b < n) << endl; // Evaluates to
1 (true) or 0 (false)

return 0;
}

Explanation:
Relational Operators: In the program, the conditions b == n , b > n , and b < n

evaluate to Boolean values ( true or false ).

b == n checks if b is equal to n .

Chapter - 2 | DATA TYPES AND VARIABLES 12


b > n and b < n evaluate whether b is greater than or less than n ,
respectively, returning 1 for true and 0 for false.

Output Example:

Enter the number n: 10


This is executed.
b > n is 0
b < n is 0

Important Points:
Storage of Boolean Values: Although bool only has two logical states ( true
and false ), it is typically stored using 1 byte of memory, where false is
represented by 0 and true by 1 .

Convenience: Using the bool data type makes your code more readable and
clear when working with logical expressions, rather than using int or other
numeric types to represent truth values.

Size of Integers
The sizeof() operator in C++ is used to determine the size (in bytes) of a data
type or variable on your system. Different systems might have different sizes for
data types, but the sizeof() operator provides the exact size based on the system
you're running your program on.

Here’s a breakdown of how the sizeof() operator works in the example program
you provided:

C++ Program to Determine the Size of Data Types

#include <iostream.h>
#include <conio.h>

int main() {
clrscr (); // Clears the screen

Chapter - 2 | DATA TYPES AND VARIABLES 13


// Output the size of various data types using sizeof()
cout << "The size of an int is:\t\t" << sizeof(int) << "
bytes \n";
cout << "The size of a short int is:\t" << sizeof(short)
<< " bytes.\n";
cout << "The size of a long int is:\t" << sizeof(long) <<
" bytes.\n";
cout << "The size of a char is:\t\t" << sizeof(char) << "
bytes.\n";
cout << "The size of a float is:\t\t" << sizeof(float) <<
" bytes.\n";
cout << "The size of a double is:\t" << sizeof(double) <<
" bytes.\n";

return 0;
}

Explanation of Output:
sizeof(int) : The size of an int can vary depending on the system. On many
modern systems, it is 4 bytes, but it can also be 2 bytes on older or less
common systems.

sizeof(short) : The short integer type typically takes 2 bytes.

sizeof(long) : On many systems, a long integer is 4 bytes, but on some


systems, it could be 8 bytes.

sizeof(char) :A char is usually 1 byte, regardless of the system.

sizeof(float) :A float is typically 4 bytes.

sizeof(double) :A double is typically 8 bytes, though it can vary depending on


the system.

Example Output on a Common 64-bit System:

Chapter - 2 | DATA TYPES AND VARIABLES 14


The size of an int is: 4 bytes
The size of a short int is: 2 bytes.
The size of a long int is: 4 bytes.
The size of a char is: 1 bytes.
The size of a float is: 4 bytes.
The size of a double is: 8 bytes.

Key Points:
Consistency on One Machine: The size of a data type is consistent on a given
machine. Once you determine the size, it doesn’t change during program
execution.

System Dependency: The actual size of a data type may differ from one
machine to another, so using sizeof() helps determine the exact size for the
current system.

char size: char is always 1 byte in C++, even though its value can be positive
or negative, based on the system’s representation.

This program allows you to check and understand how much memory each data
type takes up on the system you're working on.

Constants (Literals)
In C++, constants (also known as literals) are used to store values that remain
unchanged throughout the execution of a program. These constants can either be
literal constants (directly used values in the program) or symbolic constants
(named constants using the const keyword). Here's a detailed explanation:

1. Literal Constants
A literal constant is a fixed value used directly in the program, like 3.14 , 100 , or
'A' . These are simply written in the code and represent a fixed value without the

need for any variable.


Example:

Chapter - 2 | DATA TYPES AND VARIABLES 15


double pi = 3.14159; // 3.14159 is a literal constant

2. Symbolic Constants
A symbolic constant is defined with a specific name and can be used throughout
the program. Using the const keyword, symbolic constants cannot be changed
after they are assigned.
Example:

const int MAX = 100; // MAX is a symbolic constant with a val


ue of 100

The const keyword ensures that the value of MAX cannot be modified once it is
initialized.

C++ Program Using Constants (Literals)

#include<iostream.h>

main() {
const int MAX = 100; // Define a symbolic constant MAX
cout << "MAX = " << MAX << endl;

int z, y;
z = (MAX) * 2; // Using the constant MAX in calculations
cout << "Z = " << z << endl;

y = (MAX) * 3 + 10; // Another calculation with MAX


cout << "Y = " << y << endl;
}

Explanation of the Program:


1. Constant Declaration: const int MAX = 100; declares MAX as a constant integer
with the value 100.

Chapter - 2 | DATA TYPES AND VARIABLES 16


2. Using the Constant: The constant MAX is used in calculations to find the
values of z and y .

z = (MAX) * 2; results in z = 200 .

y = (MAX) * 3 + 10; results in y = 310 .

3. Output: The program outputs the values of MAX , z , and y .

Output Example:

MAX = 100
Z = 200
Y = 310

Key Points:
Literal Constants: Fixed values directly used in expressions or assignments,
such as 3.14159 or 100 .

Symbolic Constants: Named constants using the const keyword, which


cannot be modified after initialization, like const int MAX = 100; .

Improves Readability and Safety: Using symbolic constants makes the code
more readable and avoids mistakes caused by changing values accidentally.

By using constants, programs become easier to maintain, more readable, and less
error-prone.

Working with Escape Characters


Escape characters are special sequences in C++ that allow you to include
characters in strings that would otherwise be difficult to express. These
characters are preceded by a backslash ( \ ), and they represent actions or
characters that are not easily typed or displayed directly. Here's a breakdown of
how they work:

Common Escape Characters:

Chapter - 2 | DATA TYPES AND VARIABLES 17


\n : Line feed or new line. Moves the cursor to the beginning of the next line.

\t : Horizontal tab. Moves the cursor to the next tab stop.

\b : Backspace. Moves the cursor back one space.

\\ : Backslash. Used to display a backslash.

\’ : Single quote. Used to display a single quote (for example, in character


literals).

\" : Double quote. Used to display a double quote inside a string.

Example Program with Escape Characters

#include<iostream.h>

main() {
cout << "He said, \"This is a quote\".\n"; // Use \" to p
rint quotes inside a string
cout << "\"This displays on one line, and this on the nex
t\".\n"; // Newline after text
cout << "\"The new line Character is \".\n"; // Newline w
ith explanation
cout << "\"She said \"I Love\" in reply to Hirut’s Questi
on.\""; // Escaping double quotes inside a string
}

Explanation of the Code:


1. First line: The string He said, \"This is a quote\".\n uses the escape character
\" to include double quotes inside the string. The \n is used to create a new
line after the string.

2. Second line: The string \"This displays on one line, and this on the next\".\n uses
the escape sequence for double quotes and also creates a new line at the end
with \n .

3. Third line: Similar to the previous examples, using escape sequences to


display the double quotes and a newline.

Chapter - 2 | DATA TYPES AND VARIABLES 18


4. Fourth line: The string \"She said \"I Love\" in reply to Hirut’s Question.\"

includes both single and double quotes using escape characters.

Output of the Program:

He said, "This is a quote".


"This displays on one line, and this on the next".
"The new line Character is ".
"She said "I Love" in reply to Hirut’s Question."

Key Points:
Escape Characters are used to represent characters that can't be typed
directly in a string (e.g., quotes, backslashes, new lines).

\n creates a new line.

\"and \’ allow you to use double and single quotes inside strings,
respectively.

\\ is used to include a backslash in a string.

By using these escape characters, you can format strings and include special
characters in your output.

Explanation of Key Concepts

1. The Concept of a Variable:


A variable is a container used to store a value in a program. The value of a
variable can change as the program runs. Variables allow programs to store and
manipulate data during execution, making them essential for almost any task in
programming.

Memory Access: When you use a variable, you're actually accessing a


specific location in the computer's memory.

Mutable Nature: Unlike constants (which have fixed values), variables are
designed to hold values that can change over time.

Chapter - 2 | DATA TYPES AND VARIABLES 19


Importance: Without variables, programs would not be able to handle dynamic
data and would be extremely limited.

2. Declaring Variables in C++:


Before you use a variable in a C++ program, it must be declared, which tells the
program the type of data it will store. The syntax for declaring a variable is:

data_type variable_name;

Example:

int myAge; // Declares an integer variable called myAge

You can also initialize a variable during its declaration:

int myAge = 22; // Declares an integer variable and initiali


zes it to 22

Uninitialized Variables: If a variable is declared but not initialized, its value is


undefined, leading to unreliable results (garbage values).

3. Variable Initialization:
Initialization is the process of giving a variable an initial value when it is declared.
For example:

int myAge = 22; // myAge is initialized to 22

Best Practice: Always initialize your variables to avoid undefined behavior.

4. Naming Variables:
Variable names in C++ must follow specific rules:

1. Must start with a letter (a-z, A-Z) or an underscore (_).

2. Can be followed by letters, digits (0-9), or underscores.

3. Are case-sensitive (e.g., myVariable and MyVariable are different).

Chapter - 2 | DATA TYPES AND VARIABLES 20


4. Cannot be keywords (e.g., int , return , for ).

5. Cannot contain special characters (e.g., spaces, periods, commas).

5. Variable Scope:
Variables have different scopes, which define where they can be accessed in the
program.

Global Scope: A variable declared outside any function can be accessed from
anywhere in the program.

Local Scope: A variable declared inside a function or a block (e.g., loops,


conditionals) can only be accessed within that function or block.

Example of Local and Global Variables:

#include <iostream.h>

int globalVar = 100; // Global variable

main() {
int localVar = 50; // Local variable
cout << "Global Variable: " << globalVar << endl;
cout << "Local Variable: " << localVar << endl;
}

Global variables can be used in any function that appears after their
declaration.

Local variables are only accessible within the block where they are defined.

6. Program Example to Show Variable Initialization and Scope:

#include<iostream.h>

int x; // Global variable

main() {

Chapter - 2 | DATA TYPES AND VARIABLES 21


x = 65; // Initialize global variable
cout << x << endl; // Output: 65

x = 90; // Change global variable value


cout << x << endl; // Output: 90
}

Output:

65
90

Key Points Recap:


Variable Declaration: Before use, a variable must be declared with a type, and
optionally initialized.

Garbage Value: If a variable is not initialized, it holds a random value that can
lead to errors.

Variable Scope: Defines where a variable can be accessed. Local variables


are limited to the function or block they are declared in, while global variables
can be accessed anywhere in the program.

Best Practice: Always initialize your variables, and give them meaningful
names to improve readability.

Chapter - 2 | DATA TYPES AND VARIABLES 22

You might also like