The C language was first developed at Bell Laboratories (USA) around 1972 by Dennis Ritchie on a DEC PDP-11 computer with the UNIX operating system. Several versions of C began to be developed by several experts to run on operating systems other than UNIX, such as PC-DOS and MS-DOS. To carry out standardization of the C language, ANSI (American National Standards Institute) formed a team to create the ANSI standard C language, which began in 1983. This ANSI standard is then used as a reference for the various versions of C that are currently circulating.
1. Scope of Use of C Language
C language has more capabilities compared to other programming languages. C language is a portable programming language, meaning a program created with C language on one computer can be run on another computer with little (or no) significant changes.
C language is a language commonly used for system programming purposes, including to create:
- assembler
- interpreter
- compiler
- operating system
- utility program
- editor
- application program package.
Some circulating package programs such as dBase are made using the C language, even the UNIX operating system is also made using the C language.
C language is actually a versatile programming language whose use is not limited to system programming, but can also be used for business, mathematical and game applications, even for artificial intelligence applications.
In some literature, C language is classified as a medium level language.
This classification does not mean that the C language is less powerful or more difficult than high-level languages (such as Pascal, Basic, Fortran, etc.), but rather to emphasize that the C language is not a machine-oriented language (which is a characteristic of low-level languages, namely machine language and assembly).
In fact, C combines elements of both high-level and low-level languages, namely the ease of programming offered by high-level languages and the speed of execution offered by low-level languages.
2. Strengths and Weaknesses of C
The C language has several advantages compared to other programming languages, namely:
- C has complete operators for manipulating data.
- Various data structures and process controls are provided in C, making it possible to create structured programs, even object-oriented programming (OOP).
- Compared to machine or assembly language, C is much easier to understand and programmers do not need to know the details of the computer machine used so that it does not take time to solve problems into program form. C is a problem-oriented language (object), and not machine-oriented.
- The execution speed of C is close to the execution speed of programs written in low-level languages, but the ease of programming is equivalent to that of high-level languages.
- C allows to manipulate data in the form of bits or bytes efficiently. In addition, it also allows to manipulate the address of a data which in C is called a pointer.
The weaknesses or more precisely the difficulties of the C programming language, especially those felt by beginner programmers, include:
- The large number of operators and the flexibility of writing programs sometimes confuses users, which if they are not familiar with them can cause problems.
- Beginner C programmers generally have never heard of pointers and are not used to using them, even though the power of the C language lies in pointers.
However, generally the above difficulties are only temporary.
3. Interpreter and Compiler
- In order for a program in a programming language to be understood and executed by a computer, the program written must first be translated into machine code. The translator used can be an interpreter or a compiler.
- An interpreter is a type of translator that translates instructions line by line at a time.
- The advantage of using an interpreter is that program compilation is relatively faster and can be tested directly even if there are still some errors in the program's rules.
- The downside is that it is slow, because before an instruction is executed it is always translated first. In addition, when the program is executed, the interpreter must also be in memory.
- Another weakness is related to program confidentiality. Programs that use interpreters, their source programs cannot be kept confidential.
- A compiler is a type of translator that works by translating all the instructions in a program at once.
- The compilation process only needs to be done once, then the translation results (after going through other stages) can be run directly without depending on the source program or compiler.
- The execution process can run faster, because there is no longer a translation process.
- The source program can also be kept secret, because what is executed is the program file that is already in machine code form.
- The weakness is that the creation and testing process is relatively longer, because it has to go through the translation (compiling) stage and the linking process.
- The program will only compile successfully if it does not contain any syntax errors at all.
4. Function of C Program Compiler
- C language programs are essentially composed of a number of function blocks.
- A program contains at least one function, namely the main function (main()).
- Each function consists of one or more statements that as a whole are intended to perform a specific task.
- The function statement section (often called the function body) begins with an opening curly bracket ({) and ends with a closing curly bracket (}).
- But in reality a function may not contain any statements at all, as shown in the following example.
Main()
{
}
- Even though a function does not have a statement, the curly braces must still be there, because they indicate the beginning and end of the function definition.
In general, a function has the following form:
Nama-fungsi (daftar parameter)
Deklarasi parameter;
{
tubuh fungsi
}
5. Main() function
- In a C program, main() is a special function, because the main() function must always be present in the program, because this function is the starting point and ending point of program execution.
- The { sign at the beginning of a function indicates the beginning of the function body and also the beginning of the program, while the } sign at the end of a function indicates the end of the function body and also the end of program execution.
- If a program consists of more than one function, the main() function is usually placed at the top of the function definition, to make it easier to find the main program.
6. printf() function
- The printf() function is a function that is commonly used to display program output on the display screen (monitor).
- To display the text "Welcome"
So the required statement is:
Printf("Selamat Datang");
- The statement above is a call to the printf() function with the argument/parameter being the string "Welcome".
- In C a string constant is written with double quotes (").
- Statements in C always end with a semicolon ( , which is used to terminate a statement and not as a separator between two statements.
The following prog-2 example is a rather complete example of a program:
#include <stdio.h>
main ()
{
printf(" Selamat datang di program pra-pasca");
}
If the above program is executed, it will produce:
C>Prog-2 Welcome to the pre-post program.
Object Oriented Programming with C++
You have learned the basic concept of object-oriented programming in Chapter 8. While its application in programming languages has also been learned by using Java in Chapter 8 and C++ in this chapter. In this section we will try to create an object-oriented application design.
The case we are discussing is one part of the sales application in a bookstore, namely inventory. If you look closely, there are many types of goods sold in a bookstore, including reading books, magazines, office stationery, and others. Each item has a brand name, price, and other characteristics. In addition, each item also has other provisions related to pricing, discounts, purchase quantities and storage space. Inventory in a bookstore is determined by goods received from orders and goods sent out because they are sold. Every time an item goes out, the goods in the inventory will automatically decrease.
The first step in object-oriented applications is to abstract the problem. If we look closely at the case above, we can create a parent class for all types of goods that exist. This is because in addition to the specific characteristics of each type of goods, there are also general characteristics that are possessed by all goods. For example, price is a general characteristic possessed by all goods. But the brand is specific to a particular type of item, especially stationery. Likewise, the title characteristic is only possessed by reading books. By looking at these conditions, we can create the following problem abstraction.
Figure 9.10. Abstract of the inventory case in a bookstore
In Figure 9.10, we create 6 classes to simplify the case above. There are two types of relationships formed in the figure above, namely inheritance relationships marked with arrows and associations (relationships between two or more classes) marked with lines without arrows. Goods is the superclass and we can state it as an abstract class. Reading Materials and Stationery are subclasses of Goods, while Books and Magazines are subclasses of Reading Materials. While Location is a class that shows where to store goods.
In the above case we can apply the concept of inheritance and polymorphism and use pure virtual functions in the Barang class. Then we can derive these functions to be implemented in its subclasses. The program code design will look like in table 9.3.
By looking at the diagram and table 9.3, we can apply it in the program code. There will be 6 classes that we code. Each class can be in a separate file or all classes can be placed in one file. Then we create the implementation of these classes in a separate file. To connect between files and call classes in other files we use the preprocessor #include followed by the file name.
Table 9.3. Classes, functions, and parameters in the bookstore inventory application
Summary
- The general structure of a program in C++ includes a file registration section, function definition, main() section, and code blocks.
- Primitive data types in C++ consist of int, long, float, double, char, bool, and short. Composite data types provided are struct, enum and array.
- The types of operators that can be used are assignment operators, unary operators, binary operators, relational operators, bitwise operators and ternary operators.
- The selection control structure can be done with if (without then) and switch ... case. As for repetition, C++ provides the commands for, while, and do-while.
- Input and output statements can be done with the cout and cin commands as streams included in the iostream class.
- Functions can return no value but can also return a value. Parameters in a function can be input parameters, output parameters or both.
- Pointers are variables. But unlike normal variables, pointers store addresses in memory, not the values we enter.
- C++ supports object-oriented programming concepts through class creation, inheritance, virtual functions, overriding, overloading and polymorphism.
Exercises
1. Write a C++ program to find the average of 5 numbers 34, 56, 91,11, 22.
2. Create a program using C++ to determine the price of an item after a discount with the following display:
Masukkan harga barang/unit : Rp. 20000
Jumlah barang yang dibeli : 5
----------------------------------------------
Total Harga sebelum diskon : Rp. 100000
Diskon (10%) : Rp. 10000
------------------ -
Harga bersih : Rp. 90000
3. A person has a savings account in a bank of Rp. 10,000 (initial balance). Then he can deposit or withdraw his savings. Create a program with C++ for transaction purposes at the bank. The main menu display is as follows:
--------------------------------------
PT. BANK ABC
--------------------------------------
Saldo : ....
Menu Transaksi
1\. Setor Tabungan
2\. Ambil Tabungan
3\. Exit
Pilihan menu (1/2/3) ? ...
Ketentuan:
Bank membuat kebijakan bahwa saldo minimum yang harus disisakan di rekening adalah Rp. 10.000,-
If the customer enters the number 1 then he will be asked to enter the amount of rupiah to be deposited. If the customer chooses the number 2 then the customer is asked to enter the amount of rupiah to be withdrawn. If the withdrawal amount results in a balance of less than Rp. 10,000 then the program will reject. (Hint: use the cin statement to get input from the keyboard)
3.a. Create a program using a function to determine the final grade of a lesson. There are 2 function arguments, namely the midterm exam score and the final exam score. The desired output is if the average score is greater than or equal to 80 then the final score is A, if the average score is less than 80 and greater than or equal to 70 then the score is B, if less than 70 then the score is C.
3.b. Look at the example question in Chapter 8 no 6. Make a system abstraction diagram then create the program code using C++ language.
Other Version Notes
This article is an introduction to object-oriented programming (OOP) using ANSI C++. It is recommended that you first master the basics of structural programming using one of the programming languages, be it C, Pascal, Basic or others. A little history about C++, C++ was created by Bjarne Stroustrup at Bell Labs in the early 80s, as a development of the C and Simula languages. Currently, C++ is one of the most popular languages for developing OOP-based software. This article introduces the object-oriented programming paradigm using C++.
1. What is the concept of OOP?
The main concept of object-oriented programming is to model real-life objects into abstract data types. Clearly, object-oriented programming is a programming concept for modeling objects that we use in everyday life, and this concept brings fundamental changes in the concept of structured programming. Dramatic changes in basic concepts are called paradigms, so don't be surprised if many people call it the "OOP paradigm" because OOP does bring a concept that is completely different from previous generation programming languages (structured programming languages). Every object in real life can be viewed as a class, for example the Animal class, the Human class, the Car class. While objects from these classes include cows and chickens for the Animal class, Budi and Tono for the Human class and Toyota and VW for the Car class. With OOP, we can implement data objects that not only have characteristics (attributes), but also have methods to manipulate these attributes. In short, OOP has the advantage of the structured programming concept, besides also having the ability to implement objects in real life.
2. Class Structure
As a first step in OOP we will discuss class definition in C++. In section 1.2 the author has given examples of several classes that we commonly encounter in everyday life. Let's observe another example from our life, by declaring a class named RationalNumber:
class BilanganRasional
{ public :
void assign (int,int); void cetak(); private :
int pembilang, penyebut;
};
Consider the example above. To define a class, the keyword class is used, followed by the declaration of the class name. The assign() and cetak() functions are called member functions. While the numerator and denominator variables are called member data (member data or member variables). They are called members because all of them are members of the RationalNumber class.
Note the keywords Public and Private. The member functions in the example above are declared as global functions, while the data members are declared as local. The difference is, global members can be accessed from outside the class, while local members can only be accessed from the class itself.
Now, that we have created the RationalNumber class, we can declare an object of the RationalNumber class as follows:
RationalNumber objectNumber;
Note that here objectNumber is the name of the object, and RationalNumber is the name of the class we want to create the object. The process of creating an object is usually called instantiation (not installation), and an object is called an instance of a class. For more details, see the full listing:
class BilanganRasional
{ public : void assign (int,int); void cetak(); private :
int pembilang, penyebut;
};
void main()
{
//mendeklarasikan objekBilangan seperti telah dibahas di atas
BilanganRasional objekBilangan;
// member fungsi assign() dipanggil.
objekBilangan.assign (22,7);
// member fungsi cetak() dipanggil.
ObjekBilangan.cetak();
} void BilanganRasional::assign(int pemb, int peny)
{ pembilang = pemb; penyebut = peny;
} void BilanganRasional::cetak()
{ cout<<pembilang<<' / '<<penyebut;
}
Take a look at the main() block. Now you have an object named objectNumber of class RationalNumber. As you can see, declaring an object is the same as declaring a variable. Or in other words objectNumber is an object of type RationalNumber. Now, how do you call a function from an object? This can be achieved by connecting the object name and the function you want to call with the dot (.) operator. So to call the assign() function, you can do it as follows:
objekBilangan.assign(22,7);
The values 22 and 7 are the parameters accepted by the assign() function. In the function, the value 22 is initialized into the numerator data member, and the value 7 is initialized into the denominator data member. So when the print() function is called, the following result will be obtained: 22 / 7. In addition, pay attention to the illustration below:
The image above is an illustration of the Number object with 2 data members, namely the numerator and denominator.
Also note that all function declarations, both assign() and print(), are preceded by the RationalNumber:: marker. This is to indicate to the compiler so that it is not "confused" about which class the function is being declared for, because in C++ a function is usually placed in a separate file.
3. Constructor
Previously we have used the assign() member function to assign values to the numerator and denominator member variables. A constructor does the same job as the assign() function, so you don't have to bother calling the assign() function for every object you declare. A constructor must have the same name as the class in which it is located, and is declared without a return value, and without the void keyword. Let's develop the RationalNumber class that we have discussed as follows:
class BilanganRasional
{ public :
//KONSTRUKTOR BilanganRasional
BilanganRasional(int pemb, int peny)
{
pembilang = pemb; penyebut = peny;
}
private :
int pembilang, penyebut;
};
Compare the constructor structure with the assign() function that we discussed earlier. The RationalNumber constructor performs the same task as the assign() function member. The only difference lies in the calling of the function and the constructor. If the assign() function must be called by being preceded by declaring an object, then the function of the object is called with the dot operator along with the value that we want to input, for example;
BilanganRasional x;
x.assign(22,7);
then the constructor is simply called as follows:
BilanganRasional x(22,7);
Both variants do the same thing, namely initializing the value 22 to the numerator variable member, and the value 7 to the denominator variable.
4. Constructors With Initialization Lists
Writing constructors with initialization lists is a facility provided by C++ to simplify the constructor structure. This means that the constructor example above can also be written as follows:
class BilanganRasional
{ public :
BilanganRasional(int pemb, int peny) : pembilang(pemb), penyebut(peny) { }
private :
int pembilang, penyebut;
};
The above example produces the same function as the constructor we discussed earlier.
5. CopyConstructor
So far we have learned how a constructor works and how to create an object from a defined constructor. However, imagine if you already have an object x, and then you want to create an object y that has the same data member values and function members. Of course you can declare a new object by calling the same constructor twice:
RationalNumber x(22,7);
RationalNumber y(22,7);
The above command declares 2 objects, namely x and y, each of which has a value of 22 in the numerator variable member and 7 in the denominator variable member. However, you can also shorten the code above with the following command:
RationalNumber x(22,7);
Rational Number y(x);
Here is an example listing for Copy Constructor:
class BilanganRasional
{ public :
BilanganRasional(int pemb, int peny) : pembilang(pemb), penyebut(peny) { }
//CopyConstructor terdapat disini
BilanganRasional(const BilanganRasional& br) : pembilang(br.pembilang), penyebut(br.penyebut) { }
private :
int pembilang, penyebut;
}; void main()
{
BilanganRasional x(22,7);
BilanganRasional y(x);
}
The CopyConstructor declaration is automatically called when you copy object x to object y. Note that x becomes a parameter when we declare object y.
6. Destructor
If we declare a constructor to create an object, then we must also declare a destructor to delete an object. Each class has exactly one destructor. If you do not declare a destructor in a class, then the C++ compiler will automatically create one. We can define a destructor ourselves with the ~ symbol. It is recommended to define your own destructor even though the C++ compiler will automatically declare a destructor when your program is compiled, but by defining your own destructor you have full control over what the destructor of your class does. See the listing below:
class BilanganRasional
{ public :
BilanganRasional() {cout <<"Konstruktor dipanggil\n";}
//Destruktor dari kelas BilanganRasional
~BilanganRasional() {cout <<"Destruktor dipanggil\n";}
private :
int pembilang, penyebut;
}; void main()
{
BilanganRasional x; cout<<"Disini main program\n" ;
}
The above listing will produce the following output:
- Constructor is called
- Here is the main program
- The destructor is called.
From the example above, it can be seen that the constructor is called when object x is created. While the destructor is automatically called by the compiler when object x leaves the main() block. This is in accordance with the rules of object locality in C++.
7. Summary
In this chapter you have learned the concept of OOP, why OOP is called a paradigm and what is the difference between the concept of object-oriented programming and the concept of structured programming. You have also learned to define a class, define member functions and data members and the structure of constructors and destructors of a class. C++ also provides a facility if you want to create a duplicate of an object, namely using the CopyConstructor facility. In addition, you have also learned to declare a constructor with Initialization Lists, so that your constructor declaration becomes more efficient.
Source:
IlmuKomputer.Com
By:
- Michael Lionardi
- lionardi@web.de
Bibliography:
- Erlenkötter, Helmut. C++, Produktorientiertes Programmieren von Anfang an
- http://infocom.cqu.edu.au/Staff/Mike_Turnbull/Home_Page/Lecturetts/Sect101.htm
- http://www.aw-bc.com/catalog/academic/product/0,4096,0201895501-PRE,00.html
- http://www.desy.de/gna/html/cc/Tutorial/node3.htm
- http://www.uni-koeln.de/rrzk/kurse/unterlagen/CPPKURS/
- http://www.uni-koeln.de/rrzk/kurse/unterlagen/CPPKURS/HTML/begriffe.htm
- Hubbard, John R. Ph.D. Schaum's Outlines. Programming with C++.
Understanding Object Oriented Programming
In this session, we will introduce some basic concepts of Object-Oriented objects, and Programming (OOP). Next, we will discuss the concept of classes and how to use classes and their members. Object changes and selection will also be discussed. Now, we will focus on using the classes that have been described in the Java Class library, we will discuss later about how to create your own classes.
OOP revolves around the concept of objects as the basic elements of your program. When we compare it to the real world, we can find several objects around us, such as cars, lions, humans and so on. These objects are characterized by their properties/attributes and behaviors.
For example, a car object has the properties of transmission type, color and manufacture. It has the behavior of turning, braking and accelerating. In the same way we can define the different properties and behaviors of a lion. Take a look at the table below as an example of comparison:
Table 1 Examples of Real-life Objects
With this description, real-world objects can be easily modeled as software objects using properties as data and behaviors as methods. The data here and methods can be used in game programming or interactive software to simulate real-world objects. Examples are as a software object car in a car racing game or a software object lion in an interactive educational software at a zoo for children.
C++ Basic Statements
Substance:
1. STATEMENT BLOCK
2. GOTO STATEMENTS AND LABELED STATEMENTS
3. SEQUENCE STRUCTURE
4. STATEMENT OF SELECTION CONDITIONS
- If statement
- Simple if statement
- If ... else statement
- Nested if statement
- Switch statement
5. REPETITION STATEMENT
- Statement for
- Nested for
- While statement
- do...while statement
C++ Basic Statements
1. Statement Block
A statement block is a collection of program lines enclosed in curly braces. Example:
{
x = 10;
x = x + 1;
}
Above is an example of a statement block that can be treated as a single block or a block of the same level. If an identifier is defined in a statement block, then the identifier is only known within that block and the blocks inside it. The identifier will not be known in blocks outside the definition of the identifier.
Example program:
#include<iostream.h>
#include<conio.h>
/**
*bundet.com
*Pendefnisian variabel dalam blok
*/
void main()
{
int nilai = 350;
cout<<"Isi nilai : "<<nilai<<endl;
{
float nilai = 234.34;
cout<<"Isi nilai : "<<nilai<<endl;
{
char nilai = 'A';
cout<<"Isi nilai : "<<nilai<<endl;
}
cout<<"Isi nilai : "<<nilai<<endl;
}
cout<<"Isi nilai : "<<nilai<<endl;
getch();
}
Execution result:
Defining variables in blocks
In the example program above, there are three value variables defined as int, float and char types. For example, if the value variable of char type does not exist, the block will recognize the value variable of float type.
2. GoTo & Labeled Statements
The goto statement is used to direct program execution to a labeled statement. A labeled statement is a statement that contains a label name and a colon ( .
Form of goto statement and labeled statement:
goto label_name;
label_name:
statement;
Example program:
#include<iostream.h>
#include<conio.h>
/**
*bundet.com
*Contoh program yang mengandung goto dan label
*/
void main()
{
cout<<"Teks ini diawal program"<<endl<<endl;
goto akhir;
cout<<"Saya ngak pernah tampil dilayar..."<<endl<<endl;
tengah:
cout<<"Teks ini ditengah program"<<endl;
cout<<"Kalau Saya tampil dilayar"<<endl;
goto selesai;
akhir:
cout<<"Teks ini diakhir program"<<endl;
cout<<"Lompat ke tengah dulu ya..."<<endl<<endl;
goto tengah;
selesai:
getch();
}
Execution result:
Example program containing goto and label
It is better to minimize the use of goto statements in a program, because it can make our program complicated, making it difficult to program logic and if an error occurs, error tracing will become complicated, especially if the program being created is large.
3. Sequential Structure
In this structure, the program lines will be executed sequentially from top to bottom according to how they are written.
Example 1:
Algorithmic:
Pseudocode Luas_Pesegi_panjang
// Diketahui sebuah pesegi panjang yang memiliki panjang
// dan lebar
//DEKLARASI
int panjang, lebar, luas
//DESKRIPSI
{
read(panjang)
read(lebar)
luas = panjang * lebar
write(luas)
}
Program:
#include<iostream.h>
#include<conio.h>
/**
*bundet.com
*Contoh program menghitung luas pesegi panjang
*/
void main()
{
int panjang, lebar, luas;
cout<<"Masukkan panjang : ";
cin>>panjang;
cout<<"Masukkan lebar : ";
cin>>lebar;
luas = panjang * lebar;
cout<<"Luasnya : "<<luas<<endl;;
getch();
}
Execution result:
Example program to calculate the area of a rectangle
Example 2:
Algorithmic
Pseudocode Isi_Tabung
// Diketahui sebuah tabung yang diketahui jari-jari tabung
// dan tinggi tabung
//DEKLARASI
int jari_jari, tinggi
float luas_lingk, isi_tabung
//DESKRIPSI
{
read(jari_jari)
read(tinggi)
luas_lingk = 3.14 * jari_jari * jari_jari
isi_tabung = luas_lingk * tinggi
write(isi_tabung)
}
Program:
#include<iostream.h>
#include<conio.h>
/**
*bundet.com
*Contoh program menghitung isi tabung
*/
void main()
{
int jari_jari, tinggi;
float luas_lingk, isi_tabung;
cout<<"Masukkan jari-jari tabung : ";
cin>>jari_jari;
cout<<"Masukkan Tinggi tabung : ";
cin>>tinggi;
luas_lingk = 3.14 * jari_jari * jari_jari;
isi_tabung = luas_lingk * tinggi;
cout<<"Isi tabung : "<<isi_tabung<<endl;;
getch();
}
Execution result:
Example program to calculate the contents of a cylinder
4. Condition Selection Statement
If statement
The if statement is used to make decisions based on the conditions being tested. The if form in C++ consists of 3 forms, namely:
a. Simple if statement
In this form, the if statement only has one possible statement that will be executed if the condition being tested is true.
The simple form of an if statement:
if <condition>
statement;
The statement form above <condition> is used to determine the test results, if <condition> is true then the statement will be executed, if <condition> is false then no statement will be executed.
Algorithmic
Pseudocode Kelulusan_Siswa
// Seorang siswa dikatakan lulus jika nilainya >= 60
//DEKLARASI
int nilai_siswa
//DESKRIPSI
{
read(nilai_siswa)
if (nilai_siswa >= 60)
write('Siswa tersebut lulus')
}
Program:
#include<iostream.h>
#include<conio.h>
/**
*bundet.com
*Contoh program yang mengandung pernyataan if sederhana
*/
void main()
{
int nilai_siswa;
cout<<"Masukkan nilai : ";
cin>>nilai_siswa;
if (nilai_siswa >= 60)
cout<<"Siswa tersebut lulus"<<endl;
getch();
}
Execution result:
Simple if statement on student grades
b. If ... else statement
In this form, the if statement has two possible statements that will be executed based on the results of the condition test.
Form of if ... else statement
if <condition>
statement1;
else
statement2;
<condition> is used to determine the test results, if <condition> is true then statement1 will be executed, if <condition> is false then statement2 will be executed.
Example 1
Algorithmic
Pseudocode Kelulusan_Siswa
// Seorang siswa dikatakan lulus jika nilainya >= 60
// jika < 60 maka siswa tidak lulus
//DEKLARASI
int nilai_siswa
//DESKRIPSI
{
read(nilai_siswa)
if (nilai_siswa >= 60)
write('Siswa tersebut lulus')
else
write('Siswa tersebut tidak lulus')
}
Program:
#include<iostream.h>
#include<conio.h>
/**
*bundet.com
*Contoh program yang mengandung pernyataan if...else
*/
void main()
{
int nilai_siswa;
cout<<"Masukkan nilai : ";
cin>>nilai_siswa;
if (nilai_siswa >= 60)
cout<<"Siswa tersebut lulus"<<endl;
else
cout<<"Siswa tersebut tidak lulus"<<endl;
getch();
}
Execution result:
if - else student grades
Example 2
Algorithmic
Pseudocode Pembayaran_Gaji
// Akan dihitung gaji yang diterima pegawai berdasarkan jumlah hari
// kerja dan jumlah jam lembur dengan tarif tertentu
//DEKLARASI
char nama[20]
int jhr_kerja
int jjam_lembur
float upah
float uang_lembur
float trans_lembur
float gaji
//DESKRIPSI
{
read(nama)
read(jhr_kerja)
read(jjam_lembur)
upah = jhr_kerja * 30000
uang_lembur = jjam_lembur * 5000
if (jjam_lembur >= 10)
trans_lembur = 0.1 * uang_lembur
else
trans_lembur = 0
gaji = upah + uang_lembur + trans_lembur
write(upah)
write(uang_lembur)
write(trans_lembur)
write(gaji)
}
Program:
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
/**
*bundet.com
*Contoh program perhitungan pembayaran gaji
*/
void main()
{
char nama[20];
int jhr_kerja;
int jjam_lembur;
float upah;
float uang_lembur;
float trans_lembur;
float gaji;
cout<<"Masukkan Nama : ";
cin>>nama;
cout<<"Masukkan jml hari kerja : ";
cin>>jhr_kerja;
cout<<"Masukkan jml jam lembur : ";
cin>>jjam_lembur;
upah = jhr_kerja * 30000;
uang_lembur = jjam_lembur * 5000;
if (jjam_lembur >= 10)
trans_lembur = 0.1 * uang_lembur;
else
trans_lembur = 0;
gaji = upah + uang_lembur + trans_lembur;
cout<<endl;
cout<<"Jumlah upah : "<<setw(10)<<upah<<endl;
cout<<"Jumlah uang lembur : "<<setw(10)<<uang_lembur<<endl;
cout<<"Transport lembur : "<<setw(10)<<trans_lembur<<endl;
cout<<" -------------- + "<<endl;
cout<<"Gaji yang diterima : "<<setw(10)<<gaji<<endl;
getch();
}
Execution result:
Example of salary calculation program
c. Nested if statement
In this form, the if statement has many possible statements and has many condition tests to carry out the statement.
Form of if ... else statement
if < kondisi1 >
pernyataan1;
else if < kondisi2 >
pernyataan2;
else if < kondisiM >
pernyataanM;
else
pernyataanN;
<condition1> is tested, if the test result is true then statement1 is executed, if the test result of <condition1> is false then <condition2> will be tested, if the test result is true then statement2 will be executed, if the test result of <condition2> is false then <conditionM> will be tested, if the test result is true then statementM will be executed, if the test result of <conditionM> is false then statementN will be executed which is the last alternative if all the tested conditions are not met.
Algorithmic
Pseudocode Konfersi_Nilai
// Diketahui nilai angka seorang siswa yang akan
// dikonfersikan ke nilai huruf
//DEKLARASI
char nama[20]
int nilai_angka
char huruf
//DESKRIPSI
{
read(nama)
read(nilai_angka)
if (nilai_angka >= 80)
huruf = 'A'
else if (nilai_angka >= 70)
huruf = 'B'
else if (nilai_angka >= 60)
huruf = 'C'
else if (nilai_angka >= 50)
huruf = 'D'
else
huruf = 'E'
write(nama)
write(huruf)
}
Program:
#include<iostream.h>
#include<conio.h>
/**
*bundet.com
*Contoh program yang mengandung pernyataan nested if
*/
void main()
{
char nama[20];
int nilai_angka;
char huruf;
cout<<"Masukkan nama : ";
cin>>nama;
cout<<"Masukkan nilai angka : ";
cin>>nilai_angka;
if (nilai_angka >= 80)
huruf = 'A';
else if (nilai_angka >= 70)
huruf = 'B';
else if (nilai_angka >= 70)
huruf = 'C';
else if (nilai_angka >= 70)
huruf = 'D';
else
huruf = 'E';
cout<<endl;
cout<<"Nama : "<<nama<<endl;
cout<<"Nilainya : "<<huruf<<endl;
getch();
}
Execution result:
Example of nested if statement
d. Switch statement
The switch statement is used to execute one statement from several possible choices. The selection in the switch statement is based on the value of the expression and the value of the selector.
Switch statement format:
switch (ungkapan)
{
case ungkapan1 :
pernyataan1;
break;
case ungkapan2 :
pernyataan2;
break;
...
default :
pernyataanX;
}
(expression) in the switch statement can be a constant or variable, while expression1, expression2, can be a constant of type int or char. The process of matching (expression) with expression1, expression2 is done sequentially starting from expression1, expression2 and so on. If it matches, the statement following the case will be executed. Execution will end if a break statement is found. The default statement will be executed if the expression in the case does not match the expression in the switch.
Algorithmic
Pseudocode Menu_Pilihan
// Ditampilkan menu pilihan untuk mengakses perhitungan yang
// akan dilakukan dengan menggunakan switch()
//DEKLARASI
char pilih
int rusuk, isi_kubus, alas, tinggi
float luas_segi3
//DESKRIPSI
{
write("Menu Pilihan")
write("============")
write("1. Isi Kubus")
write("2. Luas Segitiga")
write("3. Selesai")
write("Pilihan anda [1..3] : ")
read(pilih)
switch(pilih)
case 1 :
read(rusuk)
isi_kubus = rusuk * rusuk * rusuk
write(isi_kubus)
case 2 :
read(alas)
read(tinggi)
luas_segi3 = 0.5 * alas * tinggi
write(luas_segi3)
case 3 : break
}
Program:
#include <iostream.h>
#include <conio.h>
/**
*bundet.com
*Contoh penggunaan pernyataan switch
*/
void main()
{
char pilih;
int rusuk, isi_kubus, alas, tinggi;
float luas_segi3;
clrscr();
cout<<"Menu Pilihan"<<endl;
cout<<"============"<<endl;
cout<<"1. Isi Kubus"<<endl;
cout<<"2. Luas Segitiga"<<endl;
cout<<"3. Selesai"<<endl;
cout<<"Pilihan anda [1..3] : ";
cin>>pilih;
switch(pilih)
{
case '1' :
{
cout<<"\nPanjang rusuk : ";
cin>>rusuk;
isi_kubus = rusuk * rusuk * rusuk;
cout<<"Isi kubus : "<<isi_kubus<<endl;
break;
}
case '2' :
{
cout<<"\nPanjang alas segitiga : ";
cin>>alas;
cout<<"Tinggi segitiga : ";
cin>>tinggi;
luas_segi3 = 0.5 * alas * tinggi;
cout<<"Luas segitiga : "<<luas_segi3<<endl;
break;
}
case '3' : break;
}
getch();
}
Execution result:
Example of using switch statement
5. Repetition Statement
a. Statement for
The for statement is used to repeat one or more statements as many times as the conditions are given.
Form of the for statement:
for(ungkapan1;ungkapan2;ungkapan3)
pernyataan;
Information:
ungkakapan1 //merupakan pernyataan inisialisasi awal dari perulangan for
ungkakapan2 //merupakan kondisi yang menentukan pengulangan terhadap pernyataan atau tidak
ungkakapan3 //digunakan sebagai pengatur variabel yang digunakan dalam ungkakapan1
Example 1
Algorithmic
Pseudocode Cetak_Angka_For
// Akan dicetak angka 1 sampai 10 dengan perulangan for
//DEKLARASI
int i
//DESKRIPSI
{
for(i=1; i<=10; i++)
{
write(i)
}
}
Program:
#include <iostream.h>
#include <conio.h>
/**
*bundet.com
*Contoh program perulangan for
*/
void main()
{
for (int i=1; i<=10; i++)
{
cout<<"Isi i = "<<i<<endl;
}
getch();
}
Execution result:
For Loop Example
Example 2
Algorithmic
Pseudocode Cetak_bilangan_genap_for
// Akan dicetak bilangan genap dengan batas akhir diinputkan
//DEKLARASI
int batas_akhir
//DESKRIPSI
{
read(batas_akhir)
for(i=1; i<=batas_akhir; i++)
{
if( i%2 = 0)
write(i)
}
}
Program:
#include <iostream.h>
#include <conio.h>
/**
*bundet.com
*Mencetak bilangan genap perulangan for
*/
void main()
{
int batas_akhir;
cout<<"Jumlah perulangan : ";
cin>>batas_akhir;
for (int i=1; i<=batas_akhir; i++)
{
if ( i % 2 == 0)
cout<<i<<" ";
}
getch();
}
Execution result:
Print even numbers in a for loop
b. Nested for
Nested for is a for statement that is within a for statement (for within for). For example, a triangle consisting of the character * will be formed with nested for.
*
**
***
****
*****
******
Algorithmic
Pseudocode Segitiga_Bintang
// Akan dicetak karakter * yang membentuk bangun segitiga
//DEKLARASI
int tinggi
//DESKRIPSI
{
read(tinggi)
for(i=1;i<=tinggi;i++)
for(j=1;j<=i;j++)
write('*')
endl
}
Program:
#include <iostream.h>
#include <conio.h>
/**
*bundet.com
*Contoh program for bersarang
*/
void main()
{
int tinggi;
cout<<"Tinggi segi3 : ";
cin>>tinggi;
for(int i = 1; i <= tinggi; i++)
{
for (int j = 1; j <= i; j++)
cout<<'*';
cout<<endl;
}
getch();
}
Execution result:
Example of nested for program
c. While statement
The while statement functions to repeat one or more statements as many times as the conditions are given by testing the conditions first before executing the statements.
Form of the while statement:
while (ungkapan)
pernyataan;
In the above form, the statement following while will be executed if the expression being tested is true (equal to 1). In the while statement, the expression will be tested first before the statement is executed, so there is a possibility that the statement part in while will not be executed at all if the expression being tested is false (equal to zero).
Example 1
Algorithmic
Pseudocode Cetak_Angka_While
// Akan dicetak angka 1 sampai 10 dengan perulangan while
//DEKLARASI
int i
//DESKRIPSI
{
i = 1
while(i<=10)
{
write(i)
i++
}
}
Program:
#include <iostream.h>
#include <conio.h>
/**
*bundet.com
*Contoh program perulangan while
*/
void main()
{
int i;
i = 1;
while ( i <= 10)
{
cout<<"Isi i = "<<i<<endl;
i++;
}
getch();
}
Execution result:
Example of a while loop program
Example 2
Algorithmic
Pseudocode Cetak_bilangan_genap_while
// Akan dicetak bilangan genap dengan batas akhir diinputkan
//DEKLARASI
int batas_akhir
//DESKRIPSI
{
read(batas_akhir)
i = 1
for(i; i<=10; i++)
{
if( i%2 = 0)
write(i)
}
}
Program:
#include <iostream.h>
#include <conio.h>
/**
*bundet.com
*Mencetak bilangan genap perulangan while
*/
void main()
{
int batas_akhir;
int i = 1;
cout<<"Jumlah perulangan : ";
cin>>batas_akhir;
while (i<=batas_akhir)
{
if ( i % 2 == 0)
cout<<i<<" ";
i++;
}
getch();
}
Execution result:
Printing even numbers in a while loop
d. do...while statement
The do...while statement functions to repeat one or more statements as many times as the conditions are given by testing the conditions after the statement is executed.
Form of the do...while statement:
do
pernyataan;
while (ungkapan);
The statement following do...while will be executed first, after that the expression in while will be tested, if the expression being tested has a true value (equal to 1) then the statement will be executed again, and so on until the expression being tested has a false value (equal to zero).
Example 1
Algorithmic
Pseudocode Cetak_Angka_do_While
// Akan dicetak angka 1 sampai 10 dengan perulangan do...while
//DEKLARASI
int i
//DESKRIPSI
{
i = 1
do
{
write(i)
i++
} while(i<=10)
}
Program:
#include <iostream.h>
#include <conio.h>
/**
*bundet.com
*Contoh program perulangan do...while
*/
void main()
{
int i;
i = 1;
do
{
cout<<"Isi i = "<<i<<endl;
i++;
}while ( i <= 10);
getch();
}
Execution result:
Example of a do..while loop program
Example 2
Algorithmic
Pseudocode Cetak_bilangan_genap_do_while
// Akan dicetak bilangan genap dengan batas akhir diinputkan
//DEKLARASI
int batas_akhir
//DESKRIPSI
{
read(batas_akhir)
i = 1
do
{
if( i%2 = 0)
write(i)
} while ( i <= batas_akhir)
}
Program:
#include <iostream.h>
#include <conio.h>
/**
*bundet.com
*Mencetak bilangan genap perulangan do...while
*/
void main()
{
int batas_akhir;
int i = 1;
cout<<"Jumlah perulangan : ";
cin>>batas_akhir;
do
{
if ( i % 2 == 0)
cout<<i<<" ";
i++;
}while (i<=batas_akhir);
getch();
}
Execution result:
Printing even numbers in do...while loop
Source:
Algorithm & Programming Module, Compiled by Mr. Eko Riswanto, ST, M.Cs,
Introduction to C++ Algorithms & Programming
We start from the language before C++, namely the C language created by Dennis MacAlistair Ritchie, after that it was developed by Bjarne Stroustrup to become C++, meanwhile the position of the C/C++ language is a middle-level language, namely between low-level languages such as Assembly, namely machine language, and high-level languages such as Java, Pascal, etc., which are closer to human language.
Getting to Know Algorithms and C++
The advantages of the C++ language are:
- Easy to understand because the programming language used is close to human language.
- Has high compatibility across platforms.
To write C++ programming, you can use any text editor application, such as notepad, notepad++, wordpad, Borland C++, etc. While the C++ file itself is written with the extension <file>.cpp (derived from C Plus Plus), then in order for the program to be executed, it must first be compiled with the C++ Compiler, and I use Borland C++ version 4.45 for the compose and compile process.
Position of C++ in the compilation process of forming an Executable program:
Compiling C++ to Executable
Information:
"<file-c++>.cpp" together with "<file-header>.hpp" are combined and translated by the C++ compiler to become "<file-object>.obj" and the construction that forms this file (.obj) is a binary number (0 or 1) so that it can be accepted by the machine.
Then "<file-file>.obj" is linked to "<file-library>.lib" using the linker, so it becomes "<file-executable>.exe"
General Form of C++ Program Structure
#include <nama_file> //disebut sebagai preprosesor atau praprosesor;
void main() //disebut sebagai fungsi penyusun blok (fungsi utama)
{ //sitak pembuka blok pernyataan
pernyataan; //pernyataan untuk program ekses
} //sintak penutup blok pernyataan
Preprocessor
Or also called a preprocessor, namely a function that provides a header file library, and at the time of compilation the preprocessor is executed earlier.
Example:
#include <iostream.h>;
#include <conio.h>;
#include <stdlib.h>;
Void main()
It is the body of a C++ function with an empty () indicating that no arguments are specified so that there are no restrictions in expressing blocks of statements in the body of the void main() function and the function has no return value.
{statement;}
Inside the body of the function, there must be opening and closing curly braces "{}", while inside it is a place to include various statements and then must end with a semicolon ";"
Comment
These comments are optional, in essence comments are used to provide information on program blocks, but usually programmers work around this to disable certain program blocks.
//ini adalah tanda untuk comentar dengan 1 baris...
/*ini adalah tanda untuk membuat komentar
Yang lebih dari 1 baris*/
Simple C++ Program Example
An example of a very simple C++ program can be seen below:
#include
void main()
{
cout << "Hai, Selamat belajar C++";
getch();
}
You can save the above program with the name prak1.cpp. If the program is compiled and executed, the result will be the text on the screen:
Hai, Selamat belajar C++