0% found this document useful (0 votes)
13 views62 pages

2-Lecture-FoP-intro To C++

Intro to C++

Uploaded by

bilalasim1020
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)
13 views62 pages

2-Lecture-FoP-intro To C++

Intro to C++

Uploaded by

bilalasim1020
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
You are on page 1/ 62

CS-114 Fundamentals of Programming

Introduction to C++

Dr Ayesha Zeb
Email: [email protected]
Lecture Contents

• Programming languages
• Components of programming languages
• Programming languages rules
• Basic parts of a program
• Software development cycle
• Flowcharts and Pseudocodes
• Errors in Programs
Programming Languages

A programming language is a formal notation for general


problem solving, designed to instruct a machine.
Components of a language

• Syntax
• Semantics
Components of a language
Syntax

• Every spoken language has a general set of rules for


how words and sentences should be structured. These
rules are collectively known as the language syntax.
• Syntax is a part of the grammar of the language.
• In computer programming, syntax serves the same
purpose, defining how each instruction should be written.
• Syntax: Print Hello World!
• Syntax: cout<<“Hello World!”;
Semantics

• In spoken languages semantics is the study of meaning.


• In computer programming semantics describes the
processes a computer follows when executing a program
in that specific language.
• This can be shown by describing the relationship
between the input and output of a program, or an
explanation of how the program will execute on a certain
platform, hence creating a model of computation.
Programming language rules

• Rules of Syntax which specify how valid instructions are


written in the language.
– They deal with the structure of an instruction

• Rules of Semantics which determine the meaning of the


instructions (what the computer will do in response to the
given instructions).
– They deal with the content of an instruction
C++ HelloWorld – A First Program

//EC 100 Algorithms and Computing


//A first program
//Hello World – displays “Hello World!”
//on the screen

#include <iostream>

using namespace std;

int main()
{
cout << "Hello, World!";
return 0;
}
Tokens
• A token is the smallest element of a C++ program that is
meaningful to the compiler.
Token Type Description/Purpose Examples
Keywords Words with special int, double, for, auto
meaning to the compiler
Identifiers Names of things that are cout, std, x, myFunction
not built into the language

Literals Basic constant value “Hello, World!”, 24.3, 0,


whose value is specified ‘c’
directly in the source code

Operators Mathematical or logical +, - ,&&, %, <<


operations
Punctuation/ Punctuation defining the {}(),;
Separators structure of the program

Whitespace Spaces of various sorts; Spaces, tabs, newlines


ignored by the compiler comments
C++ HelloWorld
//EC 100 Algorithms and Computing
//A first program
//Hello World – displays “Hello World!”
//on the screen

// indicates everything following it until that line is a comment.


#include <iostream>
Comments are ignored by the compiler
Comments can also be put between /* and */ Such comments can span
multiplenamespace
using lines std;

int main()
{
cout << "Hello World!";
return 0;
}
C++ HelloWorld
Lines beginning with # are preprocessor commands, they change what code
is actually being compiled.
#include tells the preprocessor to dump in the contents of another file, here
it’s iostream, which defines the procedures for input/output
//EC 100 Algorithms and Computing
//A first program
//Hello World – displays “Hello World!”
//on the screen

#include <iostream>

using namespace std;

int main()
{
cout << "Hello World!";
return 0;
}
C++ HelloWorld
A namespace is generally a prefix that is applied to all the names in a certain
set. Think of them as toolboxes that allow us to use different tools. Formally
we can refer to these toolboxes as “classes” and the “tools” as objects.

The 100
//EC command using
Algorithms and tells the compiler to allow
Computing all names in the “std”
//A first program
namespace
//Hello World to be usable
– displays without
“Hello their prefix
World!”
//on the screen

#include <iostream>

using namespace std;

int main()
{
cout << "Hello World!";
return 0;
}
C++ HelloWorld

//EC 100 Algorithms and Computing


The program using tells the compiler to allow all names in the “std”
command
//A first
namespace
//Hello Worldto– be usable“Hello
displays without their prefix. The iostream file includes three
World!”
names
//on the used
screenfrequently in programs - cout, cin, and endl - which are all
defined in the std namespace. "std" is short for "standard" since these names
are defined in
#include the standard C++ library that comes with the compiler.
<iostream>

using namespace std;

