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

Introduction C++

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

1

ALGORITHMS AND PROGRAMMING - ULTACH ENRI

Chapter 2

INTRODUCTION to C++

C++ was introduced by Bjarne Stroustrup at Bell labs in 1980, developed from the C
language introduced by Dennis Ritchie in 1972. The name C is used as the successor to the B
language introduced by Ken Thompson who is the successor of the BPCL (Basic Combined
Programming Language) language introduced by Martin Richard in 1967. The name C++ denotes
an addition, i.e., class, but was originally named "C with class" which could facilitate object-
oriented programming.
Programming
Inventors
language
Bcpl Martin Richard
B Ken Thompson
C Dennis Ritchie
C++ Bjarne Strouptrup

The major difference between C and C++ is that C is a procedural programming language,
which means that it is derived from sequential step by step structured programming. On the
other hand, C++ is a combination of procedural programming as well as object-oriented
programming. Objects consists of Data in form of its characteristics and are coded in the form of
methods. In object-oriented programming computer programs are designed using the concept
of objects that interact with the real world. Some of the differences between c and c++ can be
seen in table below:

C c++
Since C is a procedural programming, it
C++ is an object driven language.
is a function driven language.
In C, functions cannot be defined inside In C++, functions can be used inside a
structures structure.
C uses functions for input/output. For C++ uses objects for input output. For
example, scanf and printf. example, cin and cout.
C does not provide direct support for C++ provides support for exception
error handling (also called exception handling. Used for errors that make
handling) the code incorrect.
C does not support reference variables. C++ supports reference variables.

FAKULTAS ILMU KOMPUTER UNIVERSITAS SINGAPERBANGSA KARAWANG


2
ALGORITHMS AND PROGRAMMING - ULTACH ENRI

The main purpose of creating C++ is to increase the productivity of programmers in


creating applications. PBO and C++ can reduce complexity, especially in large programs consisting
of 10,000 lines or more. Greg Perry in 1993 stated that C++ can increase programmer productivity
more than twice as much as procedural languages such as C, PASCAL and BASIC because code
written with C++ is easier to reuse on other programs.

2.1. C++ Syntax


The structure of the C++ program is the same as the previous C program structure. The
C++ program structure consists of several function blocks, each function consisting of one or
more statements that carry out a specific task.

Properties of C are covered on C++

Header

names for objects and variables can be used


from the standard library

In C++, all the header files may or may not end with the “.h” extension but in C, all the
header files must necessarily end with the “.h” extension. There are of 2 types of header file:
1. Pre-existing header files: Files which are already available in C/C++ compiler we just need to
import them.
2. User-defined header files: These files are defined by the user and can be imported using
“#include”.

Syntax:

FAKULTAS ILMU KOMPUTER UNIVERSITAS SINGAPERBANGSA KARAWANG


3
ALGORITHMS AND PROGRAMMING - ULTACH ENRI

Standard Header files are:


Header Description
iostream stands for standard input-output stream. This header file
#include<iostream>
contains definitions of objects like cin, cout, etc.
iomanip stands for input-output manipulators. The methods declared
#include<iomanip.h> in these files are used for manipulating streams. This file contains
definitions of setw, setprecision, etc.
This header file mainly describes the file stream. This header file is used
#include<fstream.h> to handle the data being read from a file as input or data being written
into the file as output.
It is used to perform input and output operations using
#include<stdio.h>
functions scanf() and printf().
It is used to perform various functionalities related to string
#include<string.h>
manipulation like strlen(), strcmp(), strcpy(), size(), etc.
It is used to perform mathematical operations like sqrt(), log2(), pow(),
#include<math.h>
etc
#include<signal.h> It is used to perform signal handling functions like signal() and raise().
It is used to perform standard argument functions
like va_start() and va_arg(). It is also used to indicate start of the
#include<stdarg.h>
variable-length argument list and to fetch the arguments from the
variable-length argument list in the program respectively.
It is used to perform error handling operations
#include<errno.h>
like errno(), strerror(), perror(), etc.
It is used to perform functions related to date() and time() like setdate()
#include<time.h> and getdate(). It is also used to modify the system date and get the CPU
time respectively.
It contains a set of various platform-dependent constants related to
floating point values. These constants are proposed by ANSI C. They
#include<float.h>
allow making programs more portable. Some examples of constants
included in this header file are- e(exponent), b(base/radix), etc.
It determines various properties of the various variable types. The
macros defined in this header, limits the values of various variable
#include<limits.h> types like char, int, and long. These limits specify that a variable cannot
store any value beyond these limits, for example an unsigned character
can store up to a maximum value of 255.
Perform console input and console output operations like clrscr() to
#include<conio.h>
clear the screen and getch() to get the character from the keyboard.
Perform standard utility functions like dynamic memory allocation,
#include<stdlib.h>
using functions such as malloc() and calloc().

