0% found this document useful (0 votes)
7 views26 pages

Focus

This document provides an overview of C++ programming basics, including program structure, data types, variable naming rules, and constants. It covers essential concepts such as preprocessor directives, functions, string constants, and assignment statements. Additionally, it explains the use of the 'const' keyword and the 'endl' manipulator for output formatting.

Uploaded by

mahishashree76
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)
7 views26 pages

Focus

This document provides an overview of C++ programming basics, including program structure, data types, variable naming rules, and constants. It covers essential concepts such as preprocessor directives, functions, string constants, and assignment statements. Additionally, it explains the use of the 'const' keyword and the 'endl' manipulator for output formatting.

Uploaded by

mahishashree76
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/ 26

Unit 1 – Lecture 2

C++ Programming Basics


Dr. M. Ifjaz Ahmed
Assistant Professor
School of Computing
SASTRA Deemed to be University
Thanjavur - 613005
Basic Program Construction
#include<iostream>

using namespace std;

int main()

cout<<"Hello World\n";

return 0;

} Output: Hello World

Dr. M. Ifjaz Ahmed, AP - II, SoC, SASTRA 2


Directives
Preprocessor Directives Header Files
#include<iostream>
#include<iostream>
using namespace std;
using namespace std;
int main() {cout
int main()
<<
{
"Hello World\n”
cout<<"Hello World\n";
;
return 0;
return 0;
}
}
Output: Hello World Output: Hello World

Dr. M. Ifjaz Ahmed, AP - II, SoC, SASTRA 3


