2. Content in this chapter:
1.1 Understand the C++ Program Basic Structure
1.2 Identifier and data types
1.3 Basic of computer program
1.4 Identify The Compiling and Debugging
Process and Error in Programming
3. Introduction
• C++ an extension of C, was developed by
Bjarne Stroudtrup in early 1980s.
• C++ has become popular because the
combination traditional C with OOP capability.
• Object Oriented programs are easier to
understand, correct and modify.
• To give C++ instructions to comp, we need
editor & compiler.
4. Hello World!
// my first program in C++
#include <iostream>
using namespace std;
int main ()
{
cout << "Hello World!";
return 0;
}
Hello World!
5. 1.1 C++ Program Basic Structure
• Comments
• Preprocessor directives
• Header files
• Main() function
• Return statements
6. comment
• Comments are parts of the source code
disregarded by the compiler. They simply do
nothing.
• Their purpose is only to allow the programmer
to insert notes or descriptions embedded
within the source code.
7. • C++ supports two ways to insert comments:
a) // line comment
• A line comment begins with pair of slash signs
(//) and continue to the end of that same line.
b) /* block comment */
• Block comment begins with the symbol /* and
end with the symbol */ .
• Block comments are conveniently used for
statements that span across two or more lines.
8. preprocessor directives
• What’s a #?
– Any line that begins with # symbol is a pre-processor
directive
– Processed by preprocessor before compiling
• What’s pre-processor?
– A utility program, which processes special instructions are
written in a C/C++ program.
– Include a library or some special instructions to the compiler
about some certain terms used in the program
– Different preprocessor directives (commands) perform
different tasks.
– It is a message directly to the compiler.
9. • How to write/syntax ?
– Begin with #
– No semicolon (;) is expected at the end of a preprocessor
directive.
• Example : #include and #define
10. Header File
• header file, sometimes known as an
include file. Header files almost always
have a .h extension.
• Why use header file?
– For big projects having all the code in one file is
impractical. But if we split the project into smaller
files, how can we share functions between them? Ans:
By using Headers!
The purpose of a header file?
To hold declarations for other files to use.
When we use the line #include <iostream>, we
are telling the compiler to locate and then read all the
declarations from a header file named “iostream”.
11. o In program never defines cout, so how does the compiler
know what cout is?
o The answer is that cout has been declared in a header file
called “iostream”.
o If cout is only defined in the “iostream” header file, where
is it actually implemented?
o Answer: It is implemented in the runtime support library,
which is automatically linked into your program during the link
phase.
12. preprocessor directives
& header file
#include <iostream>
• Lines beginning with a hash sign (#) are directives
for the 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++.
• it is included because its functionality is going to
be used later in the program.
13. 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.
14. main() function
• main() function 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 (()).
Right after these parentheses we can find the body of the main
function enclosed in braces ({}).
• What is contained within these braces is what the function does
when it is executed.
15. return statement
• The return statement causes the main function to
finish. return may be followed by a return code
(for 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.
16. Code Indentation
• Programming style and indentation can be defined as the
way you follow to organize and document your source
code.
• a proper code indentation will make it:
– Easier to read
– Easier to understand
– Easier to modify
– Easier to maintain
– Easier to enhance
17. indentation
• The indentation comes first in formatting section.
• The first important thing is indentation is done with SPACES not
TABS.
• As we know all programs work good with SPACES and most
important part is SPACE is of fixed length in all types of system.
• But TAB is not of fixed length. So if your TAB is set to 6 then it might
be different in other's system. So if some one is having TAB setting
as 8 then your code will look different and messy.
• So during programming we should not mix TAB with SPACES, rather
we should only use spaces.
• The following code example shows up a code with proper
indentation made by spaces.
• The matching braces should be in the same column. It means the
start and close brace should have the same column location.
18. #include<iostream>
using namespace std;
int main()
{
int num1,num2,num3;
cout<<" Enter value for first number";
cin>>num1;
cout<<" Enter value for second number";
cin>>num2;
cout<<" Enter value for third number";
cin>>num3;
if(num1>num2&&num1>num3)
{
cout<<" First number is greatest:"<<endl<<"whick is= "<<num1;
}
else if(num2>num1&&num2>num3)
{
cout<<" Second number is greatest"<<endl<<"whick is= "<<num2;
}
else
{
cout<<" Third number is greatest"<<endl<<"whick is= "<<num3;
}
return 0;
}
19. #include<iostream>
using namespace std;
int main()
{
int code;
cout<<“please enter colour code”;
cin>>code;
switch(code)
{
case 1: cout<<“RED”;
break;
case 2: cout<<“YELLOW”;
break;
case 3: cout<<“BLUE”;
break;
default:cout<<“invalid colour code”;
}
return 0;
}
20. //this should not be used even single line is there
if(CGPA>=3.0) cout<<“Excellent”;
//This is also not a good practice
if(CGPA>=3.0)
cout<<“Excellent”;
// The opening brace shoud not be in the same line
if(CGPA>=3.0) {
cout<<“Excellent”;
}
// This is the perfect way to use braces
if(CGPA>=3.0)
{
cout<<“Excellent”;
}
21. Spacing
• Spacing forms the second important part in code
indentation and formatting.
• It also makes the code more readable if properly
maintained. So we should follow proper spacing
through out our coding and it should be consistent.
• Following are some examples showing the usage of
spacing in code indentation.
22. Code sample: spacing best practise
// NOT Recommended
test (i, j);
// Recommended
test(i, j);
23. All binary operators should maintain a
space on either side of the operator.
// NOT Recommended
a=b-c;
a = b-c;
a=b - c;
// Recommended
a = b - c;
// NOT Recommended
z = 6*x + 9*y;
// Recommended
z = 6 * x + 9 * y;
z = (7 * x) + (9 * y);
24. All unary operators should be written
immediately before or after their operand
// NOT Recommended
count ++;
// Recommended
count++;
// NOT Recommended
i --;
// Recommended
i--;
// NOT Recommended
++ i;
// Recommended
++i;
25. 1.2 Identifier and Data types
• Identifier, Variable and Constant
• Naming convention rules for identifier
• Declare variable and constant
• Initialize variables
• Determine identifier scope:local,global
• Explain keyword
26. Identifiers
• Identifier is simply references to memory
location which can hold data and used to
represent variables, constants and name of
function (sub-modules) in computer
programs.
27. variables
• Variable is an identifiers that refers to memory
location, which can hold values.
• Variable only store one value at one time.
• Thus the content of variable may change during
the program execution. Before it is used, it must
be declared with its data type.
• Syntax: data type variable_name
• Example: int sum;
float price;
char name;
28. • Single declaration:
Example:
int quiz1;
Int quiz2;
Int quiz3;
• Multiple declaration- variable having the same data type can be
grouped and declared using the single declaration statement.
• For example, single declaration as shown above can be declared as
a single statement.
• Example:
int quiz1,quiz2,quiz3;
29. Constant
• An identifier whose value does not change throughout
program execution.
• Allow to give name to a a value that is used several
times in a program.
• Usually constant name is capital to distinguish from
other variable.
• 2 ways of declaring constant:
a. Using constant keyword:
const float PI=3.142
b. Using preproseccor directive:
#define PI 3.142
30. Naming convention rules for identifier
a. The 1st letter must be alphabet or underscore
Example valid identifier: Example of invalid identifier:
age 1number
quiz3 5_student
total_weight
_name
b. Can be a combination of alphabet letter, digit and underscore
Example valid identifier: Example of invalid identifier:
ic_number price$
c. Cannot used c++ reserved word.
some of C++ reserved word:
asm, auto, bool, break, case, catch, char, class, const, const_cast, continue, default, delete,
do, double, dynamic_cast, else, enum, explicit, export, extern, false, float, for, friend, goto,
if, inline, int, long, mutable, namespace, new, operator, private, protected, public, register,
reinterpret_cast, return, short, signed, sizeof, static, static_cast, struct, switch, template,
this, throw, true, try, typedef, typeid, typename, union, unsigned, using, virtual, void,
volatile, wchar_t, while
d. No blank or white space characters.
Example valid identifier: Example of invalid identifier:
ic_number ic number
e. Case sensitive (the lowercase and uppercase letters are treated as different characterss)
Example:
firstnumber, Firstnumber, FirstNumber, FIRSTNUMBER are treated as different identifiers.
31. Writing a C++ Program
C++ source files
(ASCII text) .cpp
Programmer
(you)
emacs
editor
C++ header files
(ASCII text) .h
1 source file
=
1 compilation unit
Makefile
(ASCII text)
Also: .C .cxx .cc
Also: .H .hxx .hpp
readme
(ASCII text)
Eclipse
Visual Studio
32. 1.4 Identify The Compiling and Debugging
Process and Error in Programming
Compiling process of a program
• A C++ must be compiled before it can be executed.
• To do this you need a compiler, which will take the source
code and translate them into a form understood by the
computer.
• Compiler have a stage where the original program (source
code) is converted to something called object code which is
used to package up procedures and libraries so that the
program can executed successfully.
• This object code can be converted into machine code, which
is the language that computer understands.
33. Errors In Programming
There are three types of error in programming ;
1. Syntax / Compile Time Error
2. Logical Error
3. Runtime Error
34. Syntax Error
• Syntax error refers to an error in the syntax of a sequence of characters or
tokens that is intended to be written in a particular programming language.
• If a syntax error is encountered during compilation it must be corrected if the
source code is to be successfully compiled.
• Syntax errors may also occur when an invalid equation is entered into a
calculator. This can be caused by opening brackets without closing them.
Logic error
• A logic error is a bug in a program that causes it to operate incorrectly, but not
to fail.
• Because a logic error will not cause the program to stop working, it can
produce incorrect data that may not be immediately recognizable.
• With a logic error, the program can be compiled or interpreted (supposing
there are no other errors), but produces the wrong answer when executed.
• The mistake could be the logical error in a statement (for example, a wrong or
incorrect formula), an error in an algorithm, or even the wrong algorithm
selected.
35. Runtime error
• An error that occurs during the execution of a program.
• Runtime errors indicate bugs in the program or problems that the
designers had anticipated but could do nothing about.
• For example, running out of memory will often cause a runtime error.
• Example: Values that divided by zero.
int dividend = 50;
int divisor = 0;
int quotient;
quotient = (dividend/divisor); /* This will produce a runtime error! */
36. Debugging Process
• In computers, debugging is the process of locating and fixing
or bypassing bugs (errors) in computer program code or the
engineering of a hardware device.
• To debug a program or hardware device is to start with a
problem, isolate the source of the problem, and then fix it.
• A user of a program that does not know how to fix the
problem may learn enough about the problem to be able to
avoid it until it is permanently fixed.
• When someone says they've debugged a program or "worked
the bugs out" of a program, they imply that they fixed it so
that the bugs no longer exist.