Week 2 Introduction To Programming Language in C++

You might also like

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 43

Introduction to

Programming Language
Prepared By Dalton Ndirangu
Common Concepts of Programming
Language
 Character set:

 Letters

 Digits

 Special characters

 White space (blank line, space characters and tab characters)

 Keyword: words reserved for any language

 Identifiers: a series of characters consisting of letters, digits and underscores. Identifiers cannot begin with a digit and cannot contain spaces. Thus identifiers begins with either a letter, underscore,
or dollar sign.

 Constants: an identifier whose value cannot change

 Integer constants is a sequence of digits

 Real constants consists of fractional part in their representation

 Single character constant represent a single character which is enclosed in single quotes

 A String constants is a set of characters enclosed in double quotation marks

 A variable: an identifier whose value can change. It is a memory place holder-ie a memory location used to store a data value.

 Variables must always begin with a letter

 White space is not allowed

 Should not be a keyword

 Should not contain special character


Cont..

 Mathematical Operators
 + used for addition or unary plus
 - Used for subtraction or unary minus
 * used for multiplication
 / used for division
 % used for modulus operator (reminder after division)
 Relational Operator
 < Less than
 > greater than
 <= less or equal to
 >= greater than or equal to
 == is equal to (equivalent)
 != for c language
Cont..

 Assignment Operator

 = equal sign is used as assignment operator. The assignment is usually done from right to left. The general format is variable = expression

 Basic Data Types

 A program usually contains different types of data types

 Types of Data types can be classified as Primary data type and Secondary data types

 Primary Data type

 Character

 Integer (Integral) (whole numbers ie a number without decimal part)

  

 Float (fractional real numbers with single precision )

 Double (fractural real numbers with double precision)

 Boolean for logic true or false

 Secondary Data Type

 Array

 Pointer

 Structure

 Union

 Enum etc
Introduction to Programming in C++

Some Remarks about Programming


Programming is a core activity in the process of performing tasks or solving
problems with the aid of a computer.
There are many different programming languages, and many ways to classify them.
For example, "high-level" programming languages are languages whose syntax is
relatively close to natural language, whereas the syntax of "low-level" languages
includes many technical references to the nuts and bolts (0's and 1's, etc.) of the
computer. "Declarative" languages (as opposed to "imperative" or "procedural"
languages) enable the programmer to minimise his or her account of how the
computer is to solve a problem or produce a particular output. "Object-oriented
languages" reflect a particular way of thinking about problems and tasks in terms of
identifying and describing the behaviour of the relevant "objects". Smalltalk is an
example of a pure object-oriented language. C++ includes facilities for object-
oriented programming, as well as for more conventional procedural programming.
The Origins of C++

 C++ was developed by Bjarne Stroustrup of AT&T Bell Laboratories in the


early 1980's, and is based on the C language. The name is a pun - "++" is a
syntactic construct used in C (to increment a variable), and C++ is intended as
an incremental improvement of C. Most of C is a subset of C++, so that most C
programs can be compiled (i.e. converted into a series of low-level
instructions that the computer can execute directly) using a C++ compiler.
 C is in many ways hard to categorise. Compared to assembly language it is
high-level, but it nevertheless includes many low-level facilities to directly
manipulate the computer's memory. It is therefore an excellent language for
writing efficient "systems" programs. But for other types of programs, C code
can be hard to understand, and C programs can therefore be particularly
prone to certain types of error. The extra object-oriented facilities in C++ are
partly included to overcome these shortcomings.
ANSI C++

 The American National Standards Institution (ANSI) provides "official" and


generally accepted standard definitions of many programming languages,
including C and C++. Such standards are important. A program written only in
ANSI C++ is guaranteed to run on any computer whose supporting software
conforms to the ANSI standard. In other words, the standard guarantees that
ANSI C++ programs are portable. In practice most versions of C++ include ANSI
C++ as a core language, but also include extra machine-dependent features to
allow smooth interaction with different computers' operating systems. These
machine dependent features should be used sparingly. Moreover, when parts
of a C++ program use non-ANSI components of the language, these should be
clearly marked, and as far a possible separated from the rest of the program,
so as to make modification of the program for different machines and
operating systems as easy as possible.
The C++ Programming Environment

 The best way to learn a programming language is to try writing programs and
