0% found this document useful (0 votes)
63 views52 pages

Block-1: Unit-Ii

C++ is an object-oriented programming language that is a superset of C. It supports features like polymorphism, encapsulation, and inheritance. This document provides an overview of key C++ concepts like data types, variables, operators, and literals. It also compares C and C++, describing how C++ added object-oriented capabilities that C lacked.

Uploaded by

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

Block-1: Unit-Ii

C++ is an object-oriented programming language that is a superset of C. It supports features like polymorphism, encapsulation, and inheritance. This document provides an overview of key C++ concepts like data types, variables, operators, and literals. It also compares C and C++, describing how C++ added object-oriented capabilities that C lacked.

Uploaded by

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

BLOCK-1

UNIT-II
BASICS OF C++
Character Set
The character set is a combination of English language
comprising of the alphabets and the White spaces and
some symbols from the mathematics including the
Digits and the Special symbols. C++ character set
means the characters and the symbols that are
understandable and acceptable by the C++ Program.
These are grouped to create and give the commands,
expressions, words, c-statements, and some of the
other tokens for the C++ Language.
IDENTIFIERS
1. Constants
2. Variables
3. Functions
4. Labels
5. Defined data types

Some naming rules are common in both C and C++. They are as follows:

Only alphabetic characters, digits, and underscores are allowed.

The identifier name cannot start with a digit, i.e., the first letter should be

alphabetical. After the first letter, we can use letters, digits, or underscores.

In C++, uppercase and lowercase letters are distinct. Therefore, we can say that C++

identifiers are case-sensitive.

A declared keyword cannot be used as a variable name.


KEYWORDS
Keywords (also known as reserved words) have
special meaning to the C++ compiler and are
always written or typed in short(lower) cases.
Keywords are words that the language uses for a
special purpose, such as void, int, public, etc. It
can’t be used for a variable name or function
name. Below is the table for the complete set of
C++ keywords.
SIMPLE PROGRAM IN C++
#include <iostream.h> // Section: 1- The include
Directive
using namespace std; // Section :2 - Class declaration
and member functions
int main () // Section: 3 - Main function definition
{ // Section: 4 - Declaration of an object
cout << "Hello World!";
return 0;
}
DIFFERENCE BETWEEN C & C++
C C++

C was developed by Dennis Ritchie between the year


C++ was developed by Bjarne Stroustrup in 1979.
1969 and 1973 at AT&T Bell Labs.

C does no support polymorphism, encapsulation, and C++ supports polymorphism, encapsulation, and 


inheritance which means that C does not support inheritance because it is an object oriented
object oriented programming. programming language.

C is a subset of C++. C++ is a superset of C.

C contains 32 keywords. C++ contains 63 keywords.

For the development of code, C supports  C++ is known as hybrid language because C++
supports both procedural and 
procedural programming. object oriented programming paradigms.
DATA TYPES IN C++
• Primitive Data Types: These data types are built-in or
predefined data types and can be used directly by the
user to declare variables. example: int, char , float, bool
etc. Primitive data types available in C++ are: 
– Integer
– Character
– Boolean
– Floating Point
– Double Floating Point
– Valueless or Void
– Wide Character
Derived Data Types

Derived Data Types: Data types that are derived from


the built-in data types are known as derived data types.
The various derived data types provided by C++
are arrays, functions, references and pointers. Array
An array is a set of elements of the same data type that
are referred to by the same name.
USER DEFINED DATA TYPE
The data types that are defined by the user are
known as user-defined data types. For example;
arrays, class, structure, union, Enumeration,
pointer, etc. These data types hold more
complexity than pre-defined data types.
int

The int keyword is used to indicate integers.


Its size is usually 4 bytes. Meaning, it can store
values from -2147483648 to 2147483647.
For example,
int salary = 85000;
float and double
float and double are used to store floating-point
numbers (decimals and exponentials).
The size of float is 4 bytes and the size of double is 8
bytes. Hence, double has two times the precision
of float. To learn more, visit C++ float and double.
For example,
float area = 64.74; double volume = 134.64534;
NOTE : These two data types are also used for
exponentials. For example,
double distance = 45E12 // 45E12 is equal to 45*10^12
char

Keyword char is used for characters.


Its size is 1 byte.
Characters in C++ are enclosed inside single
quotes ' '.
For example,
char test = 'h';
wchar_t

Wide character wchar_t is similar to the char data


type, except its size is 2 bytes instead of 1.
It is used to represent characters that require more
memory to represent them than a single char.
For example,
wchar_t test = L'‫ 'ם‬// storing Hebrew character;
bool

The bool data type has one of two possible