int main()
{
cout << "Hello World!";
return 0;
Without
} the line “using namespace std;” we would have had to write
std::cout<<“Hello World!”;
:: is called the scope resolution operator – it tells the compiler that the scope
of cout is in the namespace std
C++ HelloWorld

int main() { … } defines the code that should execute when the program starts
up. The curly braces represent grouping of multiple commands into a block

//EC 100 Algorithms and Computing


//A first program
//Hello World – displays “Hello World!”
//on the screen

#include <iostream>

using namespace std;

int main()
{
cout << "Hello World!";
return 0;
}
C++ HelloWorld
cout<<“Hello
//EC World!”; tellsand
100 Algorithms the compiler
Computingto perform with cout.
//A first program
return 0; indicates that the program should tell the operating system it has
//Hello World – displays “Hello World!”
finished successfully.
//on the screen

#include <iostream>

using namespace std;

int main()
{
cout << "Hello World!";
return 0;
}
C++ HelloWorld
Every statement ends with a semicolon (;)
//EC 100 Algorithms and Computing
; indicates the end of a line in C++
//A
Do notfirst program
forget the ;
//Hello World – displays “Hello World!”
//on the screen

#include <iostream>

using namespace std;

int main()
{
cout << "Hello World!";
return 0;
}
A basic program

• Programs typically contain the following


