0% found this document useful (0 votes)
42 views

Introduction To Computer Programming: Jehangir Arshad Meo

This document provides an introduction to computer programming using C++. It discusses the main components of a C++ program including low-level and high-level programming languages, compilers, libraries, functions, and the typical structure of a C++ program. Low-level languages like machine code and assembly are directly understood by computers while high-level languages like C++ use syntax closer to human languages. C++ programs are compiled from source code to machine code using a compiler then executed by the CPU. Standard libraries provide commonly used functions to simplify programming.

Uploaded by

Alpha Romeo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
42 views

Introduction To Computer Programming: Jehangir Arshad Meo

This document provides an introduction to computer programming using C++. It discusses the main components of a C++ program including low-level and high-level programming languages, compilers, libraries, functions, and the typical structure of a C++ program. Low-level languages like machine code and assembly are directly understood by computers while high-level languages like C++ use syntax closer to human languages. C++ programs are compiled from source code to machine code using a compiler then executed by the CPU. Standard libraries provide commonly used functions to simplify programming.

Uploaded by

Alpha Romeo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 47

Introduction to Computer

Programming

Jehangir Arshad Meo

COMSATS Institute of Information Technology, Sahiwal

1
Programming Languages:
A computer program is written in a specific
manner and according to a set of rules, these
rules are called programming Language.

 There are two main categories of


programming languages:
1- Low Level Languages
2- High Level Languages

2
Low Level Languages:
 The Languages which are easily understandable for the
machine (computer) are called Low level languages.

 There are two types of Low level languages:

1- Machine Language: Computer works only in the form of 0’s


and 1’s. The arrangement of 0’s and 1’s is called binary code.
Machine languages are written in the form of 0’s and 1’s.

2- Assembly Language: It is easier to understand because


machine instructions are represented in the form of English
words. These words are called mnemonics. Assembler is used
to convert assembly language to machine language.

3
High Level Languages:
 These languages are closer to human beings because
these are easily understandable by human user.

 Instructions in these languages are just like human


languages.

 BASIC, FORTRON, COBOL, PASCAL, C++ and C Language


are the basic examples of High level languages.

 Every high level language has its own set of rules for
writing a program, these set of rules are called syntax of
the language.

4
Advantages and Disadvantages of
Low Level Languages:
 Easily understandable by the computer.

 Hard to understand for human user.

 Every computer has its own low level


language, it cannot run on the other machine.

 Intel’s processors programs cannot run on


Motorola's processor.

5
Advantages and Disadvantages of
high Level Languages:
 Machine independent, can run on other devices or
software, before implementing it on the device for
which it was written.

 Welldefined structure so easily understandable by


the human user.

 Just like English because English words are used in


it.
 Easy to debug(finding errors and correct them).

 Memory issues.

6
Why C ++?
 C++ is a language designed by and for programmers

 It is the language of choice for professional programmers worldwide

 Once mastered, C++ will give you complete control over the
computer

 C++ is the one of the most powerful programming language ever


invented!!!

 High Level language so proper syntax, proper functions, easy to


understand and learn.

 Programs can be easily altered so it is commonly used.

7
Compiler

The program that translates the c++ language code to


the machine language code is called compiler.

