Programming Basics For Kids What Is C++ Programming and Basic Concepts To Better Understand C++
Programming Basics For Kids What Is C++ Programming and Basic Concepts To Better Understand C++
By
A.G Farrell
© Copyright 2021 by (A.G Farrell) - All rights reserved.
This document is geared towards providing exact and reliable information in
regards to the topic and issue covered. The publication is sold with the idea
that the publisher is not required to render accounting, officially permitted, or
otherwise, qualified services. If advice is necessary, legal or professional, a
practiced individual in the profession should be ordered.
- From a Declaration of Principles which was accepted and approved equally
by a Committee of the American Bar Association and a Committee of
Publishers and Associations.
In no way is it legal to reproduce, duplicate, or transmit any part of this
document in either electronic means or in printed format. Recording of this
publication is strictly prohibited and any storage of this document is not
allowed unless with written permission from the publisher. All rights
reserved.
The information provided herein is stated to be truthful and consistent, in that
any liability, in terms of inattention or otherwise, by any usage or abuse of
any policies, processes, or directions contained within is the solitary and utter
responsibility of the recipient reader. Under no circumstances will any legal
responsibility or blame be held against the publisher for any reparation,
damages, or monetary loss due to the information herein, either directly or
indirectly.
Respective authors own all copyrights not held by the publisher.
The information herein is offered for informational purposes solely, and is
universal as so. The presentation of the information is without contract or any
type of guarantee assurance.
The trademarks that are used are without any consent, and the publication of
the trademark is without permission or backing by the trademark owner. All
trademarks and brands within this book are for clarifying purposes only and
are the owned by the owners themselves, not affiliated with this document.
Table of contents
INTRODUCTION
1.3 Constants
1.5 Variables
2.2 Statements
CHAPTER 4: SELECTION-MAKING
4.1 Logical Data and Operators
4.2 Two Way Selection
5.4 Sorting
CONCLUSION
Introduction
C++ is a computer programming language widely used for general-purpose
programming. It is an extension of C-language. The basic understanding of
C++ can be acquired from C. That’s why both computer languages are
represented as C/C++. Bjarne Stroustrup developed this multi-paradigm
language in 1979.
In today’s world, many operating systems use C++ as their basic language.
Some system drivers, browsers, and games are based on C++ programs. It is
a free-form, compiled, and statically-typed programming language. Many
professionals believe that C++ is the most efficient language to achieve the
desired results.
In this book, I have covered all the essential basic concepts for beginners. It
is a step by step guide, which makes sure the understanding of C++
programming. First of all, there is a need to know the structure and syntax of
C++, along with the basic expressions. Then, it guides the major “Functions”
such as mathematical manipulation and Standard Library. Moreover, there
are complete guidance about the selection making of operators and logical
data, concepts of Arrays, Pointers, Classes and Strings in C++.
While there are so many great programming languages, but C++ is the most
favorite owing to have the privilege of the first Object-Oriented Programming
language. Nowadays, there are several high-level languages with simple
syntax and user-friendly options. Still, programmers can’t deny the
importance of C++ because of its huge number of open-source libraries, wide
applications, and highly fast run-time performance.
This guide is specially designed for beginners who want to learn C++ in a
very few days. You will discover this language by making your programs
while reading this book.
Chapter 1: Introduction to C++
In the following chapter, we will discuss about the evolution of computer
programming languages and their evolution from machine languages.
As we know C++ is a high-level language. We’ll discuss the concepts of
C++, in this chapter. Moreover, you will be able to write your first program,
after going through this chapter, i.e. “Hello World”. Furthermore, you’ll
understand the concepts of Constants, Variables, Data types and some of the
operators that may help you writing and understanding a C++ program.
1.1 Background of C++
C++ is considered a properly structured programming language, that’s why
this is so popular. C++, as you know, is a high level language because it
allows a programmer to concentrate on the problem at his hand, without
worrying about the system that the program may be using. There are many
languages who claim to be system or machine independent but C++ is one of
the best among them.
Like many other languages, C++ is basically derived from ALGOL, which
was the first language to have a structure. ALGOL was developed in the early
1960s and it made a path for structured programming and its concepts. Very
first work in ALGOL was done by two scientists name as Guiseppe Jacopini
and Corrado Bohm. Both of them published a research in 1960 which defined
a thorough idea of structured programming.
In 1967, a computer scientist named as Martin Richards designed a language
designed a programming language; he named Basic Combined Programming
Language aka. BCPL. In 1970, Ken Thompson developed a language, known
as “B”. Following him, Dennis Ritchie, in 1972, developed the concept of
language “C”.
Following all the concepts from the languages, ALGOL, BCPL, B and C,
Bjarne Stroustrup, developed C++ in mid 1980s.
Declaration is considered the data that you may use to justify or write your
program or function. If you declare something in a function, it’ll be known as
“Local Declaration”. We call them local declarations because the are read,
only be the function itself.
Statements
Statements are some commands to the machine, that is using the program.
Statements cause the machine to perform the actions, such as adding or
subtracting numbers, multiply them, taking their average etc.
Simple Program
We know that C++ allow us to make declarations and statements at the same
time, but, everytime, we should write a program, which should be well
organized so that any other programmer or even the machine could
understand it fast. This is the reason, we follow the language C’s concepts of
organization. The concept states that one should perform declaration first and
statements second. Moreover, most of the times, one should use comments
for the identification of the sections; Declarations and Statements.
A C++ program is a mixture of two components main (Main) and fun
(function). In other words, function is called or used by main. Usually, we
write the code for the “main”, first. After that, we’ll code the function and
sub functions, in their order.
Moving forward, there is another concept; concept of preprocessor directives
or precompiler directives. These are some statements which give instructions
to a compiler or processor to execute the program in a unique pattern.
A statement which is globally used as a preprocessor directive is, “include”.
This statement allows the compiler to extract some data from global libraries,
known as header files. Without these header files or libraries, you will not be
able to write even a single program, because it’ll be so complex to write the
commands even for your input or output. Even, you will need an “include”
command, to write your very first program. This will be used to instruct C++
that you will be in need for the input and output libraries, so that you may
print your desired data to the console screen.
Hello World
#include <iostream>
using namespace std;
int main()
{
cout << "Hello to the world of C++!";
return 0;
}
When you’ll execute this program, there will be a console screen popping up
with the text:
Hello to the world of C++!
We’ve already written our first program so now, we will be discussing some
more important concepts of programming in C++.
1.3 Constants
The concept of constants in programming is very similar to the concept of
constant in Mathematics. Constants are the values or data which remains
unchanged during the execution of a code or program.
In this section, we will define different types of constants in programming
Integer Constants
First thing first, integers are stored in binary formation. You’ll code integers,
as you use them in your daily routine, for example you will code eight simply
as 8.
The following table will show you different integers, their values in
programming and their data types.
98 +98 int
Character Constants
Whenever, you’ll find an integer, closed between two single apostrophes, this
would be character constant. Moreover, there is a chance that you’ll find a
backslash “\” between those apostrophes.
For most machines, ASCll character set is used, i.e.
ASCII Characters Symbolic Display
newline ‘\n’
backspace ‘\b’
backslash ‘\\’
Float Constants
Float constants are stored as two parts in memory as float constants are
numbers having decimal parts. The first part, they obtain in memory is
significand and the second is exponent.
Float constant’s default type is “double”. You must write a code to specify
your desired data type, i.e. “float” or “long double”. We may remember that
“f” or “F” is used to represent float and “l” or “L” is used to represent long
double.
In the following table, some of the examples of float, double and long
double.are shown:
0. 0.00 double
Boolean Constants
These constants are predefined keywords and they can not be defined or
declared by the programmer. It has two predefined constants, “True” and
“False”. In programming, we represent this kind of constant as “bool”.
Programming Constants
Output:
In the case of this code, a console screen will pop up with the output:
Integer Constant in our code: 50
Floating point Constant in our code: 9.7
Character Constant in our code: K
Literal Constants
Values Type
7 Numeric Literal 7
void (Void)
In C++, void has no operations or no functions. In simpler words, both the set
of operations and the set of values are empty. It is a very useful data type in
programming although it seem unusual. Typically, it is a generic data type
that can represent any other standard data types.
int (Integer)
C++ allows us to use an operator “size of”, that may tell us the size of our
data types. Whenever, we are coding in C++, we should keep this statement
in mind:
sizeof (long int) => sizeof (int) => sizeof (short int)
char (Character)
Boolean data types has two functions, True and False. Traditionally, a zero is
considered as false and any non-zero part is considered as true.
float (Floating Point)
Float data type or floating point is usually a data type having a fractional part.
When coding in float data type, we should always consider this statement:
sizeof (long double) => sizeof (double) => size of (float)
We may think that the data type, float and data type, integer are the same, but
there are many differences as the “float” is always declared in a C++
program.
Data Implementations
Types
Void void
Integer Unsigned short int, unsigned int, unsigned long int, short int,
int, long int
Character char
Boolean bool
1.5 Variables
Variable, in C++ are memory locations, having different data types, such as
character or integers. Variables are manipulatable and changeable because the
use a set of different operations.
Variable Initialization
Variable Declaration
#include<iostream>
using namespace std;
int main ()
{
char a;
cout << "Enter your desired character to print its value: ";
cin >> a;
cout << "According to ASCII character set, value of " << a <<" is : "
<< (int)a;
return 0;
}
Output:
When you will execute this program, a console screen will pop up with this
text:
Enter your desired character to print its value:
You simply have to type your desired alphabet to print its value. Let's say you
want to print the value of “G”. Simply type “G” and press “Enter” key. Your
program will print the value of “G” according to ASCII character set. It will,
somehow, look like this:
According to ASCII character set, value of "G" is : 71
Problem 2
Write a program in C++ that uses five output statements to print the pattern
shown below.
A
AA
AAA
AAAA
AAAAA
Solution
#include <iostream>
using namespace std;
int main()
{
cout << "A"<< endl;
cout << "AA"<< endl;
cout << "AAA"<< endl;
cout << "AAAA"<< endl;
cout << "AAAAA";
return 0;
}
Output:
When you execute this code, a console screen will pop us with your desired
pattern, i.e.
A
AA
AAA
AAAA
AAAAA
1.7 Exercise Sets
Write a C++ Program by using “cout” or output statements to print
the initials of your name in block letters. Program should not read
any alphabet from your keyboard. Each letter should be formed by
using seven columns and five rows, using the letter itself. For
example if your name is “Faheel”, your output should be
something like this:
FFFFFFF
F
FFFF
F
F
Simply, Write a code in C++ that allows the user to enter three
numbers and them it prints those numbers vertically (one in a
line), first, in ascending order and then in descending order, as
Shown in below example:
Output:
First, your console should print a line saying:
After entering numbers, let's say 10, 50, 17, it should print:
Expressions
Pointers
Classes
In this chapter we will discuss the very first of these concepts, i.e.
Expressions. We have already used expressions in Mathematics, but the way
to use expressions is unique to “C++” and its precursor “C”. The concept of
expressions is tied to the concept of precedence, operators, statements and
associativity.
2.1 Expressions
Expression, in a C++ program, is a sequence of operators and operands that
eventually reduces to a single value. For example, 10 * 2.
In the following example, the expression reduces to 20. In C++, final value
can be of any data type, other than void.
Operators
Operators are the language specific syntactical tokens that require some
action to be performed. Many operators are derived from the concepts of
Mathematics. For example “Sign of Multiplication (*)” is an operator used in
C++. It multiplies two numbers.
Every programming language has unique operators to perform unique
operations.
Operand
For any defined operator, there may be one or more than one operands.
Operand has to receive any operator’s action. In above example, (10 * 2),
Multiplier and Multiplicand are the operands of Multiplication.
There is no limit of operand sets and operators to form an expression. The
only rule is that when program will evaluate the expression, the answer
should be a single value, that may represent the expression.
Names
Constants
Parenthetical Expressions
Additive Expressions
First type of binary expressions is additive expressions. In this kind of
expression, second operand is added to the first operand or the second
operand is subtracted from the first operand. It depends upon the operator,
that is used. These kinds of expressions use parallel algebraic notations for
example, a + 18 and b - 90. Here are two sample programs to show such kind
of expressions:
For Addition:
#include <iostream>
using namespace std;
int main()
{
// Declaration of integers
int firstinteger, secondinteger, sum;
// Printing input and output commands
cout << "Enter any integer: ";
cin >> firstinteger;
cout << "Enter another integer: ";
cin >> secondinteger;
// Sum of two integers is stored in the variable "sum"
sum = firstinteger + secondinteger;
// Printing sum of first and second integer
cout << firstinteger << " + " << secondinteger << " = " << sum;
return 0;
}
For Subtraction:
#include <iostream>
using namespace std;
int main()
{
// Declaration of integers
int firstinteger, secondinteger, sub;
// Printing input and output commands
cout << "Enter any integer: ";
cin >> firstinteger;
cout << "Enter another integer: ";
cin >> secondinteger;
// Subtraction of second integer from first is stored in the variable "sub"
sub = firstinteger - secondinteger;
// Printing the subtraction of second integer from first integer
cout << firstinteger << " - " << secondinteger << " = " << sub;
return 0;
}
Multiplicative Expressions
#include <iostream>
using namespace std;
int main()
{
// Declaration of integers
int firstinteger, secondinteger, mul;
// Printing input and output commands
cout << "Enter any integer: ";
cin >> firstinteger;
cout << "Enter another integer: ";
cin >> secondinteger;
// Product of two integers is stored in the variable "mul"
mul = firstinteger * secondinteger;
// Printing sum of first and second integer
cout << firstinteger << " * " << secondinteger << " = " << mul;
return 0;
}
For Division:
#include <iostream>
using namespace std;
int main()
{
// Declaration of integers
int firstinteger, secondinteger, div;
// Printing input and output commands
cout << "Enter any integer: ";
cin >> firstinteger;
cout << "Enter another integer: ";
cin >> secondinteger;
// Integral value of quotient in division of first integer and second integer is
stored in the variable "div"
div = firstinteger / secondinteger;
// Printing the subtraction of second integer from first integer
cout << firstinteger << " / " << secondinteger << " = " << div;
return 0;
}
Assignment Expressions
Assignment expression is an expression which usually evaluates the operands
on the right side of an equation and automatically places its value to the
variable on the left side.There are two types of assignment expressions:
Simple Assignment
n = m -1 20 15 14 14
n = m + 20 20 15 35 35
n=m*0 20 15 0 0
Compound Assignment
n /= m n=n/m
n *= m n=n*m
n -= m n=n-m
n += m n=n+m
In the following table there are some examples of compound assignment and
how its value is calculated.
n %= m 20 15 n=(20/100)* 15 3
n /= m 20 15 n = 20 / 15 1.33
n *= m 20 15 n = 20 * 15 300
n -= m 20 15 n = 20 - 15 5
n += m 20 15 N = 20 + 15 35
For Addition:
#include<iostream>
using namespace std;
int main()
{
int n = 5, m = 2;
//Compound assignment expression n += m means n = n + m
n += m;
cout << n << endl;
return 0;
}
For Subtraction:
#include<iostream>
using namespace std;
int main()
{
int n = 5, m = 2;
//Compound assignment expression n -= m means n = n - m
n -= m;
cout << n << endl;
return 0;
}
For Multiplication:
#include<iostream>
using namespace std;
int main()
{
int n = 5, m = 2;
//Compound assignment expression n *= m means n = n * m
n *= m;
cout << n << endl;
return 0;
}
For Division:
#include<iostream>
using namespace std;
int main()
{
int n = 5, m = 2;
//Compound assignment expression n /= m means n = n / m
n /= m;
cout << n << endl;
return 0;
}
Postfix Expressions
Function call
Both postfix increment (n++) and postfix decrement are postfix operators.
Usually every program, in C++ require the value 1 to be added in its variable.
In most of the programming languages, this can be done in binary
expressions.
C++, on the other hand provides its programmer an ability to code this in
both binary as well as unary expressions.
In postfix increment, the variable increases its value by 1. So, “n++” is
calculated as the variable “n” being increased by “1”. This expression is
similar as assignment expression:
n++ means that n = n + 1
On the other hand, postfix decrement (n--) also have values and results but in
this case, machine reduces your variable (n) by 1 i.e. n - 1.
n-- 20 20 - 1 19
n++ 20 20 + 1 21
For Postfix Increment:
#include <iostream>
using namespace std;
int main()
{
int n, a;
cout <<"Enter any integer: ";
cin >> n;
a = n++;
return 0;
}
#include <iostream>
using namespace std;
int main()
{
int n, a;
cout <<"Enter any integer: ";
cin >> n;
a = n--;
return 0;
}
2.2 Statements
In C++ any action performed by a program is caused by statements. It
translates the executable commands into machine language. In C++ there are
six kinds of statements:
Expression statement
Compound Statement
Labeled Statement
Iterative Statement
Selection Statement
Jump Statement
Expression Statement
Example Program:
#include <iostream>
using namespace std;
int main()
{
// declaration statement
int n = 69, m;
cout << "Enter the value of m: ";
cin >> m;
// expression statement
n = n + 1;
// expression statement
std::cout << "n = " << n << '\n';
// return statement
return 0;
}
A bit more complex statement in expression statements can be:
n = m = 69;
This statement consists of two statements. If we factorize this statement, we
will see the expressions clearly
n = (m = 69);
The compiler will assign the value 69 to “m” during the compilation process.
After evaluating “m”, the compiler will terminate and discard the value of
“m” and then will start to calculate the value of “n”. After the compiler’s
execution of this statement, 69 will stored in both the variables “m” and “n”.
Moving forward, consider a postfix expression as an expression statement,
i.e.:
n++
In this expression, the value of expression is 69. It is also the value of our
variable “n”, before it is increased by 1.When the compiler will execute the
statement, the value of the variable “n” will be 70. But the value of the
expression, i.e. 69, will be terminated.
Moreover, we have a special type of expression statement known as null
expression. This expression statement has no value and no side effect and this
can be very useful in some compex statements. Null expression is represented
as a single semicolon.
;
Compound Statement
In C++, a compound statement is a coding unit consists of some statements or
no statement. We may also call compound statement; a block. This statement
allows many statements to execute as a single unit. While writing your first
program, you used a compound statement, i.e. while writing the body of the
function main. In C++, every program has a compound statement in it, which
we call function body.
Every compound statement have some parts in it, i.e.
{ // Opening Brace
cout << "Hello to the world of C++!"; // Statement
return 0; // Return Statement
} // Closing Brace
{ // Opening Brace
// declaration statement
int n = 69, m;
cout << "Enter the value of m: ";
cin >> m;
// expression statement
n = n + 1;
// expression statement
std::cout << "n = " << n << '\n';
// return statement
return 0;
} // Closing Brace
Problem - 1
Your program must read four integers from the keyboard, calculate their sum
and their average and it should print the answer on the screen.
Solution:
#include <iostream>
using namespace std;
int main()
{
sum=n+m+o+p;
average=sum/4;
cout << "The sum of " << n << " and " << m << " and " << o << " and "
<< p << " is: " << sum << endl;
cout << "The average of " << n << " and " << m << " and " << o << "
and " << p << " is: " << average << endl;
Output:
When you execute this program, a console screen will pop up with a line:
Enter first number:
After entering your desired number, let's say “69”, the program will ask for
the second number:
Enter second number:
After entering your second number, which is “69”, as well, the program will
ask for the third number:
Enter third number:
Consider you entered 69 again, as the third number.Program will demand the
fourth number:
Enter fourth number:
Just say that you entered 69 again, as the fourth number.
Your program will add all of your entered numbers and then divide their sum
on 4. After calculating It will print:
Problem-2
Your program must read the temperature in Celsius and change it into
Fahrenheit, using the following equation:
Celsius = (100 / 180) * (Fahrenheit - 32)
Solution:
We have to convert this formula manually to find the amount of Fahrenheit.
So from
Celsius = (100 / 180) * (Fahrenheit - 32)
We may Calculate:
Celsius = (5 / 9) * (Fahrenheit - 32)
(9 * Celsius) / 5 = (Fahrenheit - 32)
((9 * Celsius) / 5) + 32 = Fahrenheit
Fahrenheit = ((9 * Celsius) / 5) + 32
Now, using this formula, we may write our program.
#include<iostream>
using namespace std;
int main()
{
Output:
When you execute this program, a console screen will pop up saying:
Enter the temperature in Celsius :
After putting your desired temperature, let's say 78, the program will
calculate according to the formula and will give out the output as:
Now, programming of the larger programs follow the same process. At first,
you need to understand what the problem is. Then, you may break your larger
program into smaller parts or modules. This programming style, basically, is
known as structured Programming.
3.1 Structured Programming and Designing
In Structured programming, it is defined that a program must be divided into
a few modules and it can be further subdivided into many other modules.
In this chart, we may learn about how structured programming works:
First of all, we have a program that we have to develop. In this case, we break
it into two parts, i.e. Module A and module B. Moving forward, Module B is
sub dividen in two sub modules, Module B-1 and Module B-2.
So, we can think that Module B-1 and Module B-2 are the smaller parts of
Module B and Module A and Module B are the sub modules of a larger
program.
Our program will work by calling different modules. For example, if we want
module A to send data to module B, Both modules will communicate through
the main program. We have to remember that direct communication between
two modules is not possible if they don't have a calling-called relationship.
Moreover, a module, in structured programming can be called by only one
higher module. This allows data to pass through a function and this technique
is known as parameter passing.
3.2 Functions in C++
In C++, module and submodules are known as functions. In every C++
program, there should be one or more functions and one of them must be
main. Main is the key function, your program must start and end on main and
main can call other functions, if necessary.
A function is an independent module, that is called to perform some specific
tasks. In C++, function can return a value to the caller. In a program, main is
called by the OS (operating system), after that main is responsible for calling
other functions. When main performs its task, the control then returns back to
the operating system.
Generally, the task of a function is to receive data, works on it and returns it
in a compiled form. With its pros, function can have side effects as well. A
function can change the state of a program.as it may reduce efficiency of a
program. Moreover, receiving and returning data to an outside source and to
change any variable’s value can be a function’s side effects.
C++ provides a large use of functions in it as functions can be used to
factorize a program. Secondly, functions can be helpful if you want to use the
same function in many parts of your program. For example, if you want to
calculate the average of five random numbers. So instead of coding all the
time, you may develop a function and can call it, whenever you need it.
To understand the coding for functions, we may have a look on this code:
#include <iostream>
using namespace std;
// Function declaration
int mul (int,int);
// Main Function
int main()
{
// Function Call
cout<<mul(1,99);
return 0;
}
/* Function is defined after the main method */
int mul(int num1, int num2){
int num3 = num1*num2;
return num3;
}
Functions must be declared and defined, like any other object in C++. In
C++, we can declare a function by the declaration of prototype. The
definition of a function contains a code to perform some specific tasks. We
may understand it with this example:
#include <iostream>
// Declaration of Prototype
Int mul (int, int)
Int main ()
{
// Local declarations
………….
// Statements
………….
// Calling of a function can be done in statements
cout<<mul(1,99);
………….
………….
return 0;
}
// Definition of a function is done after the calling function
int mul(int num1, int num2)
{ // Statements
int num3 = num1*num2;
return num3; // Multiplication
}
Function Definition
The definition of a function is based upon the code for a function. In C++, it
has two parts:
Function Header
Function Body
// Function Header
return_type function name (parameter list)
// Function Body
{
// Local Declarations
………….
// Statements
………….
// Function Name
…..
……….
}
Function Header
Return Type
Function Name
Parameter List
A semicolon is not allowed on the end of it, otherwise, there will be a syntax
error.
In function header, if the return type is not perfectly coded, the compiler will
assume it an integer. If you are not returning anything in your code, you have
to code the return type as void.
Function Body
Generally, a function body has two main parts; Declarations and Statements.
It starts with local declarations and the declaration of variables. Following the
declarations, statements are coded. Statement section ends with a return
command. If a function is returning a void-type, It can be written without a
return command, but it is a good practice to still use it.
For Example:
Prototype Declaration
Function Call
#include <iostream>
using namespace std;
// Prototype declaration of a function
int add(int, int);
int main()
{
int n, m, o;
cout<<"Enters first number: ";
cin >> n;
cout<<"Enters second number: ";
cin >> m;
// Function call
o = add(n, m);
cout << "Sum of your desired numbers = " << o;
return 0;
}
// Function definition
int add(int a, int b)
{
int add;
add = a + b;
// Return statement
return add;
}
#include <iostream>
// Function Declaration
Hello (void);
Int main (void)
{
//Statements
……
// Function call
Hello();
return;
}
// Function Definition
void Hello(void)
{
cout<<”Hello to C++”
return;
} // Greeting print
Function Example
Problem:
Write a program which reads an integer from user and prints the least
significant (right most) digit.
Solution:
#include <iostream>
{
cout << " Enter an integer: ";
int m;
cin >> m;
int digit = n (m);
cout << " Least Significant digit is: "<< digit << endl;
return 0;
} // main
/* ============= First Digit =================*/
// This function extracts the least significant
// Digit of an integer
// Pre "m" contains an integer
// Post Returned least significant digit
int n (int m)
{
return (m % 10);
} // First Digit
3.3 Default Parameter Arguments
C++ provides us with the capability to define default values for the
parameters. In C++, default values are used as the initializers. When such a
function is called, compiler uses default values to initialize the compilation
process. We have to remember that coding of default parameters in the
prototype statement of a function provides more efficiency and
documentation to the function. For Example:
#include <iostream>
using namespace std;
void display(char = '*', int = 1);
int main()
{
cout << "No Argument passed: ";
display();
Problem - 1
Write a C++ code to determine whether the entered number is even or odd.
Solution:
#include <iostream>
When you will compile this code, a console screen will pop up with a text:
Enter a number:
If you enter an even number, let’s say 68, screen will show:
68 is even
And, if you put an odd number, let's say 69, your screen will display:
69 is even
Problem - 2
Solution:
#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
int n,m;
cout<<"Enter your first number: ";
cin>>n;
cout<<"Enter your second number: ";
cin>>m;
cout<<"Your Numbers, Before swapping: "<<endl;
cout<<"First Number = "<<n<<endl;
cout<<"Second Number = "<<m<<endl;
swap(n,m); // function call by reference
cout<<"Your Numbers, After swapping"<<endl;
cout<<"First Number = "<<m<<endl;
cout<<"Second Number = "<<n<<endl;
getch();
return 0;
}
Write a C++ program to print the result in a function. For this, use
two sub functions to display results. One sub function would be
printing the results, the other one should print the measurements
and charges.
1 43 33 23 25.60
2 36 9 1 9
3 16 13 12 24.25
O2 = N2+M2
Area = 0.5 *(N * M)
Chapter 4: Selection-Making
In this chapter, we will study about “Selection”. Selection is the second
fundamental of structured programming. Selection allows a user to select
between two or more alternatives in any function. So, we may say that In
C++, selection allows us to make decisions.
In our daily life, we face many issues, when we have to make a decision, for
example, we have to select between strawberry and chocolate ice cream, or
maybe we have to select between black or brown shoes. Imagine our world,
without selection, how boring it would be!
So, moving towards the point, in this chapter, we will know about how the
selection is made by a computer program. We have to remember that the
choices made by a computer are really simple. Computer makes selection in
binary form, i.e. 0 and 1. Typically, 0 is used as false or off and 1 is used as
true or on.
In C++, we may represent logical data in two manners. Firstly, we may use
boolean data (bool) with constant identifiers, true and false. On the other
hand, we may use other data types, such as integers (int) and characters (char)
to represent logical data. If an item is zero among the data, it would be
considered as false.
Logical Operators
In C++, usually we have three logical operators. We can use them to combine
and create logical values such as not, or and and.These operators are shown
in table below:
Operator Demonstration
! not
|| Logical or
Not Operator
And Operator
Or Operator
Or Operator “||” is also a binary operator. Like and operator, or operator also
has four possibilities. But in this operator’s case, the result would be false,
only if both operands are false.
To understand these operators use in C++, we may use these tables below
false true
true false
C++ Language
n !n
Logical
n m n && m
C++ Language
n m n && m
Logical
n m n && m
C++ Language
n m n && m
Compiler can evaluate binary relationships, usually with two methods. The
only difference in these methods is about, if we need to evaluate the full
expression or a part of it.
In the first method, the compiler will evaluate the whole expression, even if
there is no need of it. For example, in the case of and operator, the entire
statement will be evaluated by the compiler, even if the first operand is false.
Similarly, in the case of Or operator, compiler will go for the full relation, if
the first operand is true.
In the second method, a programmer can set a code up to print the resulting
value as soon as the compiler knows the result. If this method, the compiler
does not need to go through full expression. It will print false, as soon as it
reads a false statement in the case of and operator. Similarly, it will print true,
as soon as it reads a true statement, in case of or operator.
The first method was used by pascal computer language and the second
method was introduced by C++ itself. As we can see, the second method
seems more efficient but it may have some problems because of the side
effects of the second operand. Usually, it causes because of poor
programming skills,
#include <iostream>
using namespace std;
main() {
int n = 5;
int m = 20;
int o;
if(n && m) {
cout << "For line 1 - Condition is true"<< endl ;
}
if(n || m) {
cout << "For line 2 - Condition is true"<< endl ;
}
if(n && m) {
cout << "For line 3 - Condition is true"<< endl ;
} else {
cout << "For line 4 - Condition is not true"<< endl ;
}
return 0;
}
Relation Operators
Operator Meaning
== Equals to
!= Not Equals
! (n < m) n >= m
! (n > m) n <= m
! (n != m) n == m
! (n <= m) n>m
! (n >= m) n<m
! (n == m) n != m
#include<iostream>
using namespace std;
int main()
{
int n=10,m=20,o=10;
if(n>m)
cout<<"n is greater"<<endl;
if(n<m)
cout<<"n is smaller"<<endl;
if(n<=o)
cout<<"n is less than or equal to m"<<endl;
if(n>=m)
cout<<"n is less than or equal to m"<<endl;
return 0;
}
4.2 Two Way Selection
Usually, any decision statement in a computer is known as two way selection.
Decision is presented to the computer, a conditional statement and computer
can answer it as true or false.
In such conditions, if the answer is true, an action or a set of actions is
performed. On the other hand, if the answer is false, different action or set of
actions is performed.
If, Else
If (expression)
{
Statements
}
Else
{
Statements
}
Here are some points, we have to keep in mind about if else statements:
if (n == 69)
N++;
else
n--;
else
{
cout << “.....”;
}
The fourth and fifth rules for if else statements are closely tied to each other.
We know that any statement can be used in if else condition but we have to
remember that it is a good practice to use a compound statement for a
complex logic.
Problem:
To understand if else statement more precisely, we may write a program that
reads an integer and prints weather the integer in positive or negative.
Solution:
#include <iostream>
using namespace std;
int main()
{
int n;
cout << "Enter an integer: ";
cin >> n;
// checks if the integer is positive
if ( n > 0)
{
cout << "You have entered a positive integer: " << n << endl;
}
else
{
cout << "You have entered a negative integer: ";
}
return 0;
}
if (expression)
{
Statements
……..
}
In C++, false statement can be omitted but a true statement can never be
omitted. Most of the times, true statement will always be coded as a null
statement. We have to keep in mind that the null else statement is not a
branch of if else statement. To further understand the formation of a null else
statement, we have to look at the example below
If Else Statement:
if (expression)
;
Else
{
……
…...
}
if ( !expression )
{
Statements
………..
}
else
; // Null Else Statement
Problem:
We have to write a C++ program that may read three integers from user and
print the highest among them.
Solution:
#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
int n, m, o, maximum;
cout<<"Enter first number: ";
cin>>n;
cout<<"Enter second number: ";
cin>>m;
cout<<"Enter third number: ";
cin>>o;
maximum = n;
if(m>maximum)
{
maximum = m;
}
if(o>maximum)
{
maximum = o;
}
cout<<"\n"<<"The largest of your entered numbers is: "
<<maximum;
getch();
}
Nested If Statements
Previously, we have learned that the if else statements may be any statements,
it can include other if else statements as well. So, when an if else statement
includes another if else statement, this is known as a nested if statement.
There is no specific limit for how many levels in an if else can be nested, but
if the nesting level is increased by three, it normally reduces the readability
and understandability of the code. To understand nested if statements, we
may take a look on this coding example
if (expression)
{
if (expression)
{
Statements
………………..
}
else
{
Statements
…………
}
else
{
statements
}
}
Switch (expression)
{
case constant - 1 : statement
…….
statement
case constant - 2 : statement
…….
statement
case constant - n : statement
…….
statement
default : statement
…….
statement
} // End Switch
Else If Statement
Switch statement works, when and only when the case values are integers.
We will need else if statement if we need a multi way selection in a non
integer data. C++ has no concepts of else if statements in ot. It is a
programming style, basically.
In else if statement, we code else if on a single line and align it with a
previous if statement. The syntax for this style looks something like
If (n >= 90)
discount = ‘V’;
Else if (n >= 80)
discount = ‘K’;
We have to remember that else if statement is only used when the same basic
expression is being evaluated.
In C++, else if is an artificial construct, that is only used when
Problem
Write a C++ program that reads operand and operator from the user and
prints the answer.
Solution:
#include <iostream>
using namespace std;
int main()
{
char o;
float n, m;
cout << "Enter an operator (+, -, *, /): ";
cin >> o;
cout << "Enter first operand: ";
cin >> n;
cout << "Enter second operand: ";
cin >> m;
switch (o)
{
case '+':
cout << n << " + " << m << " = " << n+m;
break;
case '-':
cout << n << " - " << m << " = " << n-m;
break;
case '*':
cout << n << " * " << m << " = " << n*m;
break;
case '/':
cout << n << " / " << m << " = " << n/m;
break;
default:
// operator is doesn't match any case constant (+, -, *, /)
cout << "Error! operator is not correct";
break;
}
return 0;
}
Output:
When you will compile this code, a console screen will pop up saying
Enter an operator (+, -, *, /):
After entering operator, let’s say /, your program will ask for your operands,
one by one, as
Enter first operand:
Enter second operand:
Let’s say you have entered both operands, 2. Your program will print output
such as
2/2=1
4.5 Programming Examples
Problem
Write a C++ program for banking management system. Your code should
include cases and selection.
Solution:
#include<iostream>
#include<iomanip>
#include<fstream>
#include<cctype>
{
int acno;
char name[50];
int deposit;
char type;
public:
void create_acnt();
void show_acnt() const;
void modify();
void dep(int);
void draw(int);
void report() const;
int retacno() const;
int retdeposit() const;
char rettype() const;
};
void acnt::create_acnt()
{
void acnt::modify()
{
cout<<"\nAccount No. : "<<acno;
cout<<"\nModify Account Holder Name : ";
cin.ignore();
cin.getline(name,50);
cout<<"\nModify Type of Account : ";
cin>>type;
type=toupper(type);
cout<<"\nModify Balance amount : ";
cin>>deposit;
}
void acnt::dep(int x)
{
deposit+=x;
}
void acnt::draw(int x)
{
deposit-=x;
}
void acnt::report() const
{
cout<<acno<<setw(10)<<" "<<name<<setw(10)<<" "
<<type<<setw(6)<<deposit<<endl;
}
void write_acnt();
void display_sp(int);
void modify_acnt(int);
void delete_acnt(int);
void display_all();
void deposit_withdraw(int, int);
void intro();
//Main Function for our Program
int main()
{
char ch;
int num;
intro();
do
{
system("cls");
cout<<"\n\n\n\tMAIN MENU";
cout<<"\n\n\t01. NEW ACCOUNT";
cout<<"\n\n\t02. DEPOSIT AMOUNT";
cout<<"\n\n\t03. WITHDRAW AMOUNT";
cout<<"\n\n\t04. BALANCE ENQUIRY";
cout<<"\n\n\t05. ALL ACCOUNT HOLDER LIST";
cout<<"\n\n\t06. CLOSE AN ACCOUNT";
cout<<"\n\n\t07. MODIFY AN ACCOUNT";
cout<<"\n\n\t08. EXIT";
cout<<"\n\n\tSelect Your Option (1-8) ";
cin>>ch;
system("cls");
switch(ch)
{
case '1':
write_acnt();
break;
case '2':
cout<<"\n\n\tEnter The account No. : "; cin>>num;
deposit_withdraw(num, 1);
break;
case '3':
cout<<"\n\n\tEnter The account No. : "; cin>>num;
deposit_withdraw(num, 2);
break;
case '4':
cout<<"\n\n\tEnter The account No. : "; cin>>num;
display_sp(num);
break;
case '5':
display_all();
break;
case '6':
cout<<"\n\n\tEnter The account No. : "; cin>>num;
delete_acnt(num);
break;
case '7':
cout<<"\n\n\tEnter The account No. : "; cin>>num;
modify_acnt(num);
break;
case '8':
cout<<"\n\n\tThanks for using bank managemnt system";
break;
default :cout<<"\a";
}
cin.ignore();
cin.get();
}while(ch!='8');
return 0;
}
void write_acnt()
{
acnt ac;
ofstream outFile;
outFile.open("account.dat",ios::binary|ios::app);
ac.create_acnt();
outFile.write(reinterpret_cast<char *> (&ac), sizeof(acnt));
outFile.close();
}
void display_sp(int n)
{
acnt ac;
bool flag=false;
ifstream inFile;
inFile.open("account.dat",ios::binary);
if(!inFile)
{
cout<<"File could not be open !! Press any Key...";
return;
}
cout<<"\nBALANCE DETAILS\n";
void modify_acnt(int n)
{
bool found=false;
acnt ac;
fstream File;
File.open("account.dat",ios::binary|ios::in|ios::out);
if(!File)
{
cout<<"File could not be open !! Press any Key...";
return;
}
while(!File.eof() && found==false)
{
File.read(reinterpret_cast<char *> (&ac), sizeof(acnt));
if(ac.retacno()==n)
{
ac.show_acnt();
cout<<"\n\nEnter The New Details of account"<<endl;
ac.modify();
int pos=(-1)*static_cast<int>(sizeof(acnt));
File.seekp(pos,ios::cur);
File.write(reinterpret_cast<char *> (&ac), sizeof(acnt));
cout<<"\n\n\t Record Updated";
found=true;
}
}
File.close();
if(found==false)
cout<<"\n\n Record Not Found ";
}
void delete_acnt(int n)
{
acnt ac;
ifstream inFile;
ofstream outFile;
inFile.open("account.dat",ios::binary);
if(!inFile)
{
cout<<"File could not be open !! Press any Key...";
return;
}
outFile.open("Temp.dat",ios::binary);
inFile.seekg(0,ios::beg);
while(inFile.read(reinterpret_cast<char *> (&ac), sizeof(acnt)))
{
if(ac.retacno()!=n)
{
outFile.write(reinterpret_cast<char *> (&ac), sizeof(acnt));
}
}
inFile.close();
outFile.close();
remove("account.dat");
rename("Temp.dat","account.dat");
cout<<"\n\n\tRecord Deleted ..";
}
void display_all()
{
acnt ac;
ifstream inFile;
inFile.open("account.dat",ios::binary);
if(!inFile)
{
cout<<"File could not be open !! Press any Key...";
return;
}
cout<<"\n\n\t\tACCOUNT HOLDER LIST\n\n";
cout<<"==================================================
cout<<"A/c no. NAME Type Balance\n";
cout<<"==================================================
while(inFile.read(reinterpret_cast<char *> (&ac), sizeof(acnt)))
{
ac.report();
}
inFile.close();
}
Write a menu driven C++ program that allows user to enter five
random numbers and find their sum, average and smallest number
among them. (Use switch statement to determine among the
operators)
Write a C++ program that may calculate the change due a
customer by denomination; that is how many pennies, dimes etc
are needed in change.
Chapter 5: Concept of “Arrays” in C++
We have been using standard data types so far, such as integer, floating point
number and character. No one can deny their importance but these data types
can not handle large amount of data, they can only handle a limited data. To
learn how can we handle large data in our programs, we should study the
derived data types. We have to begin with array structures.
With the introduction of arrays we can begin the study of data structures, as
well. In this chapter, we will be studying some of the basic concepts of data
structures. In most cases, a collecting mechanism is required to organise the
data. In the programming world, use of arrays is a common organising
technique from which we can process data as an individual element and as a
group as well.
let’s say, we have a problem that requires us to read process and then print
the data. consider our data twents integers. We must also keep the integers in
memory for the duration of the program. In the beginning we will declare
twenty variables, each variable with a different name. We know that having
twenty names would create a problem. So, the point is how can we create and
store twenty integers from the keyboard. For printing those twenty integers
we will need twenty references to store them and twenty more references to
print them.
This approach may be acceptable to twenty or twenty five or twenty six
integers but this is not acceptable for a larger data, i.e. let’s say 200 or 2,000
or 20,000 integers. So, to process large amount of data we need a powerful
structure. In this case we commonly use arrays. in C++, array is a fixed size
collection of elements of the same data type.
5.1 Using Arrays in C++
In this section, we will learn how to declare and define arrays, in C++, and
after that we will look at several typical applications of arrays including
reading and writing values in arrays.
In C++ an array must be first declared and then defined before it maybe used.
Definition and Declaration tells the compiler, the name of the array, types of
its elements and the number of elements in the array. we have to remember
that the size of the array is a constant and must have a value.
In C++, declaration and definition only reserve space for elements in the
array. There will be no value that will be stored. If we want to store any value
in the array, we must first initialize the elements, then read value from the
keyboard are then assign values to each individual element in the array.
Inputting Values
In C++, another way to fill and use an array is to read the values from the
keyboard or a file. This method of inputting values can be done using a loop.
When the array is going to be completely filled, the most appropriate loop to
use, is for loop. In for loop, the number of elements is fixed and known. A
general for loop to fill an array is shown below
Assigning Values
Putting Value
In the above mentioned example, all the data would be printed in one line
after the compiler compiles the code.
For example, if we have to insert and print array element, we’ll use the code
Problem:
Write a C++ program using arrays, to read five integers from the user and
print their sum.
Solution:
#include <iostream>
using namespace std;
int main()
{
int n[5], sum = 0;
cout << "Enter 5 numbers: ";
return 0;
}
In C++, any individual element can be passed to a function like every other
ordinary variable. Elements of an array can be passed through a function as
long as its parameter type matches the function’s parameter type.
Let’s say we have a function, named as print_squareroot, which receives an
integer and prints its square root on the console screen. Using array, we can
loop array’s elements to pass through our function, one by one.
In C++, if we want our desired function to apply on the whole array, we have
to pass the whole array through function. It would be less efficient as it would
take more time and a lot of memory.
We have to remember that the name of an array is a primary expression,
whose value is determined by the first element of our array. We have to
remember these two rules, whenever we are passing the whole array to a
function.
In C++, frequency array shows the number of elements with identical values
found in a series or array of numbers. For example, if we have taken a sample
data of fifty values between 0 and 17 and we want to figure out how many
values are 1, how many are 7 and how many among them are 8.
We have to read these values, using an array called alpha. We then will create
an array of fifteen elements, which will show the repetition of each number in
the series.
To better understand this application, we have to review the following code
#include<iostream>
using namespace std;
// Driver program
int main() {
int alpha[] = {0, 5, 5, 5, 4};
int m = 5;
int n = sizeof(alpha)/sizeof(alpha[0]);
cout << frequency(alpha, n, m);
return 0;
}
Histograms
#include<iostream>
#include<conio.h>
#include<iomanip>
using namespace std;
Selection Sort
Insertion Sort
Bubble Sort
Selection Sort
Selection sort is a technique for arranging the data, in which data is further
divided into sub data, i.e. sorted data and unsorted data. System divides
sorted and unsorted data with an imaginary wall. Everytime, when ever
system move an element from unsorted data to sorted data, we can say, the
system have completed a sort pass. For further understanding of the selection
sort, we may review this code, that prints entered numbers in ascending order
#include<iostream>
#include<conio.h>
#include<bits/stdc++.h>
using namespace std;
Insertion Sort
This sorting technique is usually used by card players to sort cards in their
hands, maintaining a particular sequence.In insertion sort, an element is
picked py by the compiler from unsorted data, and inserted in it’s particular
place in sorted data. For further explanation, we may go through this code
#include<iostream>
using namespace std;
int main()
{
int o,m,n,beta,alpha[30]; //, j = m , n = n , a = alpha
cout<<"Enter the total number of elements:";
cin>>n;
cout<<"\nEnter the elements\n";
for(o=0;o<n;o++)
{
cin>>alpha[o];
}
for(o=1;o<=n-1;o++)
{
beta=alpha[o];
m=o-1;
while((beta<alpha[m])&&(m>=0))
{
alpha[m+1]=alpha[m]; //moves element forward
m=m-1;
}
return 0;
}
Bubble Sort
In this sorting, we have divided the list into two sublists, i.e. sorted sublist
and unsorted sublist. The smallest element of the data is moved to sorted
sublist and bubbled from the unsorted sublist. The process continues with the
smallest elements in our unsorted sublist. For example
#include<iostream>
int main()
{
int alpha[50],n,m,o,beta;
cout<<"Enter the total number of elements: ";
cin>>n;
cout<<"Enter the elements: ";
for(m=0;m<n;m++)
cin>>alpha[m];
for(m=1;m<n;m++)
{
for(o=0;o<(n-m);o++)
if(alpha[o]>alpha[o+1])
{
beta=alpha[o];
alpha[o]=alpha[o+1];
alpha[o+1]=beta;
}
}
cout<<"Array after bubble sort:";
for(m=0;m<n;m++)
cout<<" "<<alpha[m];
return 0;
}
5.5 Programming Examples
Problem - 1
Write a C++ program that reads elements of a matrix from the user and print
it on output.
Solution:
#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
int alpha[10][10],beta,charlie,n,m;
cout<<"Enter size of row and column: ";
cin>>beta>>charlie;
cout<<"Enter elements of matrices(row wise)"<<endl;
for(n=0;n<beta;n++)
for(m=0;m<charlie;m++)
cin>>alpha[n][m];
cout<<"Displaying matrix"<<endl;
for(n=0;n<beta;n++)
{
for(m=0;m<charlie;m++)
cout<<alpha[n][m]<<" ";
cout<<endl;
}
getch();
return 0;
}
Problem - 2
Write a C++ code to add two matrices, using multidimensional arrays.
Solution:
#include <iostream>
using namespace std;
int main()
{
int r, c, alpha[100][100], beta[100][100], sum[100][100], i, j;
cout << "Enter number of rows (between 1 and 100): ";
cin >> r;
cout << "Enter number of columns (between 1 and 100): ";
cin >> c;
cout << endl << "Enter elements of 1st matrix: " << endl;
cout << endl << "Enter elements of 2nd matrix: " << endl;
for(i = 0; i < r; ++i)
for(j = 0; j < c; ++j)
{
cout << "Enter element b" << i + 1 << j + 1 << " : ";
cin >> beta[i][j];
}
cout << endl << "Sum of two matrix is: " << endl;
for(i = 0; i < r; ++i)
for(j = 0; j < c; ++j)
{
cout << sum[i][j] << " ";
if(j == c - 1)
cout << endl;
}
return 0;
}
Write a C++ program to modify the selection sort to count the number of
exchange, needed to sort the unsorted data.
Conclusion
Congratulations! If you've made it this far. We hope that you have truly
begun to understand the very basic concepts and complexities of C++. At this
point, we suppose, you should be able to read almost any code written in C++
with confidence and understanding.
We have tried to cover a fair number of important and initial C++ language
features in this book. Furthermore, we have tried to make writing clear and
easy to understand, and this book includes many theoretical, practical, and
explained examples.
The code samples are very well-formatted, easy to read, and clean so that you
may find C++ programming easy.
Moving forward, if you are a beginner in learning C++, just read the
next book of the series to understand the advanced concepts of C++.