0% found this document useful (0 votes)
150 views16 pages

Lab N O. 8: Introduction To Fundamentals of C++ Programing Pre Lab Task

C++ is an object-oriented programming language that is a more modern version of C. The key components of a basic C++ program include header files, global declarations, the main function, and method definitions. C++ programs use semicolons to terminate statements and braces to define code blocks. C++ also has specific keywords, identifiers, and trigraph rules for character representation.

Uploaded by

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

Lab N O. 8: Introduction To Fundamentals of C++ Programing Pre Lab Task

C++ is an object-oriented programming language that is a more modern version of C. The key components of a basic C++ program include header files, global declarations, the main function, and method definitions. C++ programs use semicolons to terminate statements and braces to define code blocks. C++ also has specific keywords, identifiers, and trigraph rules for character representation.

Uploaded by

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

LAB No.

INTRODUCTION TO FUNDAMENTALS OF C++ PROGRAMING

PRE LAB TASK

Objectives:

 To know about C++ Programming language.

Theory:
Programming language
A Programming language is a formal constructed language designed to communicate
instructions to a machine, particularly a computer. Programming languages can be used to
create programs to control the behavior of a machine or to express algorithms.. Traits often
considered important for what constitutes a programming language include:

Function and target


A computer programming language is a language used to write computer programs, which
involve a computer performing some kind of computation or algorithm and possibly control
external devices such as printers, disk drives ,robots, and so on. For
example, PostScript programs are frequently created by another program to control a
computer printer or display. More generally, a programming language may describe
computation on some, possibly abstract, machine

Abstractions
Programming languages usually contain abstractions for defining and manipulating data
structures or controlling the flow of execution. The practical necessity that a programming
language support adequate abstractions is expressed by the abstraction principle; this
principle is sometimes formulated as recommendation to the programmer to make proper use
of such abstractions.
Write Types of programming languages.

Types and Programming Languages


"Types are the leaven of computer programming; they make it digestible. This excellent book
uses types to navigate the rich variety of programming languages, bringing a new kind of
unity to their usage, theory, and implementation. Its author writes with the authority of
experience in all three of these aspects."

--Robin Milner, Computer Laboratory, University of Cambridge

Object-oriented languages
Object-oriented languages help to manage complexity in large programs. Objects package
data and the operations on them so that only the operations are publicly accessible and
internal details of the data structures are hidden.

C++
The C++ language, developed by Bjarne Stroustrup at AT&T in the mid-1980s, extended C
by adding objects to it while preserving the efficiency of C programs. It has been one of the
most important languages for both education and industrial programming. Large parts of
many operating systems, such as the Microsoft Corporation’s Windows 98, were written in
C++++.

Basic Structure of C++ Program.


C++ Programming language is most popular language after C Programming language. C++ is
first Object oriented programming language. We have summarize structure of C++ Program
in the following Picture – Fig 1

 
 
Fig 1

Section 1: Header File Declaration Section

Header files used in the program are listed here.

Header File provides Prototype declaration for different library functions.

We can also include user define header file.

Basically all preprocessor directives are written in this section.

Section 2: Global Declaration Section

Global Variables are declared here.

Global Declaration may include –

1. Declaring Structure
2. Declaring Class
3. Declaring Variable

Section 3: Class Declaration Section

Actually this section can be considered as sub section for the global declaration section.

Class declaration and all methods of that class are defined here.

 
 
Section 4: Main Function

Each and every C++ program always starts with main function.

This is entry point for all the function. Each and every method is called indirectly through
main.

We can create class objects in the main.

Operating system call this function automatically.

Section 5: Method Definition Section

This is optional section. Generally, this method was used in C Programming.

When we consider a C++ program, it can be defined as a collection of objects that


communicate via invoking each other's methods. Let us now briefly look into what do class,
object, methods and Instance variables mean.

Object - Objects have states and behaviors. Example: A dog has states - color, name, breed
as well as behaviors - wagging, barking, eating. An object is an instance of a class.

Class - A class can be defined as a template/blueprint that describes the behaviors/states that
object of its type support.

Methods - A method is basically a behavior. A class can contain many methods. It is in


methods where the logics are written, data is manipulated and all the actions are executed.

Instance Variables - Each object has its unique set of instance variables. An object's state is
created by the values assigned to these instance variables.

C++ Program Structure:


Let us look at a simple code that would print the words Hello World.

#include <iostream>

#include<conio.h>

// main() is where program execution begins.

int main()

 
 
cout << "Hello World"; // prints Hello World

getch ( );}

 Let us look various parts of the above program:


 The C++ language defines several headers, which contain information that is either