test them on a computer! To do this, we need several pieces of software:
 An editor with which to write and modify the C++ program components or
source code,
 A compiler with which to convert the source code into machine instructions
which can be executed by the computer directly,
 A linking program with which to link the compiled program components with
each other and with a selection of routines from existing libraries of
computer code, in order to form the complete machine-executable object
program,
 A debugger to help diagnose problems, either in compiling programs in the
first place, or if the object program runs but gives unintended results.
Cont..
The basic structure of the C++ program is:

#include<iostream>
Using namespace std;
int main()
{
First statement;
...
...
Last statement;

return 0;
}
Explanation

 All C++ programs have this basic "top-level" structure. Notice that each statement
in the body of the program ends with a semicolon. In a well-designed large
program, many of these statements will include references or calls to sub-
programs, listed after the main program or in a separate file. These sub-programs
have roughly the same outline structure as the program here, but there is always
exactly one such structure called main. Again, you will learn more about sub-
programs later in the course.
 When at the end of the main program, the line
 return 0;
 means "return the value 0 to the computer's operating system to signal that the
program has completed successfully". More generally, return statements signal
that the particular sub-program has finished, and return a value, along with the
flow of control, to the program level above.
 system(“pause”) allows the computer to pause before returning to the editor
#include <iostream>

 This statement is called an include directive. It tells the compiler and the
linker that the program will need to be linked to a library of routines that
handle input from the keyboard and output to the screen (specifically the cin
and cout statements that appear later). The header file "iostream" contains
basic information about this library. After the include directive is the line:
using namespace std;

 This statement is called a using directive. The latest versions of the C++
standard divide names (e.g. cin and cout) into subcollections of names called
namespaces. This particular using directive says the program will be using
names that have a meaning defined for them in the std namespace (in this
case the iostream header defines meanings for cout and cin in the std
namespace)
Double forward slush // and semi
colon ;
 // is used for commenting. Any statement within the // will considered as
just a comment and the program will not attempt to evaluate it. Ie it will
be ignored and no syntax nor semantics will be checked. Comments
improve readability of a program.
 All C++ statements must be terminated with a semi colon; a statement is any
line of code that the system must carry out some action. This is different
from a line of code that is meant for comment that improves the readability
C++ command statement for Input and
Output
 The objects cin and cout (pre-defined in the strean file) are for the input and
output of data of various type.
 The general format for reading data from the keyboard is:
 cin>>variable1>>variable2>>….>>variable
 Variable1, variable2, … are valid C++ variable names that should be declared
already before using them.
 The stream extraction operator >> reads the data character by character and
assigns it to the indicated location. The reading for the variable will be
terminated at the encounter of a white space or a character that does not match
the destination type.
 The general form for displaying data on the screen is:
 cout<<item1<<item2<<…itemN
 The item1 through itemN may be variables or constants of any basic type.
Cont..

{ } curly brackets are used to define a block of related statements. The left brace {marks the
beginning of a block and the right brace} marks the end of a block.
Thus all functions must be defined with { }
Control building control structure (blocks) can also be defined the scope using the { }
Example 1: Displaying message on screen

#include<iostream>
using namespace std;
int main()
{
cout<<"Welcome to Programming in C++. I hope the training will be exciting";
 
system("pause");
 
return 0;
}
 
C++ Variables, Types and Expressions
 Identifiers

 As we have seen, C++ programs can be written using many English words. It is useful to think of words found in a program as being one of three types:

 Reserved Words. These are words such as if, int and else, which have a predefined meaning that cannot be changed. Here's a more complete list:

 asm continue float new signed try

  

 auto default for operator sizeof typedef

  

 break delete friend private static union

  

 case do goto protected struct unsigned

 catch double if public switch virtual

  

 char else inline register template void

  

 class enum int return this volatile

  

 const extern long short throw while

  

 using namespace bool static_cast const_cast

 dynamic_cast true false


Cont..

 Library Identifiers. These words are supplied default meanings by the


programming environment, and should only have their meanings changed if
the programmer has strong reasons for doing so. Examples are cin, cout and
sqrt (square root).
 Programmer-supplied Identifiers. These words are "created" by the