FAKULTAS ILMU KOMPUTER UNIVERSITAS SINGAPERBANGSA KARAWANG


4
ALGORITHMS AND PROGRAMMING - ULTACH ENRI

2.2. Identifier
An identifier is a name commonly used in programming to express variables, constants,
data type, function, label, object, as well as other things declared or defined by programmers.
Rules for constructing identifier names:
1) Can consist of letters, digits, and underscores
2) Must begin with a letter or an underscore
3) These are case sensitive
4) Whitespaces or special characters like !, #, %, etc. Are not allowed
5) Reserved words cannot be used as names

Note: The maximum length of the identifying name on C++ depends on the compiler used. For
example, Borland C++ allows identifying names up to 32 characters (which is significant, the
advantages will be ignored), while Turbo C++ guarantees a significant name of up to 31
characters.

2.3. Case Sensitive


In C++ lowercase and uppercase in an identifier are not considered equal. This trait is
known as case sensitive. For example, “Me” is different with “me”.

2.4. Reserved Words


Reserved words are system identifiers that have special meaning for compilers. The uses
of this group cannot be changed. A reserved word cannot be used as an identifier, such as the
name of a variable, function, or label – it is "reserved from use". This is a syntactic definition, and
a reserved word may have no meaning.

Reserved Words:
auto const double float int short struct unsigned
break continue else for long signed switch void
case default enum goto register sizeof typedef volatile
char do extern if return static union while
asm dynamic_cast namespace reinterpret_cast try bool explicit new
static_cast typeid catch false operatot template typename class
friend private this using const_cast inline public throw
virtual delete mutable protected true Wchar_t

FAKULTAS ILMU KOMPUTER UNIVERSITAS SINGAPERBANGSA KARAWANG


5
ALGORITHMS AND PROGRAMMING - ULTACH ENRI

2.5. Variables
Variables are containers for storing data values or data that can change during the
process. To create a variable, you must specify the type and assign it a value, it’s called a variable
declaration.
Syntax: data_type variable_name;

Example: int a;
Int a, b, c;
char grade;
float value1;

2.6. C++ Comments


