Introduction To Computer Programming: Instructor: Mahwish Shahid
Introduction To Computer Programming: Instructor: Mahwish Shahid
Programming
Introduction to C++ and IDE
Chapter # 02
Starting 'C++'
Our First Program
Modify First program
Identifiers
Key words
Variables / Constants
Data Types
Operators
Expression
Precedence of Operators
Starting C++
Computer Program: Set of instructions
System Program
Application program
Low Level Language:
Machine Language: Binary Language: logically Binary Digits represent current’s availability in circuit
High Level Language:
C++ (Intermediate level language)
What is important / needed to learn a natural language? E.g. Subject Verb Object
Set of Alphabets Word Grammar Phrase / Sentences Rules / Syntax Valid Words and
What is needed to Learn C++? sentence
List of Special characters e.g.
Set of Characters: English Alphabets (a-z) (A-Z) Digits (0-9) # { } ( ) < > & + - * / ! || , ;
Constants, variable, Keywords Main, Int, Long, For, While, Do, If
Syntax / Rules Instruction Program
/ Statement
Intro to C++ Program
1. #include <iostream> Iostream: input output stream: built in Library include: to invoked that library : header file / pre processor Directive
2. using namespace std; Class of elements : an abstract container, holding definition of Input (cin) Output (cout) Functions,
3. int main () Function: Name, Inputs of Function (Argument), Output of Function (Return)
4. { Starting point of function Body
5. //variable declaration Function Body /
// are used for single line comments
Scope of Function
6. //read values input from user //Indentation is for the convenience of the reader;
7. //computation and print output to user Compiler ignores all spaces and new line
8. return 0; If function has an output
9. } End of function Body
After writing a C++ program in editor, you need to compile that program to checks whether the
program follows the C++ syntax
If there are errors, it lists those errors down
If there are no errors, it translates the C++ program into a program in machine Code which you can execute.
All statements ended by semicolon (;), the delimiter for the compiler is the semicolon
Case Sensitive Void is different than void
Main is different than main
Parts of a First C++ Program
1 // sample C++ Program Comment (//) forward slashes
“Using” is the keyword of directive to tell the compiler that the subsequent code is making use of
names in the specified namespace.
This will enable to omit std:: before each use of a name (member) in the std namespace
#include <iostream>
using namespace std;
C++ uses streams for input and output: Stream - is a sequence of data to be read (input stream) or a
sequence of data generated by the program to be output (output stream)
Other Features in C++ Program
Blank Lines and White Space
You use blank lines, space characters and tab characters (i.e., “tabs”) to make
programs easier to read.
Together, these characters are known as white space.
White-space characters are normally ignored by the compiler.
The Main Function
part of every C++ program
Program execution always begin from main function.
Main Function: Return type and Arguments.
Left curly brace {, begin the body of every function.
A corresponding right curly brace, }, must end each function’s body.
Block
A set of statements contained within a pair of braces
Other Features in C++ Program (cont’d)
An Output Statement
To print the string of characters enclosed b/w double quotation marks.
A string is called a character string / string literal / simply string.
White-space characters in strings are not ignored by the compiler.
General syntax: cout<<“Text_to_Print_on_Screen. ”;
Cout << "hello, there!";
Every c++ statement must end with a semicolon (statement terminator).
Output and input in c++ are accomplished with streams of characters.
So, it sends the stream of characters to the standard output stream object which is
normally “connected” to the screen.
11. cout << "Enter second integer: "; // prompt user for data
12. cin >> number2; // read second integer from user into number2
13. sum = number1 + number2; // add the numbers; store result in sum
14. cout << "Sum is " << sum << endl; // display sum; end line
15. } // end function main
Other Features in C++ Program (cont’d)
An Input Statement
To Store data in the computer's memory requires two steps
Allocate the memory by declaring a variable
Fetch a value from the input device and place it in the allocated memory location
Console Input: to get the values of variables from user
When input statement is read by program
it just pauses the execution until the user types something and presses <Enter> key
Program Output
General syntax: cin >> Variable_to_hold_value_ of_User’s_choice; 1234
Example:
cin >> number1;
cin >> x
The Stream Extraction Operator (>>)
To obtain a value from the keyboard stream.
Using multiple stream insertion operators (<<) in a single statement is referred to
as concatenating, chaining or cascading stream insertion operations.
Other Features in C++ Program (cont’d)
Comments
To increase the readability of the code
Not displayed on output screen
Single Line Comment : using // comment
Multi –Line Comment: using
/* please enter your comment text here if its more than one line */
Basic Concepts C++ Program
Identifiers
Key words / Reserve Words
Variable & Constants
Data Types
Operators
Arithmetic
Assignment
Logical Increment / Decrement
Relational
Expressions
Operators Precedence
Identifier
Identifiers
a name used to identify a variable, function, class, module, or any other user-defined item.
Keywords cannot be used as identifiers.
Can starts with a letter A to Z or a to z or an underscore (_) followed by zero or more
letters, underscores, and digits (0 to 9).
C++ does not allow following punctuation characters:
@, $, and % within identifiers. C++ is a case-sensitive programming language.
C++ is case sensitive, Upper- and lower-case characters are distinct
Thus, Manpower and manpower are two different identifiers in C++.
Valid Examples:
Invalid Examples:
X, x_1, _abc, A2b,
12, 3X, %change, myFirst.c, data-1
ThisIsAVeryLongIdentifier
Identifier: Programming Tips
Identifiers should be
Short enough to be reasonable to type (single word is norm)
Standard abbreviations are acceptable
Long enough to be understandable
Careful selection of identifiers makes your program clearer
Two styles of identifiers
C-style - terse, use abbreviations and underscores to separate the words, never use capital letters for
variables
Camel Case I - if multiple words: capitalize, do not use underscores
Camel Case II variant: first letter lowercased Identifier Valid / Reason if invalid
Pick style and use consistently invalid
Camel Case I C-style Camel Case II totalSales Yes
Min min min total_Sales Yes
Temperature temperature temperature total.Sales No Cannot contain .
CameraAngle Camera_angle cameraAngle 4thQtrSales No Cannot begin with digit
CurrentNumberPoints Cur_Num_Point currentNumberPoints
totalSale$ No Cannot contain $
Class Activity (I-a)
Which of the following are legal variable names in C++? What’s wrong with the
illegal names?
3rdItem Item2 IsGood? _left
float TaxRate pi_r_sqrd table4.1 m
Have special meaning to the compiler auto double else break typeid
Initialization
Assignment of an initial value for a variable using (=) assignment operator
General Syntax: Syntax: Example: int y = 45
Data_type identifier_name = value; CONST data_type identifier = value; Double x;
Uninitialized variable will contain garbage value x = 4;
Few compilers will catch this error, but most will issue a warning.
Example: CONST double PI = 3.14159;
If not corrected, it will cause a logic error.
To avoid logical error try to Initialize all variables when they are declared
Note: initialization of the variable is optional with declaration of variable.
Note initialization of the constant is required at the time of declaration.
Data Types
Data Types: what type of data store in memory
A set of values + a set of operations.
Based on the data type of a variable, the operating system allocates memory and decides what can
be stored in the reserved memory.
The set of values for each type is known as the domain of data type
Specify the space required in memory by declaring a variable
Standard Data Type Keyword
Primitive Built-in Types Boolean bool
offers the programmer built-in as well as user defined data types
Character char
Provided as an integral part of C++
Integer int
Requires no external code
Floating point float
Consists of basic numerical types
Majority of operations are symbols (e.g. +,-,*,…) Double floating point double
Valueless void
Class data type
Wide character wchar_t
Programmer-created data type
Set of acceptable values and operations defined by a programmer using C++ code
Data Type Modification
Several of the basic types can be modified using following type modifiers:
Signed, Unsigned
Short, Long
Different compilers have different internal limits on the largest and smallest values that can be stored in
each data type.
Void: Represents the absence of type. It has no values and no operations. (Empty)
Int: Natural size of integer
Float: A single-precision floating point value
Double: A double-precision floating point value
Char: To hold ASCII character. It is of one byte.
Bool: Stores either value true or false
Integer Data Types
A number without a fractional part, i.E. Int, short int and long int.
Most common allocation for int is four bytes. Set of values are whole numbers:
integers
Explicit signs allowed
Commas, decimal points, and special signs not allowed a= 10
Overwrite Value 1.int main() b=20
2.{ a= 10
3. Int a=10, b=20; b=10
4. cout << "a = " << a << " \n b= " << b<< endl;
5. b=a;
Type Sign Byte Number of bits
6. cout << "a = " << a << " \n b= " << b<< endl;
size
7.return 0;
8. } Short int Signed 2 16
Examples of int: unsigned
Valid: 0 5 -10 +25 1000 253 -26351 +36 Int Signed 4 32
Unsigned
Invalid: $255.62 2,523 3. 6,243,982 1,492.89
Long int Signed 4 32
Unsigned
Floating Point Data Types
Number with a fractional part, such as 43.32.
The C++ language supports three different sizes of floating-point: Type Byte Number of
size bits
1. Float
Float 4 32
2. Double Double 8 64
3. Long double Long double 10 80
sizeof (float) <= sizeof (double) <= sizeof (long double)
1.int main()
Round off / Truncate a= 10
2.{
3. Int a=10, b=20.5
4. float b=20.5; a= 20
5. cout << "a = " << a << " \n b= " << b<< endl; b=20.5
6. a=b;
7. cout << "a = " << a << " \n b= " << b<< endl;
8.return 0;
9. }
Although the physical size of floating-point types is machine dependent, many
computers support the sizes shown below.
Character Data Types
A variable or a constant of char type can hold an ASCII character.
Single character value: letter, digit, or special character enclosed in
single quotes
Examples: ‘A’ ‘$’ ‘b’ ‘7’ ‘y’ ‘!’ ‘M’ ‘q’
Examples:
const char star = '*';
char letter, one = '1';
Used to store single characters
Each character contained in two bytes
Letters of the alphabet (upper- and lowercase)
Digits 0 through 9
Special symbols such as + $ . , - !
Bool Data Types
Represents Boolean (logical) data
Restricted to true or false values
Often used when a program must examine a specific condition
If condition is true, the program takes one action;
if false, it takes another action.
Boolean data type uses an integer storage code
String Data Type
A Programmer-defined type #include <iostream>
using namespace std;
Requires #include <string> int main()
{
A string is a sequence of characters int x=10;
Enclosed in double quotes float y = 20.5;
char z = 'z', a= 65;
"Hi Mom" cout << " Integer= " << x<<endl;
"We're Number 1!" cout << "\n Size of Int=" << sizeof(int)<<endl;
cout << "\n Float= " << y << endl;
"75607" cout << "\n Size of Float=" << sizeof(float)<<endl;
cout << " \n Char in z= " << z << endl;
cout << "\n Size of Char=" << sizeof(char)<<endl;
cout << " \n Char in a= " << a << endl;
cout << "\n Size of Short Int=" << sizeof(short int)<< endl;
cout << "\n Size of Long Int=" << sizeof(long int) << endl;
cout << "\n Size of Double=" << sizeof(double)<<endl;
cout << "\n Size of Boolean=" << sizeof(bool) << endl;
system("pause");
return 0;
} // end function main
How much memory type takes to store the value in
memory?
Type Bit Typical Range
Conditional ? Condition ? X : Y If condition is true then it returns value of X otherwise returns value of Y.