C M M Sammurized Note
C M M Sammurized Note
C M M Sammurized Note
Student’s Information
Name: _________________________________________________________
Year: ______________________ Shift _______________________________
Tel: _________________________ Email: ____________________________
1
What is C++?
C++ is a general-purpose computer programming language that has the following primary
characteristics:
• object-oriented
• dynamic memory allocation
• generic
• functional
C++ is a C programming language extension. C++ contains all of the elements of the C language as
well as extra features for working with objects, classes, events, and other object-oriented concepts.
C++ influenced many computer programming languages, of which the following is a list of some of
the most famous and powerful ones:
• Java
• Python
• PHP
including C#, Perl, and many more.
Concept of OOPs
1. Inheritance
Inheritance is the process by which one object can acquire the properties of another. When the class
child, inherits the class parent, the class child is referred to as derived class (sub class) and the class
parent as a base class (super class). In this case, the class child has two parts: a derived part and an
incremental part. The derived part is inherited from the class parent. The incremental part is the new
code written specifically for the class child.
2. Polymorphism.
Comes from the Greek words “poly” and “morphism”. “poly” means many and “morphism” means
form i.e.. many forms. Polymorphism means the ability to take more than one form. For
example, an operation has different behavior in different instances. The behavior depends upon the
type of the data used in the operation.
3. Encapsulation
Wrapping of data and functions together as a single unit is known as encapsulation. By default, data
is not accessible to outside world and they are only accessible through the functions which are
wrapped in a class. prevention of data direct access by the program is called data hiding or
information hiding
4. Data abstraction
Abstraction refers to the act of representing essential features without including the back ground
details or explanation. Classes use the concept of abstraction and are defined as a list of attributes
such as size, weight, cost and functions to operate on these attributes. They encapsulate all essential
properties of the object that are to be created. The attributes are called as data members as they hold
data and the functions which operate on these data are called as member functions. Class use the
concept of data abstraction so they are called abstract data type (ADT)
• #include <iostream>
Lines beginning with a hash sign (#) are directives for the preprocessor. They are not regular code
lines with expressions but indications for the compiler's preprocessor. In this case the directive
#include <iostream> tells the preprocessor to include the iostream standard file. This specific file
(iostream) includes the declarations of the basic standard input-output library in C++, and it is
included because its functionality is going to be used later in the program.
• using namespace std;
All the elements of the standard C++ library are declared within what is called a namespace, the
namespace with the name std.
So, in order to access its functionality, we declare with this expression that we will be using these
entities. This line is very frequent in C++ programs that use the standard library, and in fact it will
be included in most of the source codes included in these tutorials.
• int main ()
This line corresponds to the beginning of the definition of the main function. The main function is
the point by where all C++ programs start their execution, independently of its location within the
source code. It does not matter whether there are other functions with other names defined before or
after it – the instructions contained within this function's definition will always be the first ones to
be executed in any C++ program.
For that same reason, it is essential that all C++ programs have a main function. The word main is
followed in the code by a pair of parentheses (()). That is because it is a function declaration: In C++,
what differentiates a function declaration from other types of expressions are these parentheses that
follow its name. Optionally, these parentheses may enclose a list of parameters within them.
• cout << "Hello World!";
This line is a C++ statement. A statement is a simple or compound expression that can actually
produce some effect. In fact, this statement performs the only action that generates a visible effect
in our first program. cout represents the standard output stream in C++, and the meaning of the entire
statement is to insert a sequence of characters (in this case the Hello World sequence of characters)
into the standard output stream (which usually is the screen). cout is declared in the iostream standard
file within the std namespace, so that's why we needed to include that specific file and to declare that
we were going to use this specific namespace earlier in our code.
Notice that the statement ends with a semicolon character (;). This character is used to mark the end
of the statement and in fact it must be included at the end of all expression statements in all C++
programs (one of the most common syntax errors is indeed to forget to include some semicolon after
a statement).
• return 0;
The return statement causes the main function to finish. return may be followed by a return code (in
our example is followed by the return code 0). A return code of 0 for the main function is generally
interpreted as the program worked as expected without any errors during its execution. This is the
most usual way to end a C++ console program.
To see the output of the above C++ source code, navigate to "Build" and select "Build and run" or
directly hit the "F9" key. After building and running the above C++ program, here is a snapshot of
the output:
I used the red arrow to focus your attention solely on the output text.
In a separate article, I defined each and every line of code in the preceding C++ example program.
You can find it here: C++ basic syntax.
Now that everything is in place, let's get started on the course.
Exercise 1:
- Write a C++ program to print “Hello World!”
- Write a program to print your Name:
Comments in C++
Comments are content written within the program to explain specific blocks of code or to aid in
debugging.
Comments are text that is ignored by the compiler during compilation and execution in C++ or any
other programming language. The two types of comments that can be used in a C++ program are as
follows:
1. Single-line comments
2. Multi-line comments
return 0;
}
In the above example, the second "cout" statement will not be executed because I used "//" to make
it a comment.
return 0;
}
You will get the same output as in the previous example. You can also use "/* comment_content */"
to write a single-line comment.
8. Stress relief:
Commenting on development tools, competitors, employers, working conditions, or the quality
of the code itself are the ways to relieve stress. The occurrence of this phenomenon can be easily
seen from online resources that track profanity in source code.
Constants in C++
Constants in C++ refer to variables with fixed values that cannot be changed. Once they are defined
in the program, they remain constant throughout the execution of the program. They are generally
stored as read-only tokens in the code segment of the memory of the program. They can be of any
available data type in C++ such as int, char, string, etc.
To create a constant variable in C++, use the "const" keyword before defining a normal variable.
As an example:
#include<iostream>
using namespace std;
int main()
{
const float pi = 3.1416;
float rad = 10.3;
cout<<"Area = "<<pi*rad*rad;
cout<<endl;
return 0;
}
I used the following C++ statement in the above example
cout<<endl;
only to create a single line space between the output text and the "Process returned 0 (0x0) execution
time: 0.047 s" for your convenience to make the output text more visible.
Exercise 2:
Write a program to print the following | Use Single and Multi-line comments:
1- Name
2- Date
3- Year
Tip: You may either use underscore in variable names to separate parts of the name, such as
last_name, first_name, and main_balance, or you may go for "capital style" notation, such as
lastName, firstName, and mainBalance, i.e., capitalizing the first letter of the next word.
Exercise 3:
Write a program to collect your personal information | remember to apply escape sequences:
1- First_Name:
2- Second_Name:
3- Department:
4- Index_No:
Keywords in C++
To a language compiler, certain words have a heightened significance, and these are known as
keywords. Because these are reserved words that are used for specific purposes, you are not allowed
to use them as regular identifier names.
I previously stated that reserved words or keywords may not be used as identifiers. As a result, it is
critical to remember the list of keywords so that you do not accidentally use them as identifiers. As
C++ keywords, keep the following list in mind:
• asm: To declare that a block of code is to be passed to the assembler.
• auto: A storage class specifier that is used to define objects in a block.
• break: Terminates a switch statement or a loop.
• case: Used specifically within a switch statement to specify a match for the
statement’s expression.
• catch: Specifies actions taken when an exception occurs.
• char: Fundamental data type that defines character objects.
• class: To declare a user-defined type that encapsulates data members and operations
or member functions.
• const: To define objects whose value will not alter throughout the lifetime of program
execution.
• continue:- Transfers control to the start of a loop.
• default:- Handles expression values in a switch statement that are not handled by
case.
• delete: Memory deallocation operator.
• do: indicate the start of a do-while statement in which the sub-statement is executed
repeatedly until the value of the expression is logical-false.
• double: Fundamental data type used to define a floating-point number.
• else: Used specifically in an if-else statement.
• enum: To declare a user-defined enumeration data type.
• extern: An identifier specified as an extern has an external linkage to the block.
• float:- Fundamental data type used to define a floating-point number.
• for: Indicates the start of a statement to achieve repetitive control.
• friend: A class or operation whose implementation can access the private data
members of a class.
• goto: Transfer control to a specified label.
• if: Indicate the start of an if statement to achieve selective control.
• inline: A function specifier that indicates to the compiler that inline substitution of
the function body is to be preferred to the usual function call implementation.
• int: Fundamental data type used to define integer objects.
• long: A data type modifier that defines a 32-bit int or an extended double.
• new: Memory allocation operator.
• operator: Overloads a c++ operator with a new declaration.
• private: Declares class members which are not visible outside the class.
• protected: Declares class members which are private except to derived classes
• public: Declares class members who are visible outside the class.
• register: A storage class specifier that is an auto specifier, but which also indicates to
the compiler that an object will be frequently used and should therefore be kept in a
register.
• return: Returns an object to a function’s caller.
• short: A data type modifier that defines a 16-bit int number.
• signed: A data type modifier that indicates an object’s sign is to be stored in the high-
order bit.
• sizeof: Returns the size of an object in bytes.
• static: The lifetime of an object-defined static exists throughout the lifetime of
program execution.
• struct: To declare new types that encapsulate both data and member functions.
• switch: This keyword is used in the “Switch statement”.
• template: parameterized or generic type.
• this: A class pointer points to an object or instance of the class.
• throw: Generate an exception.
• try: Indicates the start of a block of exception handlers.
• typedef: Synonym for another integral or user-defined type.
• union: Similar to a structure, struct, in that it can hold different types of data, but a
union can hold only one of its members at a given time.
• unsigned: A data type modifier that indicates the high-order bit is to be used for an
object.
• virtual: A function specifier that declares a member function of a class that will be
redefined by a derived class.
• void: Absent of a type or function parameter list.
• volatile: Define an object which may vary in value in a way that is undetectable to the
compiler.
• while: Start of a while statement and end of a do-while statement.
Above are the list of character set, which are used most of the time, specially the first two which are
"letters" and "digits". However, C++ can process any of the 256 ASCII characters as data or as
literals.
Note that the term "literals" refers to the character or group of characters (word) that is used to
describe the value that is used in the program.
The input operator (">>") ("get from"), also known as the stream extraction operator, is used to read
a value from standard input.
C++ Input Operator Example
Following is an example program in C++ that uses the C++ input operator, which is ">>.".
#include<iostream>
using namespace std;
int main()
{
int num;
cin>>num;
return 0;
}
If you execute the above C++ program, you will get nothing in the output. The only thing you need
to do with the output console is enter a number, say "23," and hit the "ENTER" key to see the
following output:
C++ Variables
Variables, one of the most important concepts in the C++ programming language, will be introduced
and investigated in this article. So, without further ado, here is a list of topics that are all related to
the "variables" discussed in this article.
• Introduction to variables
• Declaration of a Variable
• Initialization of a variable
• Dynamic initialization of a variable
• Variable scope
• Storage classes
#include<iostream>
using namespace std;
int main()
{
int age;
cout<<"How old are you? ";
cin>>age;
cout<<"\nYou're "<<age<<" years old.";
cout<<endl;
return 0;
}
Exercise 4:
Write a program C++ to check your age | remember to apply escape sequences:
Initialization of a variable in C++
Declaring a variable without a value can be called an "uninitialized variable," and the variable's value
is said to be "undefined." A first value (initial value) may be specified in the definition of a variable.
A variable with a declared first value is said to be an initialized variable.
The following is the general syntax for assigning values to variables in C++.
type variableName = value;
Here is a code fragment showing the variable initialization in C++.
int val = 100;
Let's take an example program demonstrating C++ variable initialization.
#include<iostream>
using namespace std;
int main()
{
int a = 10, b = 20;
cout<<"The value of 'a' = "<<a;
cout<<endl;
cout<<"The value of 'b' = "<<b;
cout<<endl;
return 0;
}
The output produced by the above C++ program should exactly be:
The value of 'a' = 10
The value of 'b' = 20
However, instead of initializing a variable's value when it is declared, you can do so later in the
program. For example:
int val;
val = 20;
Let me create another example for your understanding. So the following program is created after
modifying the previous program.
#include<iostream>
using namespace std;
int main()
{
int a, b, sum;
a = 10, b = 20;
cout<<"The value of 'a' = "<<a;
cout<<"\nThe value of 'b' = "<<b;
sum = a+b;
cout<<"\n\nThe sum of 'a' and 'b' is "<<sum;
cout<<endl;
return 0;
}
The following is the output:
The value of 'a' = 10
The value of 'b' = 20
The sum of 'a' and 'b' is 30
In the preceding example, the variable "avg" was dynamically assigned at program runtime, whereas
the variable "sum" was dynamically changed during program runtime.
Important: Variables that haven't been initialized aren't empty. If you do not initialize your
variables, they will contain junk (or garbage) values left over from the program that last used the
memory location they now occupy until the program places a value there.
cin>>num;
if(num < 10)
break;
}
cout<<"\nThe latest value of 'num' = "<<num;
cout<<endl;
return 0;
}
The sample run of the above C++ program with some sample inputs, say: 12, 32, 45, 676, and 3,
should exactly be:
Enter a number less than 10: 12
Enter a number less than 10: 32
Enter a number less than 10: 45
Enter a number less than 10: 676
Enter a number less than 10: 3
The latest value of 'num' = 3
In the above example, the variable "num," which is defined above the "main()" method, outside all
the functions and blocks, is called a global variable.
4. double
5. bool
6. void
Please note: The "int" data type represents integers, the "char" data type represents characters, the
"float" data type represents floating-point numbers, the "double" data type represents double
precision floating-point numbers, the "bool" data type refers to boolean type values (true or false),
and the "void" data type represents an empty set of values.
Now supply the input, say 210 or any number, and hit the "ENTER" key, and then 40 and hit the
"ENTER" key again to see the following output:
As already stated, an "int" type value cannot have a fractional part. For example:
#include<iostream>
using namespace std;
int main()
{
int num;
The fractional part will be removed automatically if you try to initialize a number with a fractional
part to a variable of the "int" type. You need to use the "float" type in that case.
return 0;
}
of values. However, floating-point numbers have one disadvantage as well. In general, floating-point
operations are slower than integer operations.
A byte is made up of 8 bits, with a bit being the smallest unit of memory. 1 bit can represent two
distinct binary number combinations (0 and 1), i.e., 21, 2 bits can represent four distinct binary
number combinations (00, 01, 10, 11,) i.e., 22, and so on. As a result, a single byte (8 bits) can
represent 28 = 256 different combinations. A two-byte unit, for example, can represent 65536 (216)
different values.
To determine the actual size of a variable on your platform, use the "sizeof()" method. As an
example:
#include<iostream>
using namespace std;
int main()
{
cout<<"\"int\" = "<<sizeof(int);
cout<<"\n\"unsigned int\" = "<<sizeof(unsigned int);
cout<<"\n\"signed int\" = "<<sizeof(signed int);
cout<<endl;
return 0;
}
My system has a 64-bit architecture, and the following is the output of the above C++ example on
my platform, using the "Code::Blocks" IDE:
Please note: The \n is used to insert a line break on the output console, whereas \" is used to output
a double quote.
The setw() manipulator does not stick from one cout statement to the next. For example, if you want
to right-justify three numbers within an 8-space field, you will need to repeat setw() for each value,
as shown below:
cout<<setw(8)<<22<<"\n";
cout<<setw(8)<<4444<<"\n";
cout<<setw(8)<<666666<<endl;
The output will be (each underscore represents a blank space):
______22
____4444
__666666
Note: The endl and "\n" are both used to break the line.
See how well-organized the output becomes after formatting it. However, if we remove all the
"setw()" methods from the above example, that is, replace the last "cout" statement with the
following:
cout<<num<<"*"<<i<<"="<<num*i<<"\n";
then the output should look like this:
Enter a number: 8
Addition operator
The arithmetic binary operator + adds the values of its two operands, yielding the sum of their values.
Here's an example of how to use the addition operator in C++.
4 + 10 results in 14
a + 5(a=2) results in 7
a + b(a=4, b=6) results in 10
Subtraction operator
The - operator takes the second operand and subtracts it from the first. Here's an example of how to
use the subtraction operator in C++.
14 - 3 evaluates to 11
a - b(a=7, b=5) evaluates to 2
Multiplication operator
The x operator multiplies the operand values. Here's an example of how to use the multiplication
operator in C++.
3 × 4 evaluates to 12
b × 4(b=6) evaluates to 24
a × c(a=3, c=5) evaluates to 15
Division operator
The / operator divides the first and second operands. Here's an example of how to use the division
operator in C++.
100/5 evaluates to 20
a/2(a=16) evaluates to 8
a/b(a=159, b=3) evaluates to 5.3
Modulus operator
The % operator calculates the modulus of its first operand in relation to its second. That is, it yields
the remainder of dividing the first operand by the second. Here's an example of how to use the
modulus operator in C++.
19%6 evaluates to 1
Because 6 enters 19 three times with a remainder of one. As a result, the preceding statement
evaluates to 1.
where a is a variable to whom the value is being assigned, and cve can either be a constant, a
variable, or an expression. Following are some examples of assignment statements:
x = 16;
y = 3.6;
z = x + y;
z = z × x;
a = b + c - d;
I already mentioned that the symbol "=" is known as the assignment operator. The assignment
operator can be used serially, which is a common feature of C++.
The assignment operator = returns the value of the assignment as well as actually assigning the value
to the left-hand operand. Because of that, assignments can be chained together. This can be useful
when assigning the same value to a number of items. For example,
x = y = z = 13
This statement assigns the value 13 to x, y, and z. All the variables in this multiple assignment
statement must be declared before. Such a statement works from right to left. First, 13 is assigned to
z, then the value of z, which is now 13, is assigned to y, and y's value of 13 is assigned to x.
#include<iostream>
using namespace std;
int main()
{
int a, b;
cout<<"Enter the value of 'a': ";
cin>>a;
cout<<"Enter the value of 'b': ";
cin>>b;
if(a>b)
cout<<"\nThe value of 'a' is greater than the value of 'b'";
cout<<endl;
return 0;
}
Now supply the value of "a," say 20, and hit the ENTER key. Type another number, say 10 as the
value of "b," and hit the ENTER key to execute the "if" statement. Based on the same input as I told
you right now, here is the sample run:
The above program is missing one feature: we will not receive any output if the value of "a" is less
than "b." So now is the time to employ the "if...else" statement.
#include<iostream>
using namespace std;
int main()
{
int a, b;
cout<<"Enter the value of 'a': ";
cin>>a;
cout<<"Enter the value of 'b': ";
cin>>b;
if(a>b)
cout<<"\nThe value of 'a' is greater than the value of 'b'";
else
cout<<"\nThe value of 'a' is less than the value of 'b'";
cout<<endl;
return 0;
}
The sample run with user inputs of 10 and 20 as the values of "a" and "b" should exactly be:
Enter the value of 'a': 10
Enter the value of 'b': 20
The value of 'a' is less than the value of 'b'
case constant1:
// block of code to execute
// if "constant1" matched the "expression"
break;
case constant2:
// block of code to execute
// if "constant2" matched the "expression"
break;
case constant3:
// block of code to execute
// if "constant3" matched the "expression"
break;
case constantN:
// block of code to execute
// if "constantN" matched the "expression"
break;
default:
// block of code to execute
// if no match found
break;
}
After the expression is evaluated, the values that it returns are compared to the values of the constants
that are specified in the case statements. When a match is discovered, the block of code (set of
statements) associated with that case begins to be carried out. This continues until either
the break statement or the end of the switch statement is reached.
If a case statement does not include a break statement, the control will continue on to the next case
statement(s) until either a break statement is encountered or the end of the switch is reached. The
term "falling through" refers to the circumstance that occurs when there is no break in the case
statement. When there is no matching entry, the default statement is the one that is carried out.
The default statement is not required, and if it is not present, there will be no action taken if none of
the matches are successful.
case 1:
cout<<"Sunday.";
break;
case 2:
cout<<"Monday.";
break;
case 3:
cout<<"Tuesday.";
break;
case 4:
cout<<"Wednesday.";
break;
case 5:
cout<<"Thursday.";
break;
case 6:
cout<<"Friday.";
break;
case 7:
cout<<"Saturday.";
break;
default:
cout<<"Invalid input!";
break;
}
cout<<endl;
return 0;
}
Now supply the input, say 6, and hit the ENTER key to see the following output:
indicates that the "for" loop continues the execution of its body, which is the statement,
cout<<"codescracker.com";
until the value of "i" becomes equal to 10. In other words, if the value of "i" becomes equal to 10,
then the condition "i<10" evaluates to false, which makes the loop terminate its execution. Therefore,
the above "for" loop code snippet prints the text "codescracker.com" on the output console 10 times.
C++ for example program
The C++ program can be considered an example program for the "for" loop in C++.
#include<iostream>
using namespace std;
int main()
{
int val, x;
cout<<"Enter a number: ";
cin>>val;
Now let me explain the above "for" loop section of the above example program:
• Initially, "val = 3" entered by the user.
• Now the execution of the "for" loop begins.
• Since I already told you that the initialization expression executed first and only once, the
value 1 was initialized to "i."
• I also told you that before entering the body of the loop, the test expression must be evaluated
to true, therefore the given test expression, "i<=10," will be evaluated.
• Since the test expression, which is "i<=10" or "1<=10," evaluates to true, program flow enters
the body of the "for" loop and executes all three written statements, which are "val*i" or
"3*1" or "3," which will be initialized to "x," and using the "cout," "val * i = x" or "3 * 1 =
3" (by putting the values of all three variables) will be printed on the output console.
• Now, after the execution of the loop's body, the update expression evaluates, and therefore
the value of "i" is incremented using "i++." So "i = 2" now.
• Again, before entering the body of the loop, the test expression must be evaluated as true.
• Because this time too, the test expression "i<=10" or "2<=10" evaluates to true, the program
flow again enters the body of the loop and again executes all three statements written in it
with the updated value of "i."
• So, the loop keeps running until the test expression is evaluated as false.
{
x = val*i;
cout<<val<<" * "<<i<<" = "<<x<<endl;
i++;
}
cout<<endl;
return 0;
}
This program does the same job as the program given in the "for" loop section.
Now type a number, say 5, and hit the ENTER key to find and print its cube, as shown in the snapshot
given below:
The above program first declares the function "cube" by providing its prototype. Then, after
accepting the number, it invokes the function "cube" and assigns the return value of it to the variable
"res." As soon as the function call statement is encountered, control gets transferred to the
function body, and all its statements are executed. With the execution of a return statement, control
returns to the statement immediately following the function call statement.
int x[10];
the above statement, declares an array named "x" of the type "int" that can store up to 10 numbers
of the "int" type. Therefore, we can say that when we need to store multiple values in a single
variable, we use array.
Note: The number of values between the braces cannot be greater than the array size (here 5).
If you omit the array size, then the array becomes big enough to hold the initialization. Therefore, if
you write:
int arr[] = {97, 69, 18, 46, 83};
The above statement created exactly the same array as the previous one. So, you can also initialize
more or less than 5 values like this:
int arr[] = {10, 12, 23};
or
int arr[] = {12, 23, 34, 35, 45, 33, 10, 2, 54};
#include<iostream>
using namespace std;
int main()
{
int arr[5];
cout<<"Enter any five numbers: ";
for(int i=0; i<5; i++)
{
cin>>arr[i];
}
cout<<"\nYou entered: ";
for(int i=0; i<5; i++)
{
cout<<arr[i]<<endl;
}
cout<<endl;
return 0;
}
Now type the first number, say 10, and hit the ENTER key; then type the second number, say 12,
and hit the ENTER key; and so on. Following is the sample output after providing the five numbers
one by one.
Now let me modify the above program to print all elements of the array along with their indexing.
#include<iostream>
using namespace std;
int main()
{
int arr[5];
cout<<endl;
return 0;
}
The following snapshots show the sample run of the above program with user inputs 1, 2, 3, 4, and
5 as the five elements of the array:
= 23
Note: In C++, the lower bound is always 0 and the upper bound is size-1. (size specifies the number
of elements in the array.)
In C++, all arrays consist of contiguous memory locations. The lowest address corresponds to the
first element, and the highest address to the last element. Arrays are a way to group a number of
items into the largest possible unit. Arrays can have data items of simple types like int or float or
even of user-defined types like structures and objects.
Types of Arrays in C++
Following are the two types of C++ arrays:
• One-dimensional arrays
• Multi-dimensional arrays
The "one-dimensional" array is discussed in a separate (next) post, whereas the "multi-dimensional"
is going to be covered in this post, right after this paragraph.
Now type the first element, say 1, and hit the ENTER key. Then type the second element, say 2, and
hit the ENTER key again. In this way, provide 12 inputs as 12 array elements and hit the ENTER
key finally to produce the following output:
dataType variableNameN;
} structureVariableName;
The keyword "struct" is used to declare a structure in C++, "dataType" is a valid C++ data type,
"variableName1," "variableName2," "variableName3," and "variableNameN" are the names
of variables that are also known as structure members, and "structureVariableName" is the name of
the structure variable that will be used to access the structure members in the program to initialize
and use them. As an example,
struct {
int sno;
long int empId;
string empName;
string empCity;
} codescracker;
The preceding C++ code fragment declares a structure with four members, namely "sno," "empId,"
"empName," and "empCity," of the types "int," "long int," "string," and "string," as well as a structure
variable called "codescracker."
We can have multiple structure variables as well, for example.
struct {
int sno;
long int empId;
string empName;
string empCity;
} a, b, c, d, e;
There is another way to create a structure in C++, which is by creating the structure along with its
name or tag. The following is the general form:
struct name {
type variable1;
type variable2;
type variable3;
} structureVariables;
Through this approach, we can also create structure variables later in the program. You will see an
example of this concept later in this post.
#include<iostream>
using namespace std;
struct {
int sno;
long int empId;
string empName;
string empCity;
} xyz;
int main()
{
xyz.sno = 1;
xyz.empId = 123904;
xyz.empName = "William";
xyz.empCity = "Houston";
cout<<"S.No. = "<<xyz.sno<<endl;
cout<<"ID = "<<xyz.empId<<endl;
cout<<"Name = "<<xyz.empName<<endl;
cout<<"City = "<<xyz.empCity<<endl;
return 0;
}
The output produced by this C++ program illustrating the structures should exactly be:
S.No. = 1
ID = 123904
Name = William
City = Houston
Now let me allow the user to define the values at program runtime. The following program not only
allows the user to enter the values; it also uses multiple structure variables.
#include<iostream>
using namespace std;
struct {
int sno;
long int empId;
string empName;
string empCity;
} a, b;
int main()
{
cout<<endl;
return 0;
}
Now, let's create the same program using the second method of declaring and defining the structure,
which is by using its name and declaring its variable later in the program; that is, I will declare the
structure variable using its name or tag inside the "main ()" method.
#include<iostream>
using namespace std;
struct myStructure {
int sno;
long int empId;
string empName;
string empCity;
};
int main()
{
myStructure a, b;
cout<<endl;
return 0;
}
Communities/Websites
Visit the following websites/communities for any helpful support in C++ and improve your career
to the professional level.
- https://www.geeksforgeeks.org/
- https://www.tutorialspoint.com/wordpress/index.html
- https://www.tutorialspoint.com/index.htm
- https://olympus.mygreatlearning.com
- https://www.w3schools.com/
- https://codescracker.com/
- https://www.javatpoint.com/