necessary or useful to your program. For this program, the header <iostream> is
needed.
 The next line // main() is where program execution begins. is a single-line comment
available in C++. Single-line comments begin with // and stop at the end of the line.
 The line int main() is the main function where program execution begins.
 The next line cout << "This is my first C++ program."; causes the message "This is
my first C++ program" to be displayed on the screen.
 The next line getch ( ); holds the screen to see output.

Compile & Execute C++ Program:

1. Let's look at how to save the file, compile and run the program. Please follow the
steps given below:
2. Open a text editor and add the code as above.
3. Save the file as: hello.cpp
4. Open a command prompt and go to the directory where you saved the file.
5. Type 'g++ hello.cpp ' and press enter to compile your code. If there are no errors in
your code the command prompt will take you to the next line and would generate
a.out executable file.
6. Now, type ' a.out' to run your program.
7. You will be able to see ' Hello World ' printed on the window.
8. $ g++ hello.cpp
9. $ ./a.out
10. Hello World
11. Make sure that g++ is in your path and that you are running it in the directory
containing file hello.cpp.
12. You can compile C/C++ programs using makefile. For more details, you can
check Makefile Tutorial.

 
 
Semicolons & Blocks in C++:
In C++, the semicolon is a statement terminator. That is, each individual statement must be
ended with a semicolon. It indicates the end of one logical entity.

For example, following are three different statements:

x = y;

y = y+1;

add(x, y);

A block is a set of logically connected statements that are surrounded by opening and closing
braces. For example:

cout << "Hello World"; // prints Hello World

return 0;

C++ does not recognize the end of the line as a terminator. For this reason, it does not matter
where on a line you put a statement. For example:

x = y;

y = y+1;

add(x, y);

is the same as

x = y; y = y+1; add(x, y);

Key words:

Asm else New this

Auto enum Operator throw

 
 
Bool explicit Private true

Break export Protected try

Case extern Public typedef

Catch false Register typeid

Char float reinterpret_cast typename

Class for Return union

Const friend Short unsigned

const_cast goto Signed using

Continue if Sizeof virtual

Default inline Static void

Delete int static_cast volatile

Do long Struct wchar_t

Double mutable Switch while

dynamic_cast namespace Template

C++ Identifiers:
A C++ identifier is a name used to identify a variable, function, class, module, or any
other user-defined item. An identifier 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 punctuation characters such as @, $, and % within identifiers. C++ is a
case-sensitive programming language. Thus, Manpower and manpower are two different
identifiers in C++.

Here are some examples of acceptable identifiers:

mohd zara abc move_name a_123

myname50 _temp j a23b9 retVal

C++ Keywords:
The following list shows the reserved words in C++. These reserved words may not be used
as constant or variable or any other identifier names.

Trigraphs:
A few characters have an alternative representation, called a trigraph sequence. A
trigraph is a three-character sequence that represents a single character and the sequence
always starts with two question marks.

Trigraphs are expanded anywhere they appear, including within string literals and character
literals, in comments, and in preprocessor directives.

Following are most frequently used trigraph sequences:

Trigraph Replacement

??= #

??/ \

??' ^

??( [

 
 
??) ]

??! |

??< {

??> }

??- ~

All the compilers do not support trigraphs and they are not advised to be used because of
their confusing nature.

Whitespace in C++:
A line containing only whitespace, possibly with a comment, is known as a blank line, and
C++ compiler totally ignores it.

Whitespace is the term used in C++ to describe blanks, tabs, newline characters and
comments. Whitespace separates one part of a statement from another and enables the
compiler to identify where one element in a statement, such as int, ends and the next element
begins. Therefore, in the statement,

int age;

there must be at least one whitespace character (usually a space) between int and age for the
compiler to be able to distinguish them. On the other hand, in the statement

fruit = apples + oranges; // Get the total fruit

no whitespace characters are necessary between fruit and =, or between = and apples,
although you are free to include some if you wish for readability purpose.

 
 
Lab Task no 1

How to print Hello World using cout statement?

//we are making a program to print hellow world on the screen as an out put.

#include<iostream.h>

#include<conio.h>

void main( );

{
cout<<”hellow world!”<<endl; //Prints hellow world

getch ( );
}

Lab Task No 2

Write a program to print your name

// we are making a program to print our name on tne screen as an output.

#include <iostream.h>

#include<conio.h>

void main( )

char name;

cout << "please enter your name: ";

cin >> name;

cout << "my name is " << name << endl;

getch( )}

 
 
Lab Task No 3

Write a program that performs all Arithmetic operations on two variables

