C Programming 2
C Programming 2
C++
C++ is a general-purpose programming language
Implementations of C++ exist from some of the most modest microcomputers to the largest supercomputers
and for almost all operating systems.
C++ is a superset of the C programming language. In addition to the facilities provided by C, C++ provides flexible
and efficient facilities for defining new types.
C++ developed using class concept of Simula( already existing language which supported OOP paradigm) and C’s
efficiency and flexibility for systems programming.
1979: Work on ‘‘C with Classes’’ started. The initial feature set included classes and derived classes, public/private
access control, constructors and destructors, and function declarations with argument checking.
1984: ‘‘C with Classes’’ was renamed to C++. By then, C++ had acquired virtual functions, function and operator
overloading, references, and the I/O stream, number libraries.
1991: The C++ Programming Language, Second Edition, presenting generic programming using templates and error
handling based on exceptions
1997: The C++ Programming Language, Third Edition [Stroustrup,1997] introduced ISO C++, including
namespaces, dynamic_cast, and many refinements of templates. The standard library added the STL framework
of generic containers and algorithms
2011: ISO C++11 standard was formally approved. In 2012 The first complete C++11 implementations emerged.
2012 Work on future ISO C++ standards (referred to as C++14 and C++17) started
Software written in C++ is everywhere: It is in your computer, your phone, your car, and other many electronic devices
Many operating systems have been written in C++ like Windows, Apple’s OS, Linux, and most portable-device OSs..
C++ is used to write device drivers and other software that rely on direct manipulation of hardware under real-time
constraints.
C++ is used to write some critical parts of most widely used systems like Amazon, Google, Facebook.
Many other advanced technologies depends on C++’s performance and reliability in their implementations –
JVM of Java Technologies, Web services framework of Microsoft’s .NET technologies, JavaScript interpreters of
many browsers like Microsoft’s Internet Explorer, Mozilla’s Firefox, Apple’s Safari, and Google’s Chrome.
C was developed by Dennis Ritchie between the year C++ was developed by Bjarne Stroustrup in 1979 at
1969 and 1973 at AT&T Bell Labs. AT&T Bell Labs
C supports procedural programming. C++ is hybrid language, because it supports
procedural and object oriented programming and
generic programming.
C is a function driven language C++ object driven language
Functions are written and data is passed as Data and functions are encapsulated together in an
parameter in functions. object in C++.
Different operators are supported on built-in data Different operators are supported on built-in data
types types as well as user defined data type
malloc(), calloc(), realloc(), free() functions are used Operators new and delete are used for memory
for memory management management
Features like – namespace, template, exception
handling, reference variable, function and operator
overloading are supported in C++
Total 32 keywords in Standard C Total 63 keywords in C++
First C++ Program :
#include<iostream>
int main()
{
cout<<"Hello World..";
return 0;
}
Tokens in C++ : In C++, tokens can be defined as the smallest building block of C++ programs that the
compiler understands. Every word in a C++ source code can be considered a token.
Before translation parser does parsing of each statement and finds out tokens. Each token has some pre-
defined meaning in compiler. Compiler translates each token in machine understandable form and
returns .exe file. This .exe file is executable file, which can be executed directly on OS prompt.
Types of tokens :
• Identifiers
• Keywords
• Constants
• Datatypes
• Strings
• Operators
• Escape sequence
Identifier : It is user-defined word. Used to define and declare variable_name, function_name, user_defined
data types etc..
Preprocessor directive, works like find and replace. Before compilation all occurrences of word MAX in program
are replaced by 100.
Constants :
Demonstration: constDemo.cpp
Datatypes:
We use the variables to store values in programs, but the OS has to know what kind of data we want to
store in them, since OS is going to allocate some amount of memory to store a value.
A declaration is statement that introduces a variable name into the program. It specifies a datatype for the
variable
A datatype defines a set of possible values and a set of operations we can perform on those values.
unsigned: 0 to 65535
int Integer. 4bytes
signed: -2147483648 to 2147483647
unsigned: 0 to
4294967295
long int (long) Long integer. 4bytes
signed: -2147483648 to 2147483647
unsigned: 0 to 4294967295
Demonstration : Limits.cppBoolean value.
bool 1byte
true or false
float Floating point number. 4bytes +/- 3.4e
string in C++ :
Variables that can store non-numerical values that are longer than one single character are known as
strings.
The C++ language library provides support for strings through the standard string class. This is not a
primitive type, but it behaves like a primitive types in its most basic usage.
Demonstration: stringDemo.cpp
Operator: C++ has very rich set of operators.
Assignment operator =
The part at the left of the assignment operator (=) is known as the lvalue (left value) and the right
one as the rvalue (right value).
The lvalue has to be a variable whereas the rvalue can be either a constant, a variable, the result of
an operation or any combination of these.
The most important rule when assigning is the right-to-left rule:
The assignment operation always takes place from right to left, and never the other way:
a = b;
This statement assigns to variable a (the lvalue) the value contained in variable b (the rvalue).
The value that was stored until this moment in a is not considered at all in this operation, and in fact
that value is lost.
A property that C++ has is that the assignment operation can be used as the rvalue (or part of an rvalue)
for another assignment operation.
For example: a = 2 + (b = 5);
is equivalent to:
b = 5; a = 2 + b;
that means: first assign 5 to variable b and then assign to a the value 2 plus the result of the previous
assignment of b (i.e. 5), leaving a with a final value of 7.
+ addition
- subtraction
* multiplication
/ division
% modulo
Compound assignment (+=, -=, *=, /=, %=, >>=, <<=, &=, ^=, |=)
Sequence Meaning
\a Alert.
\b Backspace.
\f Form feed.
\n Newline.
\r Carriage return.
\t Horizontal tab.
\v Vertical tab.
\\ Backslash ( \ ).
\’ Single quote ( ' ).
\" Double quote ( " ).
\? Question mark ( ? ).
Demo: escSequence.cpp
Control Structures in C++:
Condition Structure:
if..else if..else
Loop Structures:
for loop
while loop
do..while loop
break
continue
#6. Take range of numbers from user and print tables of all numbers within the given range.
#7. Print all prime numbers between given range.
#8. Basic pattern printing programs : separate file is shared.
#9. Menu driven program for small hotel menu with sub menu and print total bill amount, when user enter Exit
choice.
#10. Take a range of numbers and print all perfect numbers within the given range.
Assignment #1: From hackerRank
Given a positive integer , do the following:
If 1 <= n <=9, print the lowercase English word corresponding to the number (e.g., one for , two for , etc.).
If n > 9, print Greater than 9.
Input Format
A single integer, n .
Constraints
1 <= n <= 9
Output Format
If 1<=n<=9, then print the lowercase English word corresponding to the number (e.g., one for 1 , two for 2,
etc.); otherwise, print Greater than 9.
Assignment #2: From hackerRank
Input Format
You will be given two positive integers, a and b (a <= b), separated by a newline.
Output Format
If 1 <= n <= 9, then print the English representation of it in lowercase. That is "one" for , "two" for , and so on.
Else if n > 9 and it is an even number, then print "even".
Else if n > 9 and it is an odd number, then print "odd".
Assignment #3: Assignment #4:
C++ Program to check whether a number is a C++ Program to check whether a number is a
Perfect Cube or not Perfect Square or not
Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to
go outside the signed 32-bit integer range [-231, 231 - 1], then return 0.
Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
Example 1:
Input: x = 120
Input: x = 123 Output: 21
Output: 321
Example 2:
Constraints:
Input: x = -123
Output: -321 -231 <= x <= 231 - 1
Example 3:
Functions in C++ :
A function is a group of statements that is executed when it is called from some point of the program.
Gives feature of reusability because of its write once and call multiple times mechanism.
They are written to perform a specific task and are also called as module or sub-program or procedure or
sub-routine.
A function can optionally define input parameters that enable callers to pass arguments into the function.
Every function should be called directly or indirectly from main(). main() function is entry point function for
C++ program.
type function_name ( parameter1, parameter2, ...) { statements }
where:
• type is the data type specifier of the data returned by the function.
• name is the identifier by which it will be possible to call the function.
• parameters (as many as needed): Each parameter consists of a data type specifier followed
by an identifier, like any regular variable declaration (for example: int x) and which acts within
the function as a regular local variable. They allow to pass arguments to the function when it
is called. The different parameters are separated by commas.
Function declaration, definition and call should match to avoid syntax error.
Global variable:
Local variable:
Static variable:
Implement pow(x, n), which calculates x raised to the power n (i.e., x n).
Example 1:
Constraints:
Input: x = 2.00000, n = 10
-100.0 < x < 100.0
Output: 1024.00000
-231 <= n <= 231-1 n is an integer.
Example 2:
-104 <= xn <= 104
Input: x = 2.10000, n = 3
Output: 9.26100
Example 3:
Input: x = 2.00000, n = -2
Output: 0.25000
Explanation: 2-2 = 1/22 = 1/4 = 0.25
Assignment #7: hackerRank
Write a function int max_of_four(int a, int b, int c, int d) which returns the maximum of the four arguments it receives.
Input Format
Output Format
3
4
6
5
Sample Output
6
Assignment #8: Hackerearth
A number n is said to be special if the sum of its digits is divisible by
4. Constraints
Output format
For each test case, print a number n that satisfies the above
conditions in a new line.
Pointers in C++:
It is a variable, which holds address of another variable. The address should be from same process's address space.
Usages:
1. To return more than one values from function. (call by address)
2. To store the address returned by malloc at run time.
3. Array is a constant pointer.
4. To access a variable which has been declared outside the function (declared in caller() etc)
5. To write fast and efficient programs.