programmer, and are typically variable names, functions, arrays, classes etc.
 An identifier cannot be any sequence of symbols. A valid identifier must start
with a letter of the alphabet or an underscore ("_") and must consist only of
letters, digits, and underscores.
C++ Basic Data Types

 int are used to define data of type integer


 float are used to define data of type decimal number with single precision
( 8 decimal places)
 double are used to define data type of decimal numbers with double
precision (16 decimal points)
 string are used to define data of type character. Character constants of type
must be enclosed in double quotation marks when used in a program .
 boolean is used to define data of type logic ie true or false.
Declarations, Constants

 Variables have to be declared before they can be used in a program. Declaration means
assigning data type to a variable. In C/C++ declaration is performed as follows
Datatype variablename;
Eg
int x will declare x to be type integer. Thus x will handle data of type integer

double y, z will declare both y and z to be of type double. Thus y and z will handle data of
type double (real numbers with high precision)

string name will declare name to be of type string. Thus name will handle data of type
character literal strings
boolean paid will declare paid to be of type Boolean. Thus paid will handle data of type logic is
paid or not paid
Cont..

 It is possible to initialize variables with a particular value at the same time


as declaring them. eg
double PI = 3.14
 Furthermore, we can specify that a variable's value cannot be altered during
the execution of a program with the reserved word "const":
const double PI=3.14
 const identifier can be placed before or immediately after the data type
identifier. Eg
double const PI=3.14 or const double PI=3.14
Assignments and Expressions

In general, assignment statements have a value equal to the value of the left hand side after the assignment.
= sign is used as assignment operator
Assignment is always done from right to left
Eg
A=5;
Is interpreted as 5 is assigned to a variable A
An expression is a combination of operators, constants and variable arranged as per the rules of the languages. It may include
function calls which return values. An expression may consist of an algebraic expression that produces a value. For example:
A=C+B;
A=5*7+C*B;
A=A+B;
 
Where to put Constant and Variable Declarations
Generally speaking, it is considered good practice to put constant declarations before the "main" program heading, and variable
declarations afterwards, in the body of "main".
Cont..
Cont..
Cont..
Blocks and Scoping

 We have already seen how compound statements in C++ are delimited by "{}"
braces. These braces have a special effect on variable declarations. A
compound statement that contains one or more variable declarations is called
a block, and the variables declared within the block have the block as their
scope. In other words, the variables are "created" each time the program
enters the block, and "destroyed" upon exit. If the same identifier has been
used both for a variable inside and a variable outside the block, the variables
are unrelated. While in the block, the program will assume by default that
the identifier refers to the inner variable - it only looks outside the block for
the variable if it can't find a variable declaration inside.
Algorithms
Pseudocode
Example 2:adding two numbers
Example 2: Adding two Numbers

//Program for adding two numbers

#include<iostream>

using namespace std;

int main()

int a, b, sum;

cout<<"Enter first number";

cin>>a;

cout<<"Enter second number";

cin>>b;

sum=a+b;

cout<<"The result is "<<sum;

system("pause");

return 0;

}
Example 3: Computing Netpay

 Algorithm:Computing NetPay

1. Request/Prompt for gross pay

2. Input gross pay

3. Request /Prompt for taxrate

4. Input taxrate

5. Calculate tax =grosspay* taxrate

6. Calculate netpay=grosspay-tax

7. Display/Print netpay and taxpayable


Cont..

#include<iostream>
using namespace std;
int main()
{
float grosspay, taxrate, tax, netpay;
cout<<"Enter gross pay ";
cin>>grosspay;

cout<<"Enter taxrate ";


cin>>taxrate;

tax=grosspay*taxrate;

netpay=grosspay-tax;

cout<<" The net payment is "<<netpay;


cout<<" The tax payable is "<<tax;
system("pause");
return 0;
}
Escape Sequence
Example 4:Testing \n escape sequence

#include<iostream>
using namespace std;
int main()
{
cout<<"Programming in \nC++ is \nvery exciting.”;
system("pause");
return 0;
}
Arithmetic Operators
Precedence of arithmetic operators
Cont..
Cont..
Exercises
Cont..

You might also like