//we are making a program that performs all arithmetic operations on two variables

#include <iostream.h>
#include<conio.h>

void main( )
{
int a,b;
clrscr;
a=10;
b=5;
cout<<”a+b=”<<a+b<<endl;
cout<<”a-b=”<<a-b<<endl;
cout<<”a*b=”<<a*b<<endl;
cout<<”a/b=”<<a/b<<endl;
getch( );
}

Lab Task No 4

Write a program to print area of square

//we are making a program to print area of square.

#include<iostream.h>

#include<conio.h.

void main()

{
int a,b,e;

 
 
clrscr( );

a=20;

b=20;

e=a*b;

cout<<”the area of square is=“<<e<<endl;

getch( );
}

C++ Basic Input/Output


The C++ standard libraries provide an extensive set of input/output capabilities which we
will see in subsequent chapters. This chapter will discuss very basic and most common I/O
operations required for C++ programming.

C++ I/O occurs in streams, which are sequences of bytes. If bytes flow from a device like a
keyboard, a disk drive, or a network connection etc. to main memory, this is called input
operation and if bytes flow from main memory to a device like a display screen, a printer, a
disk drive, or a network connection, etc, this is called output operation.

 I/O Library Header Files:


There are following header files important to C++ programs:

Header File Function and Description

<iostream> This file defines the cin, cout, cerr and clog objects, which correspond to the
standard input stream, the standard output stream, the un-buffered standard
error stream and the buffered standard error stream, respectively.

<iomanip> This file declares services useful for performing formatted I/O with so-called
parameterized stream manipulators, such as setw and set precision.

 
 
<fstream> This file declares services for user-controlled file processing. We will discuss
about it in detail in File and Stream related chapter.

The standard output stream (cout):


The predefined object cout is an instance of ostream class. The cout object is said to be
"connected to" the standard output device, which usually is the display screen. The cout is
used in conjunction with the stream insertion operator, which is written as << which are two
less than signs.

The standard input stream (cin):


The predefined object cin is an instance of istream class. The cin object is said to be
attached to the standard input device, which usually is the keyboard. The cin is used in
conjunction with the stream extraction operator, which is written as >> which are two
greater than signs.

The standard error stream (cerr):


The predefined object cerr is an instance of ostream class. The cerr object is said to be
attached to the standard error device, which is also a display screen but the object cerr is un-
buffered and each stream insertion to cerr causes its output to appear immediately.

The standard log stream (clog):


The predefined object clog is an instance of ostream class. The clog object is said to be
attached to the standard error device, which is also a display screen but the object clog is
buffered. This means that each insertion to clog could cause its output to be held in a buffer
until the buffer is filled or until the buffer is flushed.

Lab Task No 5

Write a program that takes two numbers from users and display their sum in third
variable.
 

#include<iostream.h>

#include<conio.h>

 
 
void main ( )

clrscr ( );

cout<<”enter value of a”<<endl;

cin>>a;

cout<<”enter value of b”<<endl;

cin>>b;

c=a+b;

cout<<”the sum of a and b is”<<c;

getch( );}

Lab Task No 6

Write a program that prints area of triangle using printf statement.

#include<iostream.h>

#include<conio.h>

void main ( )

clrscr ( );

float,area,height,width;

prinrf (“enter a value of height=”);

scanf(“%f”,&height);

printf (“enter a value of width=”);

scanf(“%f”,& width);
area=.5*height*width;

printf(“area of triangle is=5.2%f=” , area);

getch ( );

Lab Task No 7

Write a program that display ASCII code of given character.


#include<iostream.h>

#include<conio.h>

void main ( )

clrscr ( );

int num;

char charc;

cout<<”enter character:”;

cin>>charc;

num=charc;

cout<<”the ascii code for”<<char<<”is”<<num;

getch ( );

Lab Task No 8

Write a program that displays average and percentage of given subjects.


#include<iostream.h>

#include<conio.h>

 
 
void main ( )

clrscr ( );

float physics,chemistry,maths,avg,per,sum,total;

cout<<”enter number of maths=”<<endl;

cin>>maths;

cout<<”enter number of chemistry=”<<endl;

cin>>chemistry;

cout<<”enter number of physics=”<<endl;

cin>>physics;

avg=((physics+chemistry+maths)/3;

cout<<”avg is”<<avg<<endl;

per=((physics+chemistry+maths)/300)*100;

cout<<”your percent is=”<<per<<endl;

getch ( );

LAB SESSION

1. Write a program that adds and prints two characters?


2. Write a program to swap the values of two variables.
3. Write a program to swap value of two variables without using third
variable.

You might also like