values: true or false.
Booleans are used in conditional statements and
loops (which we will learn in later chapters).
For example,
bool cond = false;
void

The void keyword indicates an absence of data.


It means "nothing" or "no value".
We will use void when we learn about functions
and pointers.
Note: We cannot declare variables of
the void type.
C++ Type Modifiers

There are 4 type modifiers in C++. They are:


i. signed
ii. unsigned
iii. short
iv. long
• long b = 4523232;
• long int c = 2345342;
• long double d = 233434.56343;
• short d = 3434233; // Error! out of range
unsigned int a = -5; // Error! can only store
positive numbers or 0
TYPE CONVERSION
Type conversion can be done in two ways in C++, one is implicit type
conversion(automatic type conversion.), and the second is explicit type
conversion. Those conversions are done by the compiler itself, called the
implicit type or automatic type conversion. The conversion, which is
done by the user or requires user interferences called the explicit or user
define type conversion.
For example, we are adding two numbers, where
one variable is of int type and another of float
type; we need to convert or typecast the int
variable into a float to make them both float data
types to add them.
Eg.
Int a;
float b=4.3;
b=a;
VARIABLES
A variable is a name of memory location. It is
used to store data. Its value can be changed
and it can be reused many times.
SYNTAX:
type variable_list;  
int a;    
int _ab;    
int a30;    
C++ Literals

Literals are data used for representing fixed


values. They can be used directly in the code.
For example: 1, 2.5, 'c' etc.
Here, 1, 2.5 and 'c' are literals.
C++ Constants

We can create variables whose value cannot be


changed. We use the const keyword. Here's an
example:
const int LIGHT_SPEED = 299792458;
LIGHT_SPEED = 2500 // Error! LIGHT_SPEED is a
constant.
Operators in C++

C++ has many built-in operator types and they

are classified as follows: 


1. Arithmetic Operators
Arithmetic operators are used to perform
arithmetic operations on variables and data. For
example,
a + b;
Operator Operation

+ Addition

- Subtraction

* Multiplication

/ Division

Modulo Operation (Remainder after


%
division)
Assignment Operators

Assignment operators are used to assign values


to variables.
For example,
// assign 5 to a a = 5;Here, we have assigned a
value of 5 to the variable a.
Relational Operators

A relational operator is used to check the


relationship between two operands.
For example,
// checks if a is greater than b
a > b;
Relational Operators
Operator Meaning Example

== Is Equal To 3 == 5 gives us false

!= Not Equal To 3 != 5 gives us true

> Greater Than 3 > 5 gives us false

< Less Than 3 < 5 gives us true

Greater Than or
>= Equal To 3 >= 5 give us false

<= Less Than or Equal 3 <= 5 gives us true


To
Logical Operators
Logical operators are used to check whether an expression
is true or false. If the expression is true, it returns 1 whereas if
the expression is false, it returns 0.

Operator Example Meaning

Logical AND.
expression1 &&
&& expression2 True only if all the
operands are true.

Logical OR.
|| expression1 || True if at least one of the
expression2
operands is true.

Logical NOT.
! !expression True only if the operand is
false.
Bitwise Operators

Operator Description

& Binary AND

| Binary OR

^ Binary XOR

~ Binary One's Complement

<< Binary Shift Left

>> Binary Shift Right


Other C++ Operators
Operator Description Example

sizeof returns the size of data sizeof(int); // 4


type

?: returns value based on the string result = (5 > 0) ?


condition "even" : "odd"; // "even"

represents memory
& address of the operand &num; // address of num

accesses members of struct


. s1.marks = 92;
variables or class objects
used with pointers to
-> access the class or struct ptr->marks = 92;
variables
<< prints the output value cout << 5;
>> gets the input value cin >> num;
Bitwise Operators Versus Logical Operators

Bitwise operators look and function similarly to


logical operators but operate solely on integer-
type values and not Booleans. Bitwise operators
compare two integers on a bit-by-bit basis and
output a 1 or a 0 depending on the result of the
operation.
SPECIAL CHARACTERS
Operator Description Example

sizeof returns the size of data type sizeof(int); // 4

returns value based on the string result = (5 > 0) ? "even" :


?: condition "odd"; // "even"

represents memory address of


& the operand &num; // address of num

accesses members of struct


. variables or class objects s1.marks = 92;

used with pointers to access


-> ptr->marks = 92;
the class or struct variables

<< prints the output value cout << 5;

>> gets the input value cin >> num;


