0% found this document useful (0 votes)
2 views10 pages

C++ Programming Basics Explained

The document provides an overview of the fundamental concepts of C++ programming, including the structure of a C++ program, data types, variables, constants, keywords, identifiers, and operators. It explains the components of a C++ program, such as the documentation section, linking section, and the main function, along with examples of syntax and semantics. Additionally, it covers arithmetic operators and the importance of proper variable naming and the use of constants in programming.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views10 pages

C++ Programming Basics Explained

The document provides an overview of the fundamental concepts of C++ programming, including the structure of a C++ program, data types, variables, constants, keywords, identifiers, and operators. It explains the components of a C++ program, such as the documentation section, linking section, and the main function, along with examples of syntax and semantics. Additionally, it covers arithmetic operators and the importance of proper variable naming and the use of constants in programming.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Fundamentals of programming January 1, 2024

Chapter 2
2. Basics concepts of C++ programming
2.1 Structure of C++ program
Structure of a C++ program includes:
✓ Documentation section
✓ Linking section
✓ Definition section
✓ Global declaration section
✓ Class declaration
✓ Function
✓ main() functions
{
Initializations;
Executable parts;
}
✓ Function1()
{
Initializations;
Executable parts;
}…n
 Documentation Section: include comment parts, which are ignored by compiler. The comments are