The using Directive
Preprocessor Directives Header Files
#include<iostream>
#include<iostream>
int main()
using namespace std;
{
int main()
std::cout<<"Hello World\n”;
{
return 0;
cout<<"Hello World\n";
}
return 0;

Output: Hello World Output: Hello World

Dr. M. Ifjaz Ahmed, AP - II, SoC, SASTRA 4


Comments
// comments.cpp
Two types
// demonstrates comments
Single line (//)
#include<iostream> //preprocessor directive // single line comment
int a=10; //inline comment
using namespace std; //”using” directive
Multiline comment (/* … */)
int main() //function name “main” /* this is
{ //start function body
line 2 and
line 3 */
cout<<"Hello World\n"; //statement

return 0; //statement

} //end function body

Output: Hello World

Dr. M. Ifjaz Ahmed, AP - II, SoC, SASTRA 5


Functions
#include<iostream>

using namespace std;

int main()
• Function Name
{ • Braces and Body of the
function
cout<<"Hello World\n"; • Always starts with main()

return 0;

Dr. M. Ifjaz Ahmed, AP - II, SoC, SASTRA 6


String Constants
String Constant

cout<<"Hello World\n";
• You can’t change during execution of the program.
• String can be represented in TWO ways.
1. Array of characters
2. Object of a class
Dr. M. Ifjaz Ahmed, AP - II, SoC, SASTRA 7
Output using “cout”
Object of Standard
Output Stream

cout<<"Hello World\n";

Insertion / Put to
Operator

Dr. M. Ifjaz Ahmed, AP - II, SoC, SASTRA 8


Output using “cout”
#include<iostream>
using namespace std;
int main() {
int a=3,b=5;
cout<<"This is Line 1\n"; This is Line 1
cout<<"Line 2"<<endl; Line 2
cout<<a<<"\t"<<b<<endl; 3 5
return 0;
}

Dr. M. Ifjaz Ahmed, AP - II, SoC, SASTRA 9


Output using “cout”
#include<iostream>
using namespace std;
int main()
{
int a=10,b=25;
cout<<"Addition of a and b=:"<<a+b<<endl;
cout<<"Subtraction of a and b=:"<<a-b<<endl;
cout<<"Multiplication of a and b=:"<<a*b<<endl;

return 0; Addition of a and b=:35


} Subtraction of a and b=:-15
Multiplication of a and b=:250
Dr. M. Ifjaz Ahmed, AP - II, SoC, SASTRA 10
Data Types in C++

❖ In C++, data types are used to specify the type of data a variable
can hold.
❖ These are broadly classified into
1. Built-in (primitive) types,
2. Derived types, and
3. User-defined types.

Dr. M. Ifjaz Ahmed, AP - II, SoC, SASTRA 11


Data Types in C++
1. Built-in (Primitive) Data Types
These are the basic types provided by the language.

Type Description Size (approx.) Example


int Integer type 4 bytes int a = 10;
Single-precision
float 4 bytes float b = 3.14f;
floating-point

Double-precision
double 8 bytes double c = 2.718;
floating-point
Single character
char 1 byte char d = 'A';
(ASCII)
Boolean type
bool 1 byte bool e = true;
(true/false)
Represents no value
void N/A void function();
(used for functions)
wchar_t Wide character type 2-4 bytes wchar_t f = L’B';
Dr. M. Ifjaz Ahmed, AP - II, SoC, SASTRA 12
Data Types in C++
2. Derived Data Types
Derived from primitive types.

Type Description Example

Collection of elements of the


Array int arr[5] = {1, 2, 3, 4, 5};
same type

Stores the address of another int* ptr1 = &a;


Pointer
variable Int *ptr2 = &b;

int& ref = a;
Reference Alias for another variable
Int &ref = b;
A block of code with a return
Function int add(int x, int y);
type

Dr. M. Ifjaz Ahmed, AP - II, SoC, SASTRA 13


Data Types in C++
3. User-defined Data Types
Created by the user to define custom types.

Type Description Example

Defines objects with attributes


Class class MyClass { public: int a; };
and methods

Structure Groups related variables together struct MyStruct { int x; float y; };

Shares memory among its


Union union MyUnion { int x; float y; };
members

Defines a set of named integral enum Color { RED, GREEN,


Enum
constants BLUE };

Defines a new name for an


Typedef / Alias typedef unsigned int uint;
existing type

Dr. M. Ifjaz Ahmed, AP - II, SoC, SASTRA 14


Data Types in C++
Type Modifiers in C++.
Modifiers are used with built-in data types to change their size or range.
Sizes of types depend on the compiler and platform.
Use <cstdint> for fixed-width integers like int32_t or uint64_t.

Modifier Description Example

Allows positive and negative


signed signed int a;
values

unsigned Allows only positive values unsigned int b;

short Reduces size of the integer short int c;

long Increases size of the integer long int d;

Dr. M. Ifjaz Ahmed, AP - II, SoC, SASTRA 15


Key Words in C++
atomic_noexcep
alignas alignof and and_eq asm atomic_cancel atomic_commit
t

auto bitand bitor bool break case catch char


char16_t char32_t class compl concept const const_cast consteval
constexpr constinit continue co_await co_return co_yield decltype default

delete do double dynamic_cast else enum explicit export

extern false float for friend goto if import

inline int long module mutable namespace new noexcept

not not_eq nullptr operator or or_eq private protected

public reflexpr register reinterpret_cast requires return short signed

sizeof static static_assert static_cast struct switch synchronized template

this thread_local throw true try typedef typeid typename

union unsigned using virtual void volatile wchar_t while


xor xor_eq

Dr. M. Ifjaz Ahmed, AP - II, SoC, SASTRA 16


Rules for Naming Variables in C++
Allowed Characters
Variable names may consist of letters (a–z, A–Z), digits (0–9), and the
underscore character ( _ ).
No other special characters (like @, #, $, etc.) are allowed in variable
names.
No Leading Digit
The first character of a variable name cannot be a digit.
For example, 1value is invalid, whereas value1 is valid.
No Reserved Keywords
You cannot use C++ reserved words (keywords) as variable names.
Examples of keywords include int, double, for, while, class, if, etc.

Dr. M. Ifjaz Ahmed, AP - II, SoC, SASTRA 17


Rules for Naming Variables in C++
Case Sensitivity
C++ is case-sensitive.
This means myVariable and MyVariable would be considered different
variables.
No Duplicate Names in the Same Scope
You cannot have two variables with the exact same name in the same
scope.
Length and Readability
Although the language does not impose a strict limit on variable
name length, it’s best practice to keep names descriptive and concise.
Overly long names or one-letter names can make code harder to read.

Dr. M. Ifjaz Ahmed, AP - II, SoC, SASTRA 18


Examples of Valid and Invalid Names
Variable Name Valid? Reason
total Yes Starts with a letter, only letters
Allowed: letters, digits,
total_1 Yes
underscore
_counter Yes Underscore followed by letters
1count No Starts with a digit
double No double is a reserved keyword
my#Var No # is not an allowed character
Case-sensitive, both are valid
myVar and MyVar Yes (but different variables)
but distinct

Dr. M. Ifjaz Ahmed, AP - II, SoC, SASTRA 19


Assignment Statements in C++
In C++, an assignment statement is used to give a variable (the
left-hand side, or LHS) a value (the right-hand side, or RHS). The
most basic assignment operator is the single equals sign (=).
Basic Assignment
int x;
x = 5; // Assign the value 5 to x
The expression on the RHS (5) is evaluated first.
The result is then stored in the variable on the LHS (x).
Multiple Assignments
You can chain assignments:
int a, b, c;
a = b = c = 10;
This effectively sets a, b, and c all to 10.
The assignment is evaluated right to left: b = c = 10 first, then a = (b=10).

Dr. M. Ifjaz Ahmed, AP - II, SoC, SASTRA 20


Assignment Statements in C++
Compound Assignments
C++ provides compound assignment operators, which are a shorthand for using both an
arithmetic operation and an assignment at once:
Operator Equivalent To Example Explanation
+= x=x+y x += y; Add y to x, then store in x.
-= x=x-y x -= y; Subtract y from x.
*= x=x*y x *= y; Multiply x by y.
/= x=x/y x /= y; Divide x by y.
%= x=x%y x %= y; Remainder of x / y.
<<= x = x << y x <<= y; Left-shift x by y bits.
>>= x = x >> y x >>= y; Right-shift x by y bits.
&= x=x&y x &= y; Bitwise AND of x and y.
^= x=x^y x ^= y; Bitwise XOR of x and y.
|= x=x|y x |= y; Bitwise OR of x and y.
Dr. M. Ifjaz Ahmed, AP - II, SoC, SASTRA 21
Initialization vs Assignment
Initialization vs. Assignment
Initialization happens when a variable is first declared. For example:
int x = 5; // Initialization
Assignment happens after a variable has already been declared.
int x; // Declaration
x = 5; // Assignment
Assignment as an Expression
In C++, the assignment x = 5 itself is an expression that evaluates to
the value assigned (5). Hence, you can do:
int x, y;
y = (x = 5) + 2; // The expression (x = 5) is 5, so y = 5 + 2 = 7

Dr. M. Ifjaz Ahmed, AP - II, SoC, SASTRA 22


Constants in C++
In C++, constants are values that cannot be modified once they
are defined. They improve code reliability and readability by
ensuring that important values remain unchanged.
Below are some key points about the different types of
constants in C++.
1. Literals
2. const Keyword
3. constexpr Keyword
4. enum Constants
5. #define Preprocessor Macro
6. static const and static constexpr in classes

Dr. M. Ifjaz Ahmed, AP - II, SoC, SASTRA 23


Constants in C++ - Literals
Literals are fixed values written directly in the code. They can be of different types:
Integer Literals
Examples: 10, 0, -25, 0xFF (hexadecimal), o10 (octal, though rarely used now).
May include suffixes to denote type/size (e.g., 10u for unsigned int, 10L for long, 10ULL for unsigned
long long).
Floating-Point Literals
Examples: 3.14, 2.0e5, 5.0F.
Suffixes like f or F denote float (e.g. 3.14f).
By default, a floating-point literal (without f or F) is double.
Character Literals
Example: 'A', '9', '\n'.
Wide characters: L'A' or Unicode characters: u'A', U'A'.
String Literals
Example: "Hello World".
Wide strings: L"Hello", u"Hello", U"Hello".
Boolean Literals
true or false.

Dr. M. Ifjaz Ahmed, AP - II, SoC, SASTRA 24


Constants in C++ - const Keyword
The const keyword makes a variable’s value immutable once
initialized. You must initialize it at the time of declaration.

const int MAX_SCORE = 100;

MAX_SCORE = 200; // Error: cannot modify a const variable


const can be applied to various data types (e.g., const double PI = 3.14;).

You can use const for pointer types in different ways (const pointer, pointer to const,
etc.).

Dr. M. Ifjaz Ahmed, AP - II, SoC, SASTRA 25


endl Manipulator
In C++, the endl (end line) manipulator is used with the output
stream (std::cout) to:
1. Insert a newline character into the output stream. This
effectively moves the cursor to the next line when printing to
the screen.
2. Flush the output buffer. Flushing ensures that all pending
output is immediately written (rather than waiting until the
buffer is full or the program ends).

std::cout << "End of the program" << std::endl; // endl inserts newline + flushes the stream

Dr. M. Ifjaz Ahmed, AP - II, SoC, SASTRA 26

You might also like