Escape Sequence
Escape Sequence Represents
\a Bell (alert)
\b Backspace
\f Form feed
\n New line
\r Carriage return
\t Horizontal tab
\v Vertical tab
\' Single quotation mark
\" Double quotation mark
\\ Backslash
CONDITIONAL STATEMENTS
// Program to print positive number entered by the user // If the user enters a negative number, it
is skipped
#include <iostream>
using namespace std;
int main()
{
int number;
cout << "Enter an integer: ";
cin >> number; // checks if the number is positive
If (number > 0)
{
cout << "You entered a positive integer: " << number << endl;
}
cout << "This statement is always executed.";
return 0;
}
Output 1
Enter an integer: 5 You entered a positive number: 5 This statement is always executed.
if...else
if (condition)
{
// block of code if condition is true
}
else
{
// block of code if condition is false
}
if...else...else if statement
if (condition1)
{
// code block 1
}
else if (condition2)
{
// code block 2
}
Else
{
// code block 3
}
switch..case Statement
switch (expression)
{
case constant1:
// code to be executed if
// expression is equal to constant1;
break;
case constant2:
// code to be executed if
// expression is equal to constant2;
break;
default:
// code to be executed if
// expression doesn't match any constant }
SWITCH
#include <stdio.h>
int main()
{
   int x = 2;
   switch (x)
   {
       case 1: printf("Choice is 1");
               break;
       case 2: printf("Choice is 2");
                break;
       case 3: printf("Choice is 3");
               break;
       default: printf("Choice other than 1, 2 and 3");
                break; 
   }
   return 0;
}
Iterative or looping statement
FOR LOOP
Syntax:
for (initialization expr; test expr; update expr)
{
// body of the loop
// statements we want to execute
}
FOR LOOP
#include <stdio.h>
  
int main()
{
    int i=0;
      
    for (i = 1; i <= 10; i++)
    {
        printf( "Hello World\n");    
    }
  
    return 0;
}
WHILE LOOP
initialization expression;
while (test_expression)
{
// statements update_expression;
}
Eg: while loop
#include <stdio.h>
  
int main()
{
    // initialization expression
    int i = 1;
  
    // test expression
    while (i < 6)
    {
        printf( "Hello World\n");    
  
        // update expression
        i++;
    }
  
    return 0;
}
initialization expression;
do
{
// statements update_expression;
}
while (test_expression);
Eg. : do while
#include <stdio.h>
  
int main()
{
    int i = 2; // Initialization expression
  
    do
    {
        // loop body
        printf( "Hello World\n");    
  
        // update expression
        i++;
  
    }  while (i < 1);   // test expression
  
    return 0;
}
Break Statement Example
#include <iostream>  
int main() {  
      for (int i = 1; i <= 10; i++)    
          {    
              if (i == 5)    
              {    
                  break;    
              }    
        cout<<i<<"\n";    
          }    
}  
Output:
1
2
3
4
COMMENTS
Comments can be singled-lined or multi-lined.

Single-line Comments
Single-line comments start with two forward slashes (//).
Example:
//This is a comment
cout << "Hello World!";
Multi-line Comments

Multi-line comments start with /* and ends with */.

Any text between /* and */ will be ignored by the compiler:

Example

/* The code below will print the words Hello World!

to the screen, and it is amazing */

cout << "Hello World!";


setw()
The setw() method of iomanip library in C++ is
used to set the ios library field width based on
the width specified as the parameter to this
method.
Syntax: 
setw(int n)
Eg : setw()
 
#include <iomanip>
#include <ios>
#include <iostream>
 using namespace std;
 int main()
{
 
    // Initializing the integer
    int num = 50;
 
    cout << "Before setting the width: \n"
         << num << endl;
 
    // Using setw()
    cout << "Setting the width"
         << " using setw to 5: \n"
         << setw(5);
     cout << num << endl;
     return 0;
}

Before setting the width: 50 Setting the width using setw to 5: 50


setprecision()

The setprecision() method of iomanip library in


C++ is used to set the ios library floating point
precision based on the precision specified as the
parameter to this method.

Syntax:

setprecision(int n)
#include <iomanip>
#include <ios>
#include <iostream>
 
using namespace std;
 int main()
{
 
    // Initializing the decimal
    double num = 3.142857142857;
 
    cout << "Before setting the precision: \n"
         << num << endl;
 
    // Using setprecision()
    cout << "Setting the precision using"
         << " setprecision to 5: \n"
         << setprecision(5);
 
    cout << num << endl;
 
    // Using setprecision()
    cout << "Setting the precision using"
           << " setprecision to 9 : \n "
         << setprecision(9);
 
    cout << num << endl;
 
    return 0;
}
Before setting the precision: 3.14286
Setting the precision using setprecision to 5: 3.1429
Setting the precision using setprecision to 9: 3.14285714

You might also like