Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Practical 03

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

Practical 03

Getting familiar with fundamentals of programming using C++


Objectives
 Getting familiar with basics of C++ programming language.
 Be able to write and debug simple programs in C++.
 Understanding the concept of variable, data types and operators in C++.
Tools
 Code::Blocks
Keywords: C++, CodeBlocks, cpp, Variable, Data type, Operator. Duration: 03 hours

3.1 Introduction

3.1.1 C++ Programming Language

C++ is a high-level programming language developed by Bjarne Stroustrup at Bell Labs beginning in
1979 as an enhancement to the C programming language and named it "C with Classes". In 1983 it
was renamed to C++.

3.1.2 Code::Blocks

Code::Blocks is a free, open source cross-platform Integrated Development Environment (IDE) which
supports multiple compilers including GCC, Clang and Visual C++.

3.1.3 Basic C++ Program


#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
cout<<”My name is Ali Asghar”;
getch();
return 0;
}
First two lines are known as preprocessor directives which are instructions to the part of the
compiler known as preprocessor. The files iostream and conio.h are known as the header files.

using namespace std enables a program to use all the names in any standard C++ header (such as
<iostream>) that a program might include.

The main() function is the first executable function in any C++ program. The braces “{ “and “}” also
known as curly braces, enclose the block of code. The cout<<”My name is Ali Asghar” tells the
computer to print the string constant “My name is Ali Asghar” on the console screen.

The getch() (get character) function waits to get the character from keyboard. If you run your
program without using getch() your program will show the result in just one blink and will vanish
out quickly. When the return statement is used at the end of main, the value 0 indicates that the
program has terminated successfully, and any other value indicates abnormal termination.
Practical 03: Getting familiar with fundamentals of programming using C++

3.1.4 Statements

Statements are the instructions to the computer to work accordingly. In C++ all the statements are
always terminated with the semicolon “;”. This semicolon is known as terminator.

3.1.5 Preprocessor Directives and the Header Files

The preprocessor directives are the instruction to the part of the compiler known as preprocessor
and the header files contain the definitions of functions.

3.1.6 Outputting with cout

The cout statement displays text, numbers, characters and graphical symbols on the console screen.
cout<<”My name is Ali Asghar”;

The text in the double quotation marks ”My name is Ali Asghar” is the string constant and is printed
on the console screen as it is. The operator << is known as insertion or put to operator.

You can use the variable name in cout statement to print its value on the console screen:
cout<<”The addition of two numbers is: “<<Add;

3.1.7 Inputting with cin

The cin statement is responsible for getting input from the user during run-time.
cin>>variable_name;

The operator >> is known as extraction or get from operator.

3.1.8 Comments

Comments are non-executable lines of code in source code. Comments help make code easier to
understand.

There are two types of comments in C++: Single-line comment and Multi-line comment. In first case
we start comment with the two back slashes “//” , this causes the compiler to consider the whole line
as a comment. The second way is to start the comment with a back slash and an asterisk “/*” and
terminate the comment with an asterisk and back slash “*/”, which cause the certain block of line as
a comment.

3.1.9 Variables

A variable is a name piece of memory location that stores the data temporarily. The name given to
the variable is known as identifier. In C++ there are certain rules for identifiers as given below:

1) It can contain letters form a-z, numbers form 0-9 and an underscore sign.
2) It is case sensitive.
3) The first character of the identifier must be letter or an underscore sign.
4) The identifier should not contain any space (white space) within it.
5) You can also give underscore sign in the middle of the identifier as an space for your ease.
6) The identifier must not be same as any of the keyword (reserved word in C++).
7) The identifier can be as long as you like, but only the first 247 will be recognized.
8) The identifier must be unique throughout the program.
Practical 03: Getting familiar with fundamentals of programming using C++

Some valid identifiers are: Var, var, VAR, Var1, VAR1, Var_one, _Var1, _Var_one_of_one etc.
Some of invalid identifiers are: 1Var, 1_var, void, cout, etc.

3.1.9.1 Declaring and Defining a Variable


var1 var1
The declaration is the process of giving a name to the
variable and its data type during variable creation. Data type 50
specifies the type of value that will be stored in the variable.
data_type variable_name; int var1; int var1 = 50;

The above line specifies the syntax of variable declaration.

Whereas the process of initializing certain value to the variable at the time of declaration is referred
as defining a variable. The line below specifies the syntax of variable definition:
data_type variable_name = value;

3.1.10 Data Types

Data types specify the type of the data to be stored in a memory location (variable). The data types
available in C++ are given below:

Numerical Range
Data Type Bytes of Memory
Low High
bool true false 1
char -128 127 1
short -32,768 32,767 2
int -2,147,483,648 2,147,483,647 4
long -2,147,483,648 2,147,483,647 4
float 3.4 x 10-38 3.4 x 1038 4
double 1.7 x 10 -308 1.7 x 10308 8
long double 1.2 x 10-4932 1.2 x 104932 10

3.1.11 The const Qualifier

The keyword const is known as the constant qualifier. It specifies that the value of the variable will
remain constant and will not be altered throughout the program.
const float PI = 3.1415F;

It specifies that the variable PI stores a floating point number 3.1415 and its value will not be altered.

3.1.12 Operators in C++

Arithmetic Operators Logical Operators


Operator Name Example Operator Name Example
+ Addition radius = 25.5; && AND c = a && b;
- Subtraction c = a – b; || OR c = a || b;
* Multiplication c = a * b; ! NOT b = !a;
/ Division c = a / b;
% Remainder c = a % b;
Practical 03: Getting familiar with fundamentals of programming using C++

Relational Operators Increment/Decrement Operators


Operator Name Example Operator Name Example
== Equals to a == b; ++ Prefix Increment ++a;
!= Not equals to a != b; ++ Postfix Increment a++;
> Greater than a > b; -- Postfix Decrement --a;
< Less than a < b; -- Postfix Decrement a--;
>= Greater than or equals to a >= b;
<= Less than or equals to a <= b;

3.2 Procedure

Consider the following problem example, we are writing C++ source code in Code::Blocks IDE.
Problem statement: Write a program in C++ that accepts the width and the height of a rectangle
from the user and prints the area of the rectangle.

Step 01: Run Code::Blocks IDE.


Step 02: Create new cpp file by going in to File Menu>New>File.
Step 03: Select C/C++ Source from template dialog box.
Step 04: Press Go button and then Next button. Select C++ and press Next.
Step 05: Choosing the destination location for the file. Click Finish button.
Step 06: Write your code in Code Window.
#include <iostream>
#include <conio.h>

using namespace std;

int main()
{
float height, width, area;

cout<<"Enter height of rectangle: ";


cin>>height;
cout<<"Enter width of rectangle: ";
cin>>width;

area = height * width;


cout<<"Area of rectangle = "<<area<<endl;

getch();
return 0;
}

Step 07: Click button to compile the code.


Step 08: Debug any error in the code and recompile it.
Step 09: Click button to run the code.
Enter height of rectangle: 5.5
Enter width of rectangle: 6.1
Area of rectangle = 33.55
Practical 03: Getting familiar with fundamentals of programming using C++

EXERCISE
1. Briefly answer the following questions:

a. What is Integrated Development Environment (IDE)?


b. What is the role of main function in a C++ program?
c. Will the program execute if there is no any main function in it?
d. What will happen if there are more than one main functions in the program?
e. Can we write the preprocessor directives after the main function?
f. What is syntax error and logical error?

2. Write a complete program that calculates and displays the product of three integers. Add
comments to the code where appropriate.

3. What, if anything, prints when each of the following C++ statements is performed? If
nothing prints, then answer “nothing.” Assume x = 2 and y = 3.

a. cout << x;
b. cout << x + x;
c. cout << "x=";
d. cout << "x = " << x;
e. cout << x + y << " = " << y + x;
f. z = x + y;

4. Write a program that asks the user to enter two numbers, obtains the two numbers from
the user and prints the sum, product, difference, and quotient of the two numbers.

5. Consider the following C++ program that calculates the area of triangle;

#include <iostream>
include <conio>

using namespace std;

int MAIN()
}
char height, base, area;

cout<<"Enter height of triangle: ";


cin>>height;
cout<<"Enter base of triangle: ";
cin>>BASE;

area = (height / base) * 2;


cout<<"Area of triangle = "<<Area;

getch()
return;
{

a. Find all syntax errors.


b. Find all logical errors.
c. Correct and rewrite the program.
Practical 03: Getting familiar with fundamentals of programming using C++

6. For each of the following, specify whether it is a valid or invalid identifier. In case of invalid
identifier give the reason i.e. why it is invalid?

a. second_number e. 2nd_# i. 2nd_#_include


b. second number f. #_second j. 1#_include_sec
c. 2nd_number g. include_second_number
d. number_2nd h. 2nd_number_include

7. For each of the data item given below, write down the example value and the data type.

S.NO. Data Item Example Value Data Type


1 CNIC number
2 Phone number
3 Roll number
4 Option in MCQ
5 Percentage of marks

You might also like