C++
C++Program
Program C++
C++ Compiler
Compiler Machine
Machine
Language
(e.g.
(e.g. g++)
g++) Language
Program
Program
int
int main()
main() {{
int
int i=1;
i=1;
.. .. .. 01001001
01001001
10010100
10010100

Created with text editor or


development environment
8
C++ Standard Library/Functions
 C++ programs consist of pieces/modules called functions

A programmer can create his own functions

 Advantage: the programmer knows exactly how it works


 Disadvantage: time consuming (if it exists already)

Programmers will often use the C++ library functions

 Use these as building blocks

Avoid re-inventing the wheel

 If a pre-made function exists, generally best to use it rather than write your own
 Library functions carefully written, efficient, and portable

9
Phases of C++ Programs:
Program is created in
Editor hard disk the editor and stored
1. Edit on hard disk.

Preprocessor hard disk Preprocessor program


processes the code.
2. Preprocess Compiler creates
Compiler hard disk Machine code and stores

3. Compile it on hard disk.


Linker links the object
Linker hard disk code with the libraries,

4. Link Primary
creates a.out and
stores it on hard disk
Memory
Loader
5. Load Loader puts program
in main memory for CPU.
6. Execute hard disk ..
..
..

Primary
Memory
CPU
  CPU takes each
instruction and
executes it, possibly
storing new data
..
.. values as the program
..
executes.

10
C Preprocessor:
 C++ Compilers automatically invoke a
preprocessor that takes care of #include
statements and some other special directives.

 Programmer don't need to do anything


special to run the preprocessor - it happens
automatically.

11
Structure of C++ program:
 Preprocessor Directives
 Header files
 Comments
 Main () function of the program
 Delimiters
 Statement terminator
 Variables (declaration, initialization)
 Input/ output statements
 Expressions
 Etc…

12
Structure of C++ program:
Preprocessor directives
Processed by preprocessor before compiling
Begin with #
# include
# define

Header Files

It is the part of compiler and have the definitions of standard library functions

There are several header files each have function of one type: such as math.h
contains header files containing definitions of mathematical functions.

Each header file has extension (.h). The name of the file is written in angle brackets(<
>).

#include <math.h>
#Include is used to add header file to the program.
#define Identifier Constant value
It is used to assign a constant value to an identifier :a, b or any variable

13
Structure of C++ program(contd..)
Example:

#define square(a) (a * a)

y = square(x);
becomes y = (x * x);
z = square(y*x);

becomes z = (y*x * y*x);

14
Structure of C++ program(contd..):
 Comments:

Document programs
Improve program readability
Ignored by compiler

Single-line comment:

Begin with //

Multiple-line comment:

Everything between /* and */ is ignored.

15
Structure of C++ program(contd..)
main() Function:
 It indicates the start of the C++ language program.
 It must be include in every C++ program.
 We can say it is the entering point to the program.

Delimiters:
 Symbols that are used to specify the limits of the C++ language program.
 Curly brackets are used to start( { ) and Terminate ( } ) the body of the
program.
statement terminators:
 Statement that is used to terminate the statement of a C++
Language program is called statement terminator.
 ( ; ) semicolon is used to terminate the statements.

16
Structure of C++ program(contd..):
Escape Sequences:

Character combinations consisting of a backslash (\) followed by a letter or by a combination of digits are called "escape sequences." To
represent a newline character, single quotation mark, or certain other characters in a character constant, we must use escape sequences .

Escape Sequence Description

\n Newline. Position the screen cursor to the


beginning of the next line.
\t Horizontal tab. Move the screen cursor to the next
tab stop.
\r Carriage return. Position the screen cursor to the
beginning of the current line; do not advance to the
next line.
\a Alert. Sound the system bell.
\\ Backslash. Used to print a backslash character.
\" Double quote. Used to print a double quote
character.

17
1 // code1.cpp
2 // A first program in C++. Single-line comments.
3 #include <iostream> Function main returns an
4 integer { begins Preprocessor
value.
Left brace function directive to
5 // function main begins program execution include input/output
Statements stream
end with a
body. Function main appears
6 int main() header filesemicolon
<iostream>.
exactly once in every C++ ;.
7 {
program..
8 cout << "Welcome to C++!\n";
9 Corresponding right brace }
10 return 0; // indicateends
that program
functionended
body.successfully
11 Stream insertion operator.
12 } // end function main
Keyword return is one of
Welcome to C++!
several means to exit
function; value 0 indicates
program terminated
successfully.

18
1 // code3.cpp
2 // Printing multiple lines with a single statement
3 #include <iostream>
4
5 // function main begins program execution Using newline characters to
6 int main() print on multiple lines.
7 {
8 std::cout << "Welcome\nto\n\nC++!\n";
9
10 return 0; // indicate that program ended successfully
11
12 } // end function main

Welcome
to
 
C++!

19
Structure of C++ program(contd..):

 Input/output

◦ Cin

 Standard input stream


 Normally keyboard
◦ Cout

 Standard output stream


 Normally computer screen

20
A Simple Program: Printing a Line of Text
 Standard output stream object
◦ std::cout
◦ “Connected” to screen
◦ <<
 Stream insertion operator
 Value to right (right operand) inserted into output stream
 Namespace
◦ std:: specifies using name that belongs to “namespace”
std
◦ std:: removed through use of using statements
using namespace std;
 Escape characters
◦ \
◦ Indicates “special” character output

21
1 // code2.cpp
2 // Printing a line with multiple statements.
3 #include <iostream>
4
5 // function main begins program execution
Multiple stream insertion
6 int main()
statements produce one line of
7 {
output.
8 std::cout << "Welcome ";
9 std::cout << "to C++!\n";
10
11 return 0; // indicate that program ended successfully
12
13 } // end function main

Welcome to C++!

22
Another Simple Program:
Adding Two Integers
 Input stream object
◦ >> (stream extraction operator)
 Used with std::cin
 Waits for user to input value, then press Enter (Return)
key
 Stores value in variable to right of operator
 Converts value to variable data type
 = (assignment operator)
◦ Assigns value to variable
◦ Binary operator (two operands)
◦ Example:
sum = variable1 + variable2;

23
Variables

◦ Location in memory where value can be stored

◦ Common data types


 int (whole numbers)- integer numbers(long(4 b), short(2 b), double(4 b))
 Char (character, digits) – characters(1 b)
 flot - floating point numbers

◦ Declare variables with name and data type before use


int integer1;
int integer2;
int sum;

◦ Can declare several variables of same type in one declaration


 Comma-separated list

int integer1, integer2, sum;

24
1 // code4.cpp
2 // Addition program.
3 #include <iostream>
4 // function main begins program execution
6 int main()
7 { Declare integer variables.
8 int integer1; // first number to be input by user
9 int integer2; // second number to be input by user
10 int sum; // variable in which sum will Use
be stored
stream extraction
11 operator with standard input
12 std::cout << "Enter first integer\n"; // prompt
stream to obtain user input.
13 std::cin >> integer1; // read an integer
14
Calculations can be performed in output statements: alternative for
15 std::cout << "Enter second integer\n"; // prompt
lines 18 and 20:
16 std::cin >> integer2; // read an integer
17
std::cout << "Sum is " << integer1 + integer2 << std::endl;
18 sum = integer1 + integer2; // assign result to sum Stream manipulator
19 std::endl outputs a
20 std::cout << "Sum is " << sum << std::endl; // print sum newline, then “flushes output
21 return 0; // indicate that program ended successfully buffer.”
23 } // end function main

Concatenating, chaining or
cascading stream insertion
operations.

25
For output:
 cout << "Hello"; // prints Hello
 cout << Hello; // prints the content of Hello variable

 The insertion operator (<<) may be used more than once in a single statement:

 cout << "Hello, " << "I am " << "a C++ statement";

 This last statement would print the message Hello, I am a C++ statement on the screen.

 The utility of repeating the insertion operator (<<) is demonstrated when we want to
print out a combination of variables and constants or more than one variable:

 cout << "Hello, I am " << age << " years old and my zipcode is " << zipcode;

If we assume the age variable to contain the value 24 and the zipcode variable to


contain 90064 the output of the previous statement would be: 

 Hello, I am 24 years old and my zipcode is 90064

26
For Input:
 The standard input device is usually the keyboard. Handling the standard
input in C++ is done by applying the overloaded operator of extraction (>>)
on the cin stream. The operator must be followed by the variable that will
store the data that is going to be extracted from the stream.

 int age;
 cin >> age;

 You can also use cin to request more than one datum input from the user: 

 cin >> a >> b; is equivalent to:


 cin >> a;
 cin >> b;

27
IMPORTANT LINK:

http://www.cplusplus.com/doc/tutorial/basic_io/

28
Memory Concepts
 Variable names:

◦ Correspond to actual locations in computer's memory

◦ Every variable has name, type, size and value

◦ When new value placed into variable, overwrites previous


value
◦ Name of variable must be:

 Series of characters (letters, digits, underscores)


 Cannot begin with digit
 Case sensitive
29
Memory Concepts
scanf(“%d”,&integer1); integer1 45
◦ Assume user entered 45

scanf(“%d”,&integer2); integer1 45

◦ Assume user entered 72 integer2 72

integer1 45
sum = integer1 + integer2; integer2 72
sum 117

30
Arithmetic
 Arithmetic calculations
◦ *
 Multiplication
◦ /
 Division
 Integer division truncates remainder
 7 / 5 evaluates to 1
◦ %
 Modulus operator returns remainder
 7 % 5 evaluates to 2

31
Arithmetic
 Rules of operator precedence
◦ Operators in parentheses evaluated first
 Nested/embedded parentheses
 Operators in innermost pair first
◦ Multiplication, division, modulus applied next
 Operators applied from left to right
◦ Addition, subtraction applied last
 Operators applied from left to right
Operator(s) Operation(s) Order of evaluation (precedence)

() Parentheses Evaluated first. If the parentheses are nested, the


expression in the innermost pair is evaluated first. If
there are several pairs of parentheses “on the same level”
(i.e., not nested), they are evaluated left to right.
*, /, or % Multiplication Division Evaluated second. If there are several, they re
Modulus evaluated left to right.
+ or - Addition Evaluated last. If there are several, they are
Subtraction evaluated left to right. 32
Decision Making: Equality and
Relational Operators
 if structure
◦ Make decision based on truth or falsity of condition
 If condition met, body executed
 Else, body not executed
 Equality and relational operators
◦ Equality operators
 Same level of precedence
◦ Relational operators
 Same level of precedence
◦ Associate left to right

33
Decision Making: Equality and
Relational Operators

34
Confusing Equality (==) and
Assignment (=) Operators
 Common error

◦ Does not typically cause syntax errors

 Aspects of problem

◦ Expressions that have a value can be used for decision


 Zero = false, nonzero = true
◦ Assignment statements produce a value (the value to
be assigned)

35
Confusing Equality (==) and
Assignment (=) Operators
 Example
if ( payCode == 4 )
printf("You get a bonus!“);
◦ If paycode is 4, bonus given

 If == was replaced with =


if ( payCode = 4 )
printf("You get a bonus!");
◦ Paycode set to 4 (no matter what it was before)
◦ Statement is true (since 4 is non-zero)
◦ Bonus given in every case

36
C Data Types

Simple address Structured

Integral enum Floating pointer array


reference struct
char float union
short signed double class
int unsigned long double
long
bool

37
Integral Types
 char, short, int, long
 Different sizes of integers - different memory size
 Dependent upon the compiler
 Integer values: Sequence of one or more digits
22 129 -67 0
 commas are not allowed: 100,000

38
Type Name Bytes Other Names Range of Values
int 4 signed –2,147,483,648 to 2,147,483,647

unsigned int 4 unsigned 0 to 4,294,967,295

bool 1 none false or true

char 1 none –128 to 127

signed char 1 none –128 to 127

unsigned char 1 none 0 to 255

short 2 short int, signed short int –32,768 to 32,767

unsigned short 2 unsigned short int 0 to 65,535

long 4 long int, signed long int –2,147,483,648 to 2,147,483,647

unsigned long 4 unsigned long int 0 to 4,294,967,295

long long 8 none –9,223,372,036,854,775,808 to


9,223,372,036,854,775,807

unsigned long long 8 none 0 to 18,446,744,073,709,551,615

enum varies none

float 4 none 3.4E +/- 38

double 8 none 1.7E +/- 308

long double same as double none same as double


39
Expressions
 C expressions are used to express computation.

 Expressions is combination of operations and the


operands on which the operations are applied.

 Operands can be variables, literals or constants.

40
Precedence
 Precedence controls the order of evaluation of
operators.

◦ A high precedence means an operator is evaluated


(applied) before any lower precedence operators.

 Operators that have the same precedence can


happen in either order, but in C the one on the left
is evaluated first.

41
Precedence
Operators Precedence
() highest (applied first)
* / %
+ -
< <= > >=
== !=
= lowest (applied last)

42
const
 You can add the const modifier to the declaration
of a variable to tell the compiler that the value
cannot be changed:

const double factor = 5.0/9.0;


const double offset = 32.0;
celcius = (fahr - offset)*factor;

43
What if you try to change a const?
 The compiler will complain if your code tries to
modify a const variable:

const int temp = 100;



temp = 21;

Error: l-value specifies const object

44
Why use const?
 Const tells the compiler that a variable should
never be changed.
 You already know the variable should never be

changed!

 But - let the compiler save you from yourself (you


might forget that it shouldn't be changed).

45
Integer vs. floating point math
 How does C know whether to use floating
point or integer math operators?

 If either operand is floating point, a


floating point operation is done (the result
is a floating point value).

 If both operand are integer the result is an


integer (even division).

46
Literals (fixed values)
 Literals are fixed values used by a program.
 Some examples of literals:
22 3.14159
false "Hi Kurt" 'c'
 You can initialize a variable in the declaration by
assigning it a value:
int temp = 17;
double PI = 3.14159;
char alpha = ‘a';

47

You might also like