used to describe the functionality of each statement in the program, its copyright, author, and date of
compilation and purpose of the program to the user. C++ supports single line (// comment) and
multiline (/* comments*/).
Syntax: // This statement is a single line comment
/* this is multiline comment */

 Link section: here we can link the necessary files and libraries to current files. Using #include directive
we can link the necessary libraries to current files.
Syntax: #include<file or library name>
Example: #include<iostream.h>

 Definition Section: It is possible to define symbolic constants. Symbolic constants are normal
identifiers which value cannot be altered.
Syntax: #define identifier constant

 Global declaration Section: variables declared under this section are available throughout the program.
 Class declaration Section: defines the class declaration.
 Functions: The function main, which has been written in the program, is an example of function. A
function is defined as group of instructions, which are assigned a name and accessed by the name.

Page 1 of 10
Fundamentals of programming January 1, 2024

Syntax:
return type function name ()
{
Statement of function;
}
A function is identified by the compiler with the help of parenthesis ( ) after the function name.
Without the parenthesis the compiler thinks it as a variable or complaints that it is undefined
symbol. So to define a function, parenthesis is must. The statement inside the brace {} forms
the body of the function and specifies the task of the function. Return type specifies the type of
data the function has to send to the calling function after the execution. It may be the result of
the task performed in the function.
Main ( ) function: the execution of the program starts from main function. Every program must have
only one main function. All other functions are called either directly or indirectly from main. The
initialization or other executable statements are included with in the main function.
Initialization part: the variables that are used in the program should be initialized here. These variables
are not available to all the functions. In C++ we can initialize the variables at any part in the function.
Executable part: A statement declared under executable part performs some tasks. Every statement
under global declaration, initialization and executable parts should be terminated with the semi colon
‘;’. A semi colon acts as a statement terminator like full stop in English.
Syntax:

#include<iostream.h>
int main ()
{
Statements;
Other functions;
}

2.2 A simple C++ program


Look the program given below:

//This program accepts to integer numbers and prints out their sum.

#include<iostream.h>
int main ()
{
int a,b,sum;
cout<<”Enter the value of a and b \n”;
cin>>a>>b;
sum=a+b;
cout<<”\n Sum=”<<sum;
}

Page 2 of 10
Fundamentals of programming January 1, 2024

 #include<iostream.h>: this statement is used to include a library file, which contains the necessary
built in functions that are used in the program. The iostream.h is a library file which have the built in
function for input and output operations like cin and cout respectively in above example. The < and >
angle bracket are not a part of a file name, but are used to indicate that this is a standard C++ library
file.

 Int: the int specifies the function need not return any value. In C++ every caller function expects a
return from the called function. If you specify a ’int’ before the function, the function does not expect
any return from the called function.

 {…}: we should specify the body of the function in between the open and close flower braces.
 cout: It is an output statement available in iostream.h library file, used to display message .It is used
for prompting message and displaying the values of the variable. To use cout you must include the
following directive at the beginning of your program
#include <iostream.h>
The basic form for writing output to the screen is
Syntax:
cout<<”the statement to be displayed“; (for displaying message) or
cout<< the name of the variable to be displayed; (for displaying the value of a variable)

 cin: It is an input statement available in iostream.h library file, used to accept values of a variable.
Syntax:
cin>>the name of the variable which its’ value is going to be accepted;

 int a,b,sum; is a declaration of an integer variables.


Special characters
There are a variety of characters in C++ that are used for special purposes, such as single-quotes, double-quotes,
backslashes, etc. To include one of these as a "regular" character in an output stream, or to assign them as a
character value, we have to let the compiler know that we don't want the "special" use of the character. To do
so, we use an escape sequence - which usually simply means preceding the desired character with a backslash \
Some of the common escape sequences are listed below:

Escape sequence Meaning


\n newline (like endl)
\t tab
\\ backslash
\' single quote
\" double quote
\nnn use ASCII value

Page 3 of 10
Fundamentals of programming January 1, 2024

For example:
cout << "Here comes a double-quote: \" there it went ... " << endl;
The ASCII value for a character is an integer interpretation of the bit pattern used to store the character.
For example, the ASCII values for the characters 'A' through 'Z' are 65 through 90.
Syntax and Semantics
The Syntax of a programming language consists of the rules for the correct use of the language. This involves
the correct grammatical construction and arrangement of the language, correct spelling, hyphenation,
inflection and so on. The syntax of a programming language has to be strictly adhered to.
Character set: The character set of a language is simply that set of symbols from which programming
languages are composed. Because the character set is a fundamental element of programming languages,
especially of data representation in computers efforts were made to generate standards. As a result two
alphabets have emerged to become the de facto standards.
Semantics
The semantics of a programming language deal with the meanings given to syntactically correct constructs of
the language. Usually, semantics is defined in terms of the program’s run-time behavior: What happens when
the program is executed with a certain set of inputs, what statements are executed, what values are assigned to
the variables, and what output is produced.
Thus syntax has nothing to do with “meaning” or run-time behavior of a program. A program could be
syntactically correct yet meaningless. The program below (code fragment) is syntactically correct but does not
have any meaning at runtime (never terminates).
sum=0;
while (sum!=-1)
sum=sum+10;
Yet syntax is a prerequisite to meaningful expression. Thus, a programming language must have a good
syntactic definition before it can properly support the development of meaningful programs.

2.3 Data Types, Variables, and Constants


• Data types
Every operation in the program manipulates with different types of data. Data can be integer, a fraction or a
string. C++ provides you to define a variable, which can hold different types of data.

• Variable
A variable is a location to store data. A variable is a symbolic name that holds different data types of data. It
represents a place in the memory where particular data is stored. To access the data, the name of the variable is
referred.

Page 4 of 10
Fundamentals of programming January 1, 2024

Most of the languages support the common data type variables viz. character type, integer type, and real
numbers. C++ also supports all the basic data types besides user defined data types.
The data types in C++ are classified as

o Primary
o User defined( structures, Unions, Classes, enumerated)
o Derived( Arrays, Functions and pointers)

Primary data set


It is classified by two ways.
1. Integral type
a. Integer (int): is used to declare the integer variables. Integer variables are used to store the
natural numbers like 1,202, 343 …etc. we can define this type of variables using int. The
integer type variable occupies 2 bytes of memory.
Syntax:
int variablename;
b. Character (char):it is used to declare the character variable. Character variable are used to
store characters like ‘A’, ‘X’, ‘4’…etc. We can define character through the key word char and
followed by the character variable. These types occupy one byte space in the memory.
Syntax:
Char variablename;
2. Floating point type:
It stores numbers with decimal places. In integer we can’t stores numbers with fractional part. In such
cases where fractional parts are necessary float serves good purpose. This data type is useful when you
want to store length, width and salary etc.

Fundamentally C++ supports 2 types of floating point types.


a. float: It is used to declare the real variables(real numbers). Like 1.23, 3.05…etc. It has 7 digits of
precision. It occupies 4 bytes of memory.
Syntax:
float real_variable;
b. double: it occupies 8 bytes of memory twice as much as type float. Stores floating point numbers
with much larger range and precision. It is used when the value of a floating number more than that
held by float data type.
Syntax: double real_variable;

Page 5 of 10
Fundamentals of programming January 1, 2024

Range of primary data set


Type Size Range
Int 2 bytes -32768 to +32767
char 1 byte -128 to +127
float 4 bytes 3.4x10-38 to 3.4x10+38
double 8 bytes 1.7x10-308 to 1.7x10+308
In primary data set the range is limited as defined .If we need to access the values out of the range it
is possible through the type modifiers.

Modifiers
We have two sets of modifiers.
o Long and short
o Signed and unsigned

Type Size Range


long int 4 bytes -2147483648 to +2147483648
long double 10 bytes 3.4x10-4932 to 3.4x10+4932
unsigned int 2 bytes 0 to 65535
unsigned char 1 byte 0 to 255
unsigned short int 2 byte 0 to 65535
unsigned long int 4 byte 0 to 4294967295

Variable naming

 The name of the variable needs to be meaningful, short and should not contain any
embedded space or symbols like?!@#$%^&*(){}[ ] . , ; ”/\. However, underscores
can be used wherever a space is required; for example, Basic_salary.
 No two variables should have the same name; for example, to accept four numbers,
one variable name cannot be used rather four different variables need to be used.
 A variable name must begin with an alphabet, which may be followed by a sequence
of alphabets or digits (0-9)
 Keywords or reserved words cannot be used as variable names.

Constants
Constants are data elements whose values do not change during program execution. It is any expression that has
a fixed value. They are of two types:

Page 6 of 10
Fundamentals of programming January 1, 2024

❖ Alphanumeric constants: comprises of A-Z, a-z, 0-9, symbols like!@#$ %^&*() {}[ ] . , ; : ’ ” / \.
Each letter, symbol or number used is called a character. It cannot be used for arithmetic calculations.
A set of character is called string. Strings are enclosed with double quotes where as characters are
enclosed with single quotes.
❖ Numeric constants: are of two type
o Integer: whole numbers
o Float : numbers with decimals
2.4 Keywords and Identifiers
Keywords
Certain words are reserved by C++ for specific purposes and may not be used as identifiers. These are called
reserved words or keywords.
The keywords used in C++ are summarized in the table given below:

Asm continue Float new signed try


break delete friend private static union
Case Do Goto protected struct unsigned
Catch Double If public switch virtual
Char Else Inline register template int
Class Enum Int return this volatile
Constant Extern Long short throw while

Identifiers
Programming languages use names to refer to the various entities that make up a program. Names are a
programming convenience, which allow the programmer to organize what would otherwise be quantities of
plain data into a meaningful and human-readable collection. As a result, no trace of a name is left in the final
executable code generated by a compiler. For example, a temperature variable eventually becomes a few bytes
of memory which is referred to by the executable code by its address, not its name.
C++ imposes the following rules for creating valid names (also called identifiers). A name should consist of
one or more characters, each of which may be a letter (i.e., 'A'-'Z' and 'a'-'z'), a digit (i.e., '0'-'9'), or an
underscore character ('_'), except that the first character may not be a digit. Upper and lower case letter are
distinct. For example:

salary // valid identifier


salary2 // valid identifier
2salary // invalid identifier (begins with a digit)
salary // valid identifier
Salary // valid but distinct from salary

Page 7 of 10
Fundamentals of programming January 1, 2024

C++ imposes no limit on the number of characters in an identifier. However, most implementation do. But the

limit is usually so large that it should not cause a concern (e.g., 255 characters).

2.5 Operators
An operator is a symbol that operates on one or more expressions producing a value that can be assigned to a
variable. Till now we have dealt with 3 operators
‘<<’ output operator used with cout [insertion operator]
‘>>’ input operator used with cin [extraction operator]
The operators used in C++ are discussed below:

2.5.1 Arithmetic Operator

C++ provides five basic arithmetic operators.

Operator Name Example


+ Addition 10+2 //gives 12
- Subtraction 10-2 //gives 8
* Multiplication 10*2 //gives 20
/ Division 10/2 //gives 5
% Remainder 10%2 //gives 0
Except for remainder (%) all other arithmetic operators can accept a mix of integer and real operands. Generally, if
both operands are integers then the result will be an integer. However, if one or both of the operands are real then
the result will be a real (or double to be exact). When both operands of the division operator (/) are integers then
the division is performed as an integer division and not the normal division we are used to. Integer division always
results in an integer outcome (i.e., the result is always rounded down).
For example:
9/2 // gives 4, not 4.5!
-9 / 2 // gives -4, not -4.5!
Unintended integer divisions are a common source of programming errors. To obtain a real division when both
operands are integers, you should cast one of the operands to be real:
int cost = 100;
int volume = 80;
double unitPrice = cost / (double) volume; // gives 1.25
The remainder operator (%) expects integers for both of its operands. It returns the remainder of integer-
dividing the operands. For example 13%3 is calculated by integer dividing 13 by 3 to give an outcome of 4 and
a remainder of 1; the result is therefore 1. It is possible for the outcome of an arithmetic operation to be too
large for storing in a designated variable. This situation is called an overflow. The outcome of an overflow is
machine-dependent and therefore undefined.

Page 8 of 10
Fundamentals of programming January 1, 2024

For example: unsigned char k = 10 * 92; // overflow: 920 > 255

It is illegal to divide a number by zero. This results in a run-time division-by-zero failure which typically causes
the program to terminate.
2.5.2 Relational operators

Relational operators are used to test the relationship between two variables, or between a variable and a
constant.
Operator Name Example
== Equal to 4==4 //gives 1
!= Not equal to 4!=4 //gives 0
>= Greater than or equal to 4>=4 //gives 1
<= Less than or equal to 4<=4 //gives 1
> Greater than 4>4 //gives 0
< Less than 4<4.1 //gives 1

2.5.3 Logical Operators


C++ provides three logical operators for combining or negates logical expression.

Operator Name Example


! Logical negation !(3==3) //gives 0
&& Logical and 3<4 && 6<6 //gives 0
|| Logical or 3<4 && 6<6 //gives 1

The compound condition combined with the AND(&&) operator evaluates to true only if all the individual
conditions evaluate to true. The logical OR(||) is use when at least one of the conditions must be true in order to
satisfy the compound condition. The logical NOT(!) reverses the result of a condition.

2.5.4 Increment or decrement operator

The auto increment (++) and auto decrement (--) operators provide a convenient way of, respectively,
adding and subtracting 1 from a numeric variable.
int k=5;
Operator Name Example
++ Auto increment(prefix) ++k+5// gives 11
++ Auto increment(postfix) K++ +5// gives 10
-- Auto decrement(prefix) --k+5 //gives 9
-- Auto decrement(postfix) k-- +5// gives 10

Prefix increment and pre decrement operator increments or decrements a variable and executes the statement.
Postfix increment and decrement operator increments or decrements a variable after the variable is executed.

Page 9 of 10
Fundamentals of programming January 1, 2024

2.5.5 Assignment operators

The assignment operator is used for storing a value at some memory location (typically denoted by a variable).
Its left operand should be an lvalue, and its right operand may be an arbitrary expression. The latter is evaluated
and the outcome is stored in the location denoted by the lvalue. An lvalue (standing for left value) is anything
that denotes a memory location in which a value may be stored. The only kind of lvalue we have seen so far in
this book is a variable.

Operator Example Equivalent to


= N=5
+= N+=5 N=N+5
-= N-=5 N=N-5
*= N*=5 N=N*5
/= N/=5 N=N/5
%= N%=5 N=N%5

2.6 Debugging and programming errors

When we attempt to produce an efficient program we should take sufficient care to maintain clarity and
readability of a program. The program errors are called bugs. The art of locating and eliminating bugs or errors
is called debugging.

Types of Programming bugs or errors


➢ Compile errors: are errors indicating program syntax errors, disk or memory access errors and
command line errors. For example
o missing expected ) , ( ,{,} and comma
o Array bounds missing], array must have at least one element; array of
references is not allowed and array size too large.
➢ Linker errors: Errors that occur when a function is miss spelled, hexadecimal overflow etc. Unable to
find the required object files in the current directory to link etc. That is when main as maid or cout is
spelled as cuot and so on.
➢ Run time errors: errors that occur at run time. It is a process where the program is compiled, linked
and executed. Errors that may occur at execution time such as divide errors, stack over flow, null
pointer termination etc. Result is not as expected due to logical errors in the program.

Page 10 of 10

You might also like