elements:
– Descriptive comments (double forward slash // or /* … */)
– Include files
– Declarations: function prototypes and global variables
– Functions including exactly one main function

• The main() function


– Should have it’s type and arguments (if any) declared
– Should return a value of the correct type
– Controls the execution of the program, even if it is not first in the file.
Input / Output Statements

cout << “Hello C++ World”;


• cout is an object in c++, predefined to display the
standard output stream
• << insertion operator
• The output of this program
– Hello C++ World

cin >> var;


• cin is an object in C++, predefined to wait for user input.
This input is stored in the variable ‘var’
• >> extraction operator
C++ HelloWorld – Putting it all together!

//EC 100 Algorithms and


Computing
Descriptive comments
//A first program
//Hello World – displays
“Hello World!”
//on the screen

#include <iostream> Include files

using namespace std;


Telling the compiler to use
the prefix std where required
int main() main() function
{
Standard cout << "Hello,World!";
output stream return 0;
insertion
}
operator
C++ HelloWorld – Putting it all together!
//EC 100 Algorithms and Computing
//A first program
//Hello World – displays “Hello World!”
//on the screen

#include <iostream>

using namespace std;

int main()
{
cout << "Hello, World!";
return 0;
}
Descrip
tive
comme
Include nts
files
Telling the compiler to use
main() the prefix std where required
function
Label the parts

#include <iostream> sum = a + b;


//including libraries //displaying output
using namespace std; //the cout << "The sum is: " <<
using directive sum << endl;
int main() return 0;}
{
int a, b, sum;
cout << "Please enter an
integer value: ";
cin >> a;
cout << "Please enter Second
integer value: ";
cin >> b;
//summing function
Label the parts

#include <iostream> cout << "Please enter


//including libraries Second integer value:
using namespace std; ";
//the using directive cin >> b;
int main() //summing function
{ sum = a + b;
int a, b, sum; //displaying output
cout << "Please enter cout << "The sum is: "
an integer value: "; << sum << endl;
cin >> a; return 0;}
Compilation: How it all came together
Software Development Cycle

• Developing a software to solve a problem is a multi-step


process consisting of at least the following major
elements.
– Program Concept
– Algorithm Development
– Program Coding
– Testing and Debugging
– Program Documentation
– Program Maintenance
Software Development Cycle
Program
Concept

Program Algorithm
Maintenance Development

Program
Coding
Documentation

Testing
and
Debugging
Software Development Cycle

• Only one portion of this process (coding) focuses on the


use of a specific programming language.
• The initial two steps relate to the development of a
problem-solving approach.
• The final two steps ensure proper usage of the
developed software.
Misconception to Students !
• Students often incorrectly assume that once they master
a programming language they can solve almost any
problem.
• This could not be further from the truth.
• In fact, most experienced programmers spend up to 90%
of their time working on the logic of their programs, not
on the coding.
• Therefore, it is crucial that you understand this process
and develop good problem-solving skills before
attempting to write any programs.
Programming process
• Good organization is key to writing
good programs
• Steps to writing a program:
– Step 1. Think! (This is not optional!!)
– Step 2. Organize your thoughts
– Step 3. Write them down in English
– Step 4. Finally translate them into C++
Program Concept
• The first stage of developing a
program and the most crucial,
is to define the problem
carefully.
– If you are successful, remainder
of the process will be greatly
simplified.
– Conversely, if you fail to define
the problem adequately, you will
usually have great difficulties at
later stages.
Algorithm

• Any solvable computing problem can be solved by the


execution of a series of actions in a specific order.
• A procedure for solving a problem in terms of
1. the actions to execute and
2. the order in which these actions execute

is called an algorithm.
Algorithms

• Example algorithm: "Bake sugar cookies"


– Mix the dry ingredients.
– Cream the butter and sugar.
– Beat in the eggs.
– Stir in the dry ingredients.
– Set the oven temperature.
– Set the timer.
– Place the cookies into the oven.
– Allow the cookies to bake.
– Spread frosting and sprinkles onto the cookies.
– ...
Problems with algorithms

• lack of structure: Many tiny steps; tough to


remember.
• redundancy: Consider making a double batch...
– Mix the dry ingredients.
– Cream the butter and sugar.
– Beat in the eggs.
– Stir in the dry ingredients.
– Set the oven temperature.
– Set the timer.
– Place the first batch of cookies into the oven.
– Allow the cookies to bake.
– Set the timer.
– Place the second batch of cookies into the oven.
– Allow the cookies to bake.
– Mix ingredients for frosting.
– ...
Structured algorithms
• structured algorithm: Split into coherent tasks.
1 Make the cookie batter.
– Mix the dry ingredients.
– Cream the butter and sugar.
– Beat in the eggs.
– Stir in the dry ingredients.
2 Bake the cookies.
– Set the oven temperature.
– Set the timer.
– Place the cookies into the oven.
– Allow the cookies to bake.
3 Add frosting and sprinkles.
– Mix the ingredients for the frosting.
– Spread frosting and sprinkles onto the cookies.
...
Structured algorithms

• Sequence Matters!
1 Make the cookie batter.
– Mix the dry ingredients.
– Cream the butter and sugar.
– Beat in the eggs.
– Stir in the dry ingredients.

2 Add frosting and sprinkles.


– Mix the ingredients for the frosting.
– Spread frosting and sprinkles onto the cookies.

3 Bake the cookies.


– Set the oven temperature.
– Set the timer.
– Place the cookies into the oven.
– Allow the cookies to bake.
Developing an Algorithm

• What is an Algorithm?
– The steps to be taken in order to solve a problem form an
algorithm.
– It may also be called designing the solution.
– Hundreds of algorithms for different problems have been
developed and made available for use, such as sorting
algorithms and searching algorithms.
Developing an Algorithm

• Top down approach


– What to do.
• Step wise refinement
– How to do it.
Developing an Algorithm

• Gather Requirements
– Identify inputs and outputs
• Step wise refinement
– State how you can convert the input to the output
– Break the entire process into small steps
– Test each small step before moving on to the next one
Developing an Algorithm

• The 2 most basic and widely use methods of developing


algorithms are:
– Developing a pseudocode
– Developing a flowchart
Pseudocode

• Pseudocodes (or "fake" code) are the English language


equivalents of C++ (or any other programming language)
programs.
• They are written to help programmers develop
algorithms syntax.
• They are convenient and user friendly,
• Pseudocodes do not execute on computers.
• Pseudocodes are not language dependent.
Pseudocode

• Pseudocodes describe executable statements


• They do not normally include variable declarations
• For example, for adding two numbers
1. Prompt the user to enter the first integer
Input the first integer
2. Prompt the user to enter the second integer
Input the second integer
3. Add first integer and second integer, store result
Display result
Pseudocode

• For branching and looping, pseudocodes use four


statement keywords to portray logic:
1. IF, THEN, ELSE, and DO.
2. Repetitive processing logic is portrayed using the statements DO
WHILE (repeat an activity as long as a certain condition exists).
3. DO UNTIL (repeat an activity until a certain condition is met), and
4. END DO (stop repeating the activity).
• The logic statement keywords are capitalized, and
several levels of standard indentation are used.
• The keywords DATA, INPUT and RESULT, OUTPUT
may also be used
Flowcharts

• A program flowchart graphically details the processing


steps of a particular program.
• A program flowchart is a diagram that uses standard
ANSI symbols to show the step-by-step processing
activities and decision logic needed to solve a problem.
• The flow of logic in a program flowchart normally goes
from top to bottom and left to right.
• Arrows are used to show a change from those directions.
Symbols
Make a flowchart for the following:
Find the smallest of 5 numbers input by the user.

Symbol Description
TERMINAL - To start or end a flowchart

INPUT / OUTPUT - Used with Read, Input, Print and other I/O
commands.
PROCESSING - Used for operations done inside the computer.
Such as calculations, storing and moving of data.
DECISION - Used to ask a question in programming. Questions
are Yes/No format (Used with the If Statement).

DIRECTION FLOW - Used to connect symbols and to represent


the direction of flow. Lines should not cross each other.
Arrowheads should be placed at the end close to the symbol.

Connector - or joining of two parts of program


Flowcharts

• A flowchart is used to;


– Clarify the program logic.
– Identify alternate processing methods available.
– Serve as a guide for program coding.
– Serve as documentation.

• The book follows UML (Unified Modeling Language) for


flowcharts.
Flowchart example

Construct a flow chart that adds two numbers


Flowchart example

Variables Algorithm

X: First Number Step 1- Start


Y: Second Step 2- Read X, Y,
Number
S: Sum(X+Y) Step 3- Calculate S = X+Y

Step 4- Print S,
Step 5- Stop
Flowchart example

Start

Read X,Y
Flowchart

S= X+Y

Print S

Stop
Errors in programs

• Computers are not smart


• Water drink do you ?

Syntax Error!!
But you still understood the meaning (no semantic error)
Errors in programs

• Colorless green ideas sleep furiously.

Semantic Error!!
But syntactically correct
Errors in programs

• Syntax errors
• Semantic errors
• Runtime errors
Syntax errors

• Most languages including c++ can only execute a


program if the program is syntactically correct;
otherwise, the process fails and returns an error
message.

• cout<<“Hello World!”
• cout<<Hello World!”;
Semantic Errors

• Semantic error is an error in the content of a code.


• If there is a semantic error in your program, it will run
successfully, i.e. the computer will not generate any error
messages, but it will not do the right thing.
Semantic Errors

• The problem is that the program you wrote is not the


program you wanted to write. The meaning of the
program (its semantics) is wrong.
• Identifying semantic errors can be tricky because it
requires you to work backward by looking at the output
of the program and trying to figure out what it is doing.
Runtime Errors

• The third type of error is a runtime error, so called


because the error does not appear until you run the
program.

• These errors are also called exceptions because they


usually indicate that something exceptional (and bad)
has happened.

• Runtime errors are rare in the simple programs so it


might be a while before you encounter one.
Errors in programs

• Errors in programs are called bugs


• Errors in programs are called bugs
• Finding and fixing errors is called debugging
• More on this in lab

http://www.computerhistory.org/
C++ HelloWorld – A First Program

//EC 100 Algorithms and int main()


Computing {
//A first program cout << "Hello,
//Hello World – World!";
displays “Hello World!” return 0;
//on the screen }

#include <iostream>

using namespace std;


C++ HelloWorld – Input/Output

//EC 100 Algorithms and int main()


Computing {
//Simple Input Output string name;
//Modifying our program cout << "Please enter
your name" << endl;
#include <iostream> cin >> name;
#include <string> cout << "\n Hello
"<<name<<endl;
using namespace std; return 0;
}
C++ HelloWorld – Input/Output
//EC 100 Algorithms and Computing
//Simple Input Output Descriptive
//Modifying our program comments

#include <iostream> Include files


#include <string>

using namespace std;


Telling the compiler to use the
prefix std where required
int main() main() function
{
string name; variable
cout << "Please enter your name“ <<endl;
cin >> name;
cout << "\n Hello "<<name<<endl;
Standard return 0; End line
input
}
extraction
stream operator
Escape Sequences
Escape
Description
sequence Remember
\' single quote
cout << "\n Hello
\" double quote "<<name<<endl;
\? question mark
\\ backslash
\n is an escape
\a audible bell sequence
\b backspace
\f form feed - new page
Escape sequences
\n line feed - new line
\r carriage return
are used to represent
\t horizontal tab special characters etc
\v vertical tab
Acknowledgement/References
• Slides contents taken from Ma’am Fatima Faruq

• Deital and Deital, “C++ How to Program”, Latest Edition

• Stroustrup, “Programming – Principles and Practice


Using C++”, Latest Edition

You might also like