Comments can be used to explain C++ code, and to make it more readable. It can also be
used to prevent execution when testing alternative code. Comments can be singled-lined or
multi-lined.
 Single-line comments start with two forward slashes (//). Any text between // and the end
of the line is ignored by the compiler (will not be executed).
e.g.: // This is a comment
 Multi-line comments start with /* and ends with */. Any text between /* and */ will be
ignored by the compiler:
e.g.: /* The code below will print the words Hello World!
to the screen, and it is amazing */

2.7. C++ Data Types


A variable in C++ must be a specified data type. The data type specifies the size and type
of information the variable will store.
Basic Data Types

FAKULTAS ILMU KOMPUTER UNIVERSITAS SINGAPERBANGSA KARAWANG


6
ALGORITHMS AND PROGRAMMING - ULTACH ENRI

2.8. C++ Output


The cout object, together with the << operator, is used to output values/print text. To use
this cout() function, it must include an iostream header.
Example:

Manipulator
Manipulators are commonly used to organize the appearance of data.
Manipulator Description
Inserts a newline and sends the output buffer contents to
Endl the output device.
cout<<information<<endl;
Insert null characters.
Ends
cout<<information<<ends;
Sends the output buffer contents to the output device.
Flush
cout<<information<<flush;
Convert to base 10
Dec
cout<<dec<<information<<endl;
Convert to base 16
Hex
cout<<hex<<information<<endl;
Convert to base 8
Oct
cout<<oct<<information<<endl;
Convert to base n (n=8, 10 or 16)
Setbase(int n)
cout<<setbase(n)<<information<<endl;
Set the field width for a value as big as n characters.
Setw(int n)
cout<<setw(n)<<information<<endl;
Set the brewing character in the form of c.
Setfill(int c)
cout<<setfill(c);
Sets the precision of a fractional number of n digits.
Setprecision(int n) cout<<setiosflags (ios::fixed);
cout<<setprecision(n)<<information<endl;
Setting the format specified by f. f is the format sign
Setiosflags(long f)
cout<<setiosflags(f);
Removing the format specified by f. f is a format sign.
Resetiosflags(long f)
cout<<resetiosflags(f);
Note: If using a manipulator other than dec, hex, oct, endl, flush, header file named iomanip.h
needs to be included.

FAKULTAS ILMU KOMPUTER UNIVERSITAS SINGAPERBANGSA KARAWANG


7
ALGORITHMS AND PROGRAMMING - ULTACH ENRI

Formats used in setiosflags() and resetiosflags():


❑ ios::left
It is useful to set the left alignment set through setw().
❑ ios::right
It is useful to set the right alignment set through setw().
❑ ios::showpos
Useful for displaying ‘+’ marks on positive numbers
❑ ios::scientific
Useful for formatting outputs in the form of exponential notation.
❑ ios::fixed
Useful for formatting outputs in decimal notation form
❑ ios::showpoint
Useful for displaying decimal points on numbers that do not have fractional parts
❑ ios::showbase
Useful for displaying prefixes 0x for hexa numbers or 0 for octal numbers
❑ ios::oct
Useful for formatting outputs on base 8
❑ ios::dec
Useful for formatting output in base 10
❑ ios::hex
Useful for formatting output in base 16
❑ ios::uppercase
Useful for formatting letters on hexa notation in capital letter form

Examples:

setprecision()

Result:

FAKULTAS ILMU KOMPUTER UNIVERSITAS SINGAPERBANGSA KARAWANG


8
ALGORITHMS AND PROGRAMMING - ULTACH ENRI

resetiosflag()

Result:

2.9. C++ Input


We will use cin to get user input. cin is a predefined variable that reads data from the
keyboard with the extraction operator (>>). In the following example, the user can input a
number, which is stored in the variable x. Then we print the value of x:

Result:

Assigment:
1. Create a program with input and output with this template:
Your name : ___________
Your Place of Birth : ___________ input

“Hello, my name is (your name) and I born at (your place of birth) → output

2. Create a program to find the area of the triangle if it is known base=10 and height=20.

FAKULTAS ILMU KOMPUTER UNIVERSITAS SINGAPERBANGSA KARAWANG


9
ALGORITHMS AND PROGRAMMING - ULTACH ENRI

3. Create a program for calculating the total price, with the following conditions:
Input : Item Code, Item Name, Item price and number of items
Output: total price

4. A car travels at a fixed speed v km/h. If the car runs for t hours, write an algorithm to calculate
the distance that has been travelled by the car (in km). The algorithm reads inputs in the
form of v and t, calculates the distance with the formula s = vt, and then print the distance.
Draw a flowchart to solve it.

5. Translate the algorithm on problem number 4 into the program in c++, then test the program
with various values v and t.

FAKULTAS ILMU KOMPUTER UNIVERSITAS SINGAPERBANGSA KARAWANG

You might also like