SlideShare a Scribd company logo
1 of 28
Download to read offline
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
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
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
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
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
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
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
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
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
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
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
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
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.
14
Constant definition in C++
Constant definition by using const keyword
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
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
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
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
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
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
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
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
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
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
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
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
27
Arithmetic operators
Relational/Comparison Operator
 Relational operator is an operator that tests or defines some kind
of relation between two entities
28
Logical Operators
Logical operators:
 The logical operators are used to combine one or more relational
expression.

More Related Content

What's hot

What's hot (20)

over all view programming to computer
over all view programming to computer over all view programming to computer
over all view programming to computer
 
Handout#01
Handout#01Handout#01
Handout#01
 
C programme presentation
C programme presentationC programme presentation
C programme presentation
 
C languaGE UNIT-1
C languaGE UNIT-1C languaGE UNIT-1
C languaGE UNIT-1
 
Features of c
Features of cFeatures of c
Features of c
 
C basics
C   basicsC   basics
C basics
 
Turbo C
Turbo CTurbo C
Turbo C
 
The C++ Programming Language
The C++ Programming LanguageThe C++ Programming Language
The C++ Programming Language
 
Chapter 2(1)
Chapter 2(1)Chapter 2(1)
Chapter 2(1)
 
C programming
C programming C programming
C programming
 
introduction to c language
 introduction to c language introduction to c language
introduction to c language
 
Programming in c
Programming in cProgramming in c
Programming in c
 
Chapter 3(1)
Chapter 3(1)Chapter 3(1)
Chapter 3(1)
 
Introduction to c programming
Introduction to c programmingIntroduction to c programming
Introduction to c programming
 
Learning the C Language
Learning the C LanguageLearning the C Language
Learning the C Language
 
PSEUDOCODE TO SOURCE PROGRAMMING LANGUAGE TRANSLATOR
PSEUDOCODE TO SOURCE PROGRAMMING LANGUAGE TRANSLATORPSEUDOCODE TO SOURCE PROGRAMMING LANGUAGE TRANSLATOR
PSEUDOCODE TO SOURCE PROGRAMMING LANGUAGE TRANSLATOR
 
Tokens_C
Tokens_CTokens_C
Tokens_C
 
Introduction to C Programming
Introduction to C ProgrammingIntroduction to C Programming
Introduction to C Programming
 
Compiler
Compiler Compiler
Compiler
 
SULTHAN's - C Programming Language notes
SULTHAN's - C Programming Language notesSULTHAN's - C Programming Language notes
SULTHAN's - C Programming Language notes
 

Similar to Cp week _2.

C programming language tutorial for beginers.pdf
C programming language tutorial for beginers.pdfC programming language tutorial for beginers.pdf
C programming language tutorial for beginers.pdf
ComedyTechnology
 
Introduction To C++ programming and its basic concepts
Introduction To C++ programming and its basic conceptsIntroduction To C++ programming and its basic concepts
Introduction To C++ programming and its basic concepts
ssuserf86fba
 

Similar to Cp week _2. (20)

C Programming UNIT 1.pptx
C Programming  UNIT 1.pptxC Programming  UNIT 1.pptx
C Programming UNIT 1.pptx
 
unit 1 programming in c ztgdawte efhgfhj ewnfbshyufh fsfyshu
unit 1 programming in c ztgdawte efhgfhj ewnfbshyufh fsfyshuunit 1 programming in c ztgdawte efhgfhj ewnfbshyufh fsfyshu
unit 1 programming in c ztgdawte efhgfhj ewnfbshyufh fsfyshu
 
C programming language tutorial for beginers.pdf
C programming language tutorial for beginers.pdfC programming language tutorial for beginers.pdf
C programming language tutorial for beginers.pdf
 
Lecture 1
Lecture 1Lecture 1
Lecture 1
 
C++ programming language basic to advance level
C++ programming language basic to advance levelC++ programming language basic to advance level
C++ programming language basic to advance level
 
C programming notes BATRACOMPUTER CENTRE IN Ambala CANTT
C programming notes BATRACOMPUTER CENTRE IN Ambala CANTTC programming notes BATRACOMPUTER CENTRE IN Ambala CANTT
C programming notes BATRACOMPUTER CENTRE IN Ambala CANTT
 
C Programming Unit-1
C Programming Unit-1C Programming Unit-1
C Programming Unit-1
 
Unit-2_Getting Started With ‘C’ Language (3).pptx
Unit-2_Getting Started With ‘C’ Language (3).pptxUnit-2_Getting Started With ‘C’ Language (3).pptx
Unit-2_Getting Started With ‘C’ Language (3).pptx
 
Basics Of C++.pptx
Basics Of C++.pptxBasics Of C++.pptx
Basics Of C++.pptx
 
INTRODUCTION TO C PROGRAMMING MATERIAL.pdf
INTRODUCTION TO C PROGRAMMING MATERIAL.pdfINTRODUCTION TO C PROGRAMMING MATERIAL.pdf
INTRODUCTION TO C PROGRAMMING MATERIAL.pdf
 
Bcsl 031 solve assignment
Bcsl 031 solve assignmentBcsl 031 solve assignment
Bcsl 031 solve assignment
 
1. introduction to computer
1. introduction to computer1. introduction to computer
1. introduction to computer
 
Introduction To C++ programming and its basic concepts
Introduction To C++ programming and its basic conceptsIntroduction To C++ programming and its basic concepts
Introduction To C++ programming and its basic concepts
 
Unit-2.pptx
Unit-2.pptxUnit-2.pptx
Unit-2.pptx
 
Tutorial basic of c ++lesson 1 eng ver
Tutorial basic of c ++lesson 1 eng verTutorial basic of c ++lesson 1 eng ver
Tutorial basic of c ++lesson 1 eng ver
 
Lect '1'
Lect '1'Lect '1'
Lect '1'
 
C Theory
C TheoryC Theory
C Theory
 
IIM.Com-FIT-Unit2(14.9.2021 TO 30.9.2021).pptx
IIM.Com-FIT-Unit2(14.9.2021 TO 30.9.2021).pptxIIM.Com-FIT-Unit2(14.9.2021 TO 30.9.2021).pptx
IIM.Com-FIT-Unit2(14.9.2021 TO 30.9.2021).pptx
 
Prog1-L1.pdf
Prog1-L1.pdfProg1-L1.pdf
Prog1-L1.pdf
 
490450755-Chapter-2.ppt
490450755-Chapter-2.ppt490450755-Chapter-2.ppt
490450755-Chapter-2.ppt
 

Recently uploaded

TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
mohitmore19
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
VictorSzoltysek
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 

Recently uploaded (20)

Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 

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.
  • 14. 14 Constant definition in C++ Constant definition by using const keyword
  • 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
  • 27. 27 Arithmetic operators Relational/Comparison Operator  Relational operator is an operator that tests or defines some kind of relation between two entities
  • 28. 28 Logical Operators Logical operators:  The logical operators are used to combine one or more relational expression.