The document provides an introduction to computer programming and the C++ programming language. It discusses what a computer program is, different types of programs, and the process of computer programming. It then covers key concepts in C++ programming including data types, variables, constants, input/output, and basic program structure. The document is intended to teach programming fundamentals and provide an overview of C++ for beginners.
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
Cp week _2.
1. 1
INTRODUCTION
COMPUTER
PROGRAMMING
Computer Program
A computer program is a sequential set/collection of
instructions that performs a specific task when executed by
a computer.
Everything a computer does is done by using a computer
program
A computer program is usually written by a computer
programmer in a programming language.
Some examples of computer programs:
Operating system.
A web browser like Mozilla Firefox and Apple Safari can be used
to view web pages on the Internet.
An office suite can be used to write documents or spreadsheets.
Video games are computer programs.
2. 2
Computer Programming
The process of developing and implementing various sets of
instructions to enable a computer to do a certain task.
These instructions are considered computer programs and help
the computer to operate smoothly.
People who program are referred to as programmers and write
their code in a programming language.
Pseudocode, Algorithm
and Flow charts
3. 3
PSEUDOCODE, ALGORITHMS
AND FLOWCHARTS
Computer programming can be divided into two
phases:
Problem solving phase
Make an ordered sequence of steps that solves a
problem
These sequence of steps is called an algorithm
Implementation phase
implement using a programming language
Introduction to C++
C is a programming language developed in the
1970's alongside the UNIX operating system.
C++ is an “extension” of the C language.
C++, as opposed to C, supports “object-oriented
programming.”
C++ is pronounced as C plus plus, is a powerful
computer programming language.
C is a procedural programming language.
C++ is a an object oriented programming
language.
4. 4
Writing C++ programs
The source code of a c++ program is stored on the disk
with file extension .cpp ( stands for c plus plus).
Program stored on a text file on disk
Different text editors are used for code writing
The boreland c++ and turbo++ have their own editors for
code writing.
Visual studio IDE(integrated development environment)
Steps in compiling C++ Program
C++ compiler translates the source program with .cpp
extension into machine code called object code and
stored in newfile with .obj extension.
Object code is then linked to libraries
After linking an executable file with extension .exe is
created.
The executable program is then executed.
5. 5
Stages of compiling a C program
Preprocessing
First stage of compilation is called preprocessing.
The C preprocessor modifies a source file before handing it over to the
compiler, like defining constants # define and including header files i.e.
# include<>.
The preprocessors are the directives, which give instructions to the
compiler to preprocess the information before actual compilation start.
All preprocessor directives begin with #
Making the Object file: The compiler
After the C Preprocessor has included all the header files, the compiler
then COMPILES the program.
Compiler changes the C source file with .cpp extension into an Object
code file with .o extension.
The object file contains the binary version of the source code.
6. 6
Putting it all together: The linker
The job of the linker is link together a bunch of object files(.o files) into a
binary executable.
The file created after linking is ready to be loaded into memory and
executed by the system.
Preprocess, Compile, Link, execute
7. 7
Structure of c++ program.
In every programming language there are some
fundamentals you need to know before you can write the
most basic programs.
C++ program mainly consist of 3 parts
1. Preprocessor directives
2. The main() function
3. C++ statements
Header file
It is a source file that contain definitions of library
functions/objects.
Library functions:
Those functions which are predefined in c++ language i.e. built in
functions.
Added into program at the compilation of program.
Only added if function defined in it is used in program.
8. 8
The main function
The main() function indicates the beginning of the program.
The parenthesis following function name is distinguishing feature of
function and must be included
The syntax
void main()
{
Program statements…
}
C++ statements
The statements of the program are written under the main()
function between curly braces
{
…………………statements………………….
}
Every function must use this pair of braces around its body.
Statements are the body of program
Each statement in C++ ends with a semicolon ;.
C++ is a case sensitive language.
9. 9
Program statements & namespace
Statements of program are written under the main function inside curly
brackets.
int main()
{
cout<<“ statement”;
return 0;
}
The first statement tells the compiler to display the quoted phrase.
Second statement returns a 0 value to who ever calls it.
The built in C++ library routines are kept in the standard namespace.
The standard C++ library is defined in this standard namespace.
Output using Cout
cout<<“ this is my first c++ program”;
It causes the phrase in quotation marks to be displayed on
the screen.
It shows the standard output stream.
The ‘<<‘ operator is called insertion or put to operator.
Directs the string constant “this is c++ program” to the cout.
cout sends it to display screen.
The statement in “ this is my c++ program” is a string
constant example.
10. 10
Keywords
The words that are used by the language and carries
special meanings are called keywords.
Keywords are predefined reserved words used in programming.
Keywords are part of the syntax and they cannot be used as an
identifier.
For example: int salary; Here, int is a keyword that indicates
‘salary' is a variable of type integer.
Keywords appear in blue in Visual C++.
Do not use keywords as variable and constant names!!
For e.g.
The word main is used to indicate the starting of program.
include is used to add header files.
int to declare an integer type variable.
C Keywords
As C is a case sensitive language:
all keywords must be written in lowercase. Here is a list of all
keywords allowed in ANSI C.
11. 11
Tokens
A program statement consists of variable names, keywords,
constants, punctuation marks, operators etc.
In C++ these elements are called tokens.
In the following program segment tokens are
main()
{
int, b;
}
Tokens are main, {,}, int, a, b , (,) are tokens
Identifiers
An identifier is a name that is assigned by the user for a program
element such as variable, functions and structures.
Identifier must be unique:
They are created to give unique name to a entity to identify it
during the execution of the program. For example:
int length;
char nmfirst=‘a’;
Note:
Identifier must be different from keywords. Better to have a
meaningful name for the identifier.
12. 12
variables
Variables are fundamental part of any programming language.
A variable is a container (storage area) to hold data.
continued
To indicate the storage area, each variable should be given a unique
name (identifier).
variable names are just the symbolic representation of a memory
location. For example:
Float gpa=3.5; // gpa is a variable of type float and the value assigned is
3.5.
The value of the variable can be changed, as the name suggests
“variable”.
13. 13
Rules for naming a variable name
A variable must be declared before using.
A variable name can have letters (both uppercase and lowercase letters),
digits and underscore only.
The first letter of a variable should be either a letter or an underscore.
Blank spaces are not allowed in a variable name.
Special characters can not be used in variable name.
The maximum length of variable name depends on compiler of c++.
variable name pay and Pay will be considered different.
Constants or literals
Constant is a fixed value that does not change during program
execution.
Constant must have to be initialized at the time of creating it and new
values cannot be assigned later to it.
15. 15
Constant definition by using #define
preprocessor
Data types in c++
C++ has five data types
int integer
Float floating point
Double double precision
Char characters
Bol Boolean.
16. 16
Integer variables
variable that holds the integer data, is known as integer variable.
a number without fractions or decimal point.
E.g. 11, 222, 345 etc.
takes two or four bytes in memory.
Size of integers
A short int is two bytes on most computers.
A long int is usually four bytes.
int can be two or four bytes long for modern compilers.
Determines the Size of Variable Types on Your Computer.
17. 17
Float data type
Float represent real or floating point data.
Float data type can be signed or unsigned.
E.g. 11.09, 34.81, -5.88 .
Storage capacity: 4 bytes
Bool data type
The word bool stands for Boolean.
Used to declare logical type variables.
Only two values can be stored
True or false
True=1
False=0
18. 18
General form of a C++ program
// Program description
#include directives
int main()
{
constant declarations
variable declarations
executable statements
return 0;
}
Example 0 – adding 2 numbers
Peter: Hey Frank, I just learned how to add two numbers
together.
Frank: Cool!
Peter : Give me the first number.
Frank: 2.
Peter : Ok, and give me the second number.
Frank: 5.
Peter : Ok, here's the answer: 2 + 5 = 7.
Frank: Wow! You are amazing!
after Frank says “2”, Peter has to keep this number in his mind.
2 5 7First number: Second number: Sum:
after Frank says “5”, Peter also needs to keep this number in his mind.
19. 19
The Corresponding C++ Program
#include <iostream>
using namespace std;
int main()
{
int first, second, sum;
cout << "Peter: Hey Frank, I just learned how to add”
<< “ two numbers together."<< endl;
cout << "Frank: Cool!" <<endl;
cout << "Peter: Give me the first number."<< endl;
cout << "Frank: ";
cin >> first;
cout << "Peter: Give me the second number."<< endl;
cout << "Frank: ";
cin >> second;
sum = first + second;
cout << "Peter: OK, here is the answer:";
cout << sum << endl;
cout << "Frank: Wow! You are amazing!" << endl;
return 0;
}
#include <iostream>
using namespace std;
int main()
{
int number_of_pods, peas_per_pod, total_peas;
cout << "Press return after entering a number.n";
cout << "Enter the number of pods:n";
cin >> number_of_pods;
cout << "Enter the number of peas in a pod:n";
cin >> peas_per_pod;
total_peas = number_of_pods * peas_per_pod;
Demo Example 1
20. 20
cout << "If you have ";
cout << number_of_pods;
cout << " pea potsn";
cout << "and ";
cout << peas_per_pod;
cout << " pea in each pod, then n";
cout << "you have ";
cout << total_peas;
cout << " peas in all the pods.n";
return 0;
}
Demo Example 1
C++ comments
Comments appear in green in Visual C++.
Comments are explanatory notes; they are ignored by the
compiler.
There are two ways to include comments in a program:
// A double slash marks the start of a
//single line comment.
/* A slash followed by an asterisk marks
the start of a multiple line comment. It
ends with an asterisk followed by a
slash. */
21. 21
Programming Style
C++ is a free-format language, which means
that:
Extra blanks (spaces) or tabs before or after
identifiers/operators are ignored.
Blank lines are ignored by the compiler just like
comments.
Code can be indented in any way.
There can be more than one statement on a
single line.
A single statement can continue over several
lines.
In order to improve the readability of your program, use
the following conventions:
Start the program with a header that tells what the
program does.
Use meaningful variable names.
Document each variable declaration with a comment
telling what the variable is used for.
Place each executable statement on a single line.
A segment of code is a sequence of executable
statements that belong together.
Use blank lines to separate different segments of code.
Document each segment of code with a comment
telling what the segment does.
Programming Style (cont. )
22. 22
What makes a bad program?
Writing Code without detailed analysis and
design
Repeating trial and error without understanding
the problem
Debugging the program line by line, statement
by statement
Writing tricky programs
Continued…
Symbol used for grouping and separating code are known as punctuators
“()” , “{}” “[ ]” : = # comma, semicolon, colon.
The following characters are used as punctuators in C++.
Brackets [ ] opening and closing brackets indicate single and multidimensional
array subscript.
Parentheses ( ) opening and closing brackets indicate functions calls, function
parameters for grouping expressions etc.
Braces { } opening and closing braces indicate the start and end of a compound
statement.
Comma , it is used as a separator in a function argument list.
Semicolon ; it is used as a statement terminator.
Colon : it indicates a labeled statement or conditional operator symbol.
Asterisk * it is used in pointer declaration or as multiplication operator.
Equal sign = it is used as an assignment operator.
Pound sign # it is used as pre-processor directive.
23. 23
Maniupulators
These are operators that are used with insertion operator (<<) to control
format of data.
The endl manipulator stands for end of line. It is predefined iostream
manipulator.
#include<iostream>
int main()
{
cout<<“ I am “<<endl<<“pakistani”;
return 0;
}
Output:
I am // end of line
Pakistani.
manipulators
‘setw’ stands for setwidth. This manipulator is used to set the width of
output on the output device.
Setw() manipulator is a part of “iomanip.h” header file.
Syntax
Setw(n)
Where n specifies the width of output field. It is an integer value.
For e.g. to print “pakistan” in first 10 columns and “islamabad” in next 15
columns, the output statement written as
Cout<<setw(10)<<“pakistan”<<setw(15)<<“islamabad”;
Output would be
24. 24
Setw continued…
Initialization of variables
Assigning known value to a variable at the time of declaration is called
initializing of variable.
When variable is declared, Memory location is assigned.
Value in memory location is also assigned to that variable.
In order to assign variables of type int and assigning known values it
can be written as :
int a=30;
int b=40;
int c ;
c= a+ b;
Cout<<c ;
25. 25
Continued…
A program that assign values to different variables at the time of
declaration and print the assigned values on computer screen.
#include<iostream>
using namespace std;
int main()
{
int xyz=4, b=2000;
double xy=6.9;
cout<<name<<xyz<<xy<<b;
getch();
}
constants
A quantity that can not change its value during the execution of
program is called constant.
Four type of constants
Integer constants
Floating point constants
Character constants
String constants
26. 26
Constant continued..
A numerical value without a decimal part is called integer constant.
Floating point constant:
Numeric values that has an integer as well as a decimal part is called
floating point constant
Character constants:
A single character enclosed in a single quotation mark is called character
constant. For e.g. ‘a’, ‘/’, and ‘+’ represents character constants.
String constants:
A sequence of characters consisting of alphabets, digits and special
characters enclosed in double quotation marks is called string constants.
for e.g. “ I study in bahria university” in “ semester -1”
Operators and types
Operators are special symbols that tells the compiler to perform specific
mathematical or logical functions
C++ divides the operators into following groups:
Arithmetic operators
Comparison/Relational operators
Logical operators
Assignment operators
Bitwise operators