Computer Programming: SECT-M1082

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 37

Computer Programming

SECT-M1082
Chapter 2
C++ Basics
SECT-M1082
Variables
• Programs manipulate data such as numbers and letters.
• C++ and other programming languages use variable to
name and store data.
• Variables are at the heart of any programming languages.
• The number or other type of data held by the variable is
called value.
• In programming languages, variables are implemented as
Memory locations.
• The complier will assign a memory location to each
variable name in the program.
• The value of the variable is kept in the memory location
assigned to that variable.

3
Identifiers
• The name of the variable is called an identifiers.
• An identifiers must start with a letter or an underscore _ and
all the rest of the characteristics must be letters, digits or the
underscore symbol.
• C++ is a case-sensitive language
• It distinguishes between upper and lower case letters in an
identifier.
• For Example:
Rate RATE rate
This are three distinct variable but it is not advised to use
such identifiers as they might be confusing.

4
Rules for writing an Identifier
1. The first letter should be either be a letter or
underscore
2. Identifiers shouldn’t be keywords
 Keywords or Reserved words are words that have
predefined meaning in C++, which means they’re defined in
the libraries.
Example: cin , cout, int, include

3. To make your program easy to understand, you should


always use meaningful names for variables.
Example:
If you are declaring a variable to hold an age of a person it is
better if you name it age than naming it x or ag.

5
6
Variable Declarations
• When you declare a variable you are telling the complier and ultimately the computer what kind
of data you will be storing in the variable.
Example:
int number_of_bars;
double one_weight , total_weight;
• The word int is abbreviation for integer. This line declares that the identifier number_of_bars to
be a variable of type int.
• The word double declares the two identifiers one_weight and total_weight to be varibles of type
double.
• When there is more than one declarations they are separated by comma.
• Note that each declarations end with a semicolon.
Example:
int number_of_bars, total_quantity, days_left;
• NOTE: All variables must be declared before use.

7
Variable Assignment
• Assignment Statement :A direct way to change the value of variable.
An assignment statement is an order to the computer saying “set the value of this variable to what I have written down. ”
For example:
total_weight = one_weight * number_of_bars;
This assignment statement tells the computer to set the value of total_weight equal to the number in the variable
one_weight multiplied by the number in number_of_bars.
• A variable can be initialized at the time of declaration.
• An assignment statement always consists of:
• a variable on the left-side of the equal sign
• an expression on the right-side.
• ends with a semicolon.
Examples of assignment:
int a = 10;
total_weight = 6;
total_weight = one_weight;
total_weight = one_weight + 3;

8
Constants
• In programming there are constant values we face over time that don’t change throughout life of the program
or are important to the program that the values don’t change.
• Named constants are constants that are created or named by the programmer.
• To declare a constant variable the keyword const must be used.
• When using the const keyword it declares the variable as "constant", which means unchangeable and read-
only.
Example:
const int myNum = 15; // myNum will always be 15
myNum = 10; // error: assignment of read-only variable 'myNum'

9
Input and Output
• An input stream is the stream of input that is being fed into the computer for the program to use.
• Input is fed to the program by using cin keyword.
• Used to accept an input from user
For example
cin >> firstname
• An output stream is the stream of output generated by the program.
• Program output is streamed by using cout keyword.
- Used to stream an output from the program to the screen.
- For example
cout << ”Please enter your name: ”;
cout << “the total cost is $” << (price + tax);
cout << first name << “ “ << second number;
• The arrow notation << is often called the insertion operation.

10
Include Directives and Namespaces
#include <iostream>
using namespace std;
• These two lines make the library iostream available.
• iostream is the library that includes the definition of cin and cout among other things. The operations of cin
and cout is defined in this file.
• C++ divides name into namespaces.
• A namespace is a collection of names, such as the names cin and cout.
using namespace std;
• This statement says that your program is using the std (standard) namespace.

11
Escape Sequences
• The \ preceding a character tells the compiler that the character following the \ does not have the
same meaning as the character appearing by itself.
• Such a sequence is called an escape sequence.
• The sequence is typed in as two characters with no space between the symbols.

12
Data Type
• All variables use data-type during declaration to
restrict the type of data to be stored.
• Data types are used to tell the variables the type of
data it can store.
• Whenever a variable is defined in C++, the
compiler allocates some memory for that variable
based on the data-type with which it is declared.
• Every data type requires a different amount of memory.
• Data-types are classified into three:
1. Primitive or Primary Data Types
2. Derived Data Types
3. Abstract or User-Defined Data Types

13
Data-type
1. Primitive Data Types
• These data types are built-in or predefined data types.
• It can be used directly by the user to declare variables.
• Primitive data types available in C++ are:
 Integer
 Character
 Boolean
 Floating Point
 Double Floating Point
 Valueless or Void
 Wide Character

14
Data-type
2. Derived Data Types:
• The data-types that are derived from the primitive or built-in datatypes are referred to as Derived Data
Types.
• These can be of four types namely:
 Function
 Array
 Pointer
 Reference

3. Abstract or User-Defined Data Types:


• These data types are defined by user itself.
• C++ provides the following user-defined datatypes:
 Class
 Structure
 Union
 Enumeration
 Typedef defined DataType

15
Primitive Data Type
• Integer:
 Keyword used for integer data types is int.
 Integers typically require 4 bytes of memory space.
 It ranges from -2147483648 to 2147483647.
• Character:
 Used for storing characters.
 Keyword used for character data type is char.
 Characters typically requires 1 byte of memory space .
 It ranges from -128 to 127 or 0 to 255.
• Boolean:
 Used for storing logical values.
 A Boolean variable can store either true or false.
 Keyword used for Boolean data type is bool.

16
Primitive Data Type
• Floating Point:
 Used for storing single precision floating point values or decimal values.
 Keyword used for floating point data type is float.
 Float variables typically requires 4 byte of memory space.
• Double Floating Point:
 Used for storing double precision floating point values or decimal values.
 Keyword used for double floating point data type is double.
 Double variables typically requires 8 byte of memory space.
• Valueless or Void:
 Void means without any value.
 Void datatype represents a valueless entity.
 Void data type is used for those function which does not return a value.
• Wide Character:
 Wide character data type is also a character data type but this data type has size greater than the normal 8-bit datatype.
 Represented by wchar_t.
 It is generally 2 or 4 bytes long.

17
Data Type Modifiers
• A modifier is used to alter the meaning of the base
type so that it more precisely fits the needs of
various situations.
• C++ allows the char, int, and double data types to
have modifiers preceding them.
• There are four type modifiers in C++
 short
 long
 signed
 unsigned

18
Data Type Modifiers

19
Operators
• An operator is a symbol that tells the compiler to perform specific
mathematical or logical manipulations.
Arithmetic Operators
Assignment Operator
Compound Assignment Operators
Relational or Comparison Operators
Logical Operators
Bitwise Operators

20
Arithmetic Operators

• Arithmetic operators are used to make mathematical or arithimetic operation on the operands.

• All of the arithmetic operators can be used with numbers of type int, double, and even with one
number of each type.

• If both operands (that is, both numbers) are of type int, then the result of combining them with
an arithmetic operator is of type int.

• If one, or both, of the operands is of type double, then the result is of type double.

21
Arithmetic Operators
• There are two types of arithmetic operators.
1. Binary operators have two operands.
• Operators that work with two operands.

2. Unary operators have only one operand.


• One of the unary operators are + and –. Both are used in the expressions to show the sign of the
number.
Example: +7 and −7.

• The C++ language has two other very common unary operators, ++ and --.
• The ++ operator is called the increment operator.
• The -- operator is called the decrement operator.

22
Arithmetic Operators

23
Compound Assignment Operators

• = is called an assignment operator.


• When an assignment operator is
used with arithmetic, comparison
or bitwise operator we call it
compound assignment operator.

24
Compound Assignment Operators

25
Relational or Comparison Operators

26
Logical Operators

27
Bitwise Operators

28
Post fix and Prefix
• Postfix - returns the value and then performs the operation
Example:
int a = 2;
cout <<a; //this gives out 2
cout<<a++; //this gives out 2
cout<<a; //this gives out 3

• Prefix - performs the operation and returns the value


Example:
int a = 2;
cout <<a; //this gives out 2
cout<<++a; //this gives out 3
cout<<a; //this gives out 3

29
Precedence Rule
• Operations in parentheses will ALWAYS come first.
• When parentheses are omitted from an expression, the computer groups
items according to rules knowns as precedence rules.
• If one operation is evaluated before another, the operation that is evaluated
first is said to have higher precedence.

30
Precedence Rule

31
Program Style
• A program that is written with careful attention to style is
 easier to read,

 easier to correct and

 easier to maintain or change.

• The recommended program style is to use:


 Indentation

 Comments

 Named constants where needed.

32
Program Style

• Indenting
• Indenting means using tabs and spaces to make the code we write clear.

• Indenting can help to make the structure of the program clearer.

• A statement within a statement should be indented.

• Use 4 space indentation or tab, and indent only one level for each nested if, while, or switch.

• Place the opening brace { at the end of the first line of the if, while, struct, etc.

33
Program Style
A program with bad indentation A program with good indentation
int Test(int number){int count;for (count = 1; count < int Test(int number)
MAX;count++) {if (number+1 > i && number-1 < count)
{
{printf("hello\n");}else {printf("goodbye\n");}number =
number + 1;}count = number;while (count > int count;
MAX)count = count - DECREMENT;}
for (count = 1; count < MAX; count++) {
if (number+1 > i && number-1 < count) {
printf("hello\n");
}
else {
printf("goodbye\n");
}
number = number + 1;
}

count = number;
while (count > MAX)
count = count - DECREMENT;
}

34
Program Style
• Comments
• In order to make a program understandable, you should include some explanatory
notes at key places in the program. Such notes are called comments.
• C++ and most other programming languages have provisions for including such
comments within the text of a program.
• There are two types of comments in C++
 Single line comment:
Can be added at the beginning, on a new line and after a code
//single line comment
 Multi-line comment
/* multi line comment
Another line comment
*/

35
Program Style

36
Thank you!

37

You might also like