Simple Application with C++ (SAC)

Figure 9.1 on the side may raise questions. What does it have to do with the chapter title above? But did you know that a spaceship like the one in Figure 9.1 is controlled by a sophisticated computer set, some of whose control applications are written in the C++ programming language.

The application program competency standards using C++ consist of five basic competencies. In the presentation in this book, each basic competency contains objectives, material descriptions, and exercises. A summary is placed at the end of the chapter.

The basic competencies in this chapter are the basics of C++ programming, implementing functions, implementing pointers, implementing Class concepts, and designing Object-oriented applications. Before studying these competencies, remember the operating system, basic programming algorithms, advanced programming algorithms and object-oriented programming concepts in the previous chapters.

At the end, there are practice questions arranged from easy to difficult questions. These practice questions are used to measure the ability of the basic competencies in this chapter. To improve the ability to do the questions better, it is recommended that all questions in this practice can be done at school with teacher guidance or at home.

Objective

After studying this chapter, it is expected that readers will be able to:

  • Explaining the basics of C++ programming
  • Applying functions o Applying pointers
  • Implementing the class concept 
  • Designing object-oriented applications

1. C++ Programming Basics

C++ is a very popular language in the world of software development. Like its predecessor, C, C++ is also included in the middle-level language group. The main purpose of creating C++ is to increase programmer productivity in creating applications. The specialty of C++ is because this language supports OOP (Object Oriented Programming). In addition, there are also many libraries that we can use to speed up application creation. Some of these libraries are available for free on several internet sites.

The program code in C++ that we create cannot be executed directly but must first be compiled with the appropriate C++ compiler. The concept of program compilation and execution in C++ can be described as in Figure 9.2. The program code that we create is called source code and is a plain text file with a file name that has the extension .cpp. This program code is then entered into the PreProcessor. The output of this PreProcessor is a file that will be entered into the Compiler. The Compiler will translate the program code in the file into assembly language. This program code is then processed by the Assembler into object code. If there are no library files involved, then this object code will be executed directly into a file. If there are other libraries involved, the Link Editor will combine the object code and the library to form an EXE file.

We can type C++ codes with any text editor, such as Notepad, Vi, or others. However, it will be easier if we use an IDE (Integrated Development Environment) device that provides an integrated text editor and C++ compiler. Some well-known IDEs include Microsoft Visual Studio, Borland C++, MingGW Developer Studio, and others. In this book, most of the code is written and run using MingGW Developer Studio (Figure 9.3). The license for this IDE is free, meaning we can use it without having to worry about the software's license. You can download this IDE from the internet address  http://www.parinya.ca/

Figure 9.2. Compilation process in C
Figure 9.2. Compilation process in C++

Figure 9.3. MingGW Developer Studio
Figure 9.3. MingGW Developer Studio

2. C++ Program Framework

#include <iostream>  using namespace std;  void nama_fungsi() {   //kode untuk nama_fungsi
    .....;
  }
 // Fungsi utama int main() {
  // kode bagian main/utama
  .....;    return 0;
}

Pay attention to the program code above. The program code consists of several parts as follows:

  • The section for registering certain files or conditions. This section always begins with a # sign.
  • Function definition section. Starts with the keyword void followed by the function name. This section may not exist if we do not create a function.
  • Main() section. In the program code usually starts with int main(). This section must be in every program because it is the main function.
  • The part that starts with the { sign and ends with the } sign, whether in the void or main section, is called a code block.

3. Header File (.h)

Header files, namely files with the extension .h, are files that contain functions and have been compiled previously. This file usually contains certain functions that we will later use in the program code that we create. For example, the iostream.h file has a number of functions to display output and capture input such as cout and cin.

There are two models for writing header files, namely written in full with the extension and not. The first form is the writing model for the old C++ compiler (Example 9.1). The second form is the form supported by the standard C++ Compiler (Example 9.2).

Example 9.1. Writing header files in old C++ compilers

#include <iostream.h>
Int main() {
  ...
  return 0;
}

Example 9.2. Writing header files in a standard C++ compiler

#include <iostream> using namespace std; Int main() {
  ...
  return 0;
}

4. Comments

Comments in C++ can be done in two ways, namely first, with the // sign and placed before the comment and second with the /* sign which is closed with */. The first way is used if the comment consists of only one line, while the second way if the comment is more than one line.

Example 9.3. Comments with marks

// program pertama #include <iostream> int main( ){
cout << "Hello World"; // cetak "Hello World" di layar }

Example 9.4. Comments with /* .. */..

/* Program pertama
Ditulis oleh ARM
Tanggal 17-11-2007 */ #include <iostream> int main( ){
std::cout << "Hello World"; // cetak "Hello World" di layar }

5. Identifier 

Identifiers or names of variables or constants in C++ generally follow the general naming rules explained in Chapter 5. There is one important addition in creating identifiers in C++, namely, they are case sensitive. A variable with the name namaguru is different from the variable NamaGuru.

There are two ways to declare constants. First, by using the preprocessor directive #define. Second, by using the const keyword. Type the following program, then check the results of its execution.

Example 9.5. Declaring constants

#include <iostream> #define potongan 0.1; using namespace std;
 int main() {
  const float hargaPerUnit = 2500;   int jumlahUnit;
  float hargaTotal, hargaDiskon, diskon;   cout << "Masukkan jumlah unit pembelian : ";   cin >> jumlahUnit;
  hargaTotal = jumlahUnit * hargaPerUnit;   diskon = hargaTotal * potongan;   hargaDiskon = hargaTotal - diskon;   cout << "Total harga pembelian = " << hargaTotal << endl;
  cout << "Diskon = " << diskon << endl;   cout << "Harga Diskon = " << hargaDiskon;   return 0; }

In the example above, there are two constants, namely discount and pricePerUnit, each of which is declared in a different way.

Declaring a variable is done by first mentioning its data type followed by the variable name as in example 9.5. In this example, there are several variables that have been defined in advance, namely number of Units, price Total, price Discount and discount. Each with its own data type. For several variables with the same data type, we can combine them in one line with a comma separator. Pay attention to the example above. price Total, price Discount and discount all have the same float data type so they are written together.

You must fully declare all variables or constants that will be used before using them. Otherwise, the program will not be able to be executed.

6. Data type

As explained in Chapter 5, data types depend on what is provided by the programming language. In C++ the basic data types provided can be seen in the following table. If you notice these types are exactly the same as Java. This is because Java actually takes many programming language elements from C++.

Table 9.1. Data types in C++

| Tipe Data | Keterangan                                                                                                              |
|-----------|-------------------------------------------------------------------------------------------------------------------------|
| int       | Tipe data bilangan bulat dengan ukuran 4 bytes                                                                          |
| long      | Tipe data bilangan bulat namun lebih besar dari int.                                                                    |
| float     | Tipe data bilangan pecahan                                                                                              |
| double    | Tipe data bilangan pecahan namun lebih besar dari float                                                                 |
| char      | Tipe data karakter yang berisi huruf, angka atau simbolsimbol (alphanumeric) sepanjang berada pada tanda “ “ atau ‘ ‘.  |
| bool      | Tipe data boolean                                                                                                       |
| short     | Tipe data bilangan bulat dengan ukuran 2 bytes                                                                          |

The available data types in C++ are arrays, structs, and enums. Arrays will be discussed in another section of this chapter. While structs and enums have been discussed in Chapter 5. However, we have not reviewed how to write them. Try typing the program codes in the following examples and then execute them to see the results.

Example 9.6. Using the struct data type

#include <iostream> using namespace std;
 int main() {

  struct Guru {     char* NIP;     char* Nama;     char* Alamat;
  };

  Guru A;

  A.NIP = "132 232 477";
  A.Nama = "Syafiq";
  A.Alamat = "Perum. Dirgantara Permai";

  // Menampilkan nilai yang diisikan ke layar    cout<<A.NIP<<endl;   cout<<A.Nama<<endl;   cout<<A.Alamat<<endl;
   return 0; }

Example 9.6. Use of the enum data type

#include <iostream> using namespace std;

enum JENIS_KELAMIN { Pria, Wanita }; int main() {    struct Guru {     char* NIP;     char* Nama;     JENIS_KELAMIN JK;
  } A;

  A.NIP = "132 232 477";
  A.Nama = "Syafiq";
  A.JK = Pria;
  cout<<"NIP  : "<<A.NIS<<endl;   cout<<"Nama : "<<A.Nama<<endl;   cout<<"Jenis Kelamin  : "<<A.JK<<endl;
   return 0;
}

7. Operator

Just like in VB and Java that you have learned, C++ also provides many operators that we can use to help solve certain problems. In general, there are many similarities between Java and C++ in providing operators. The operators available in C++ can be seen in Table 9.2.

Table 9.2. Operators in C++

| Jenis Operator      | Fungsi                                            | Contoh                                   |
|---------------------|---------------------------------------------------|------------------------------------------|
| Operator assignment |                                                   |                                          |
| =                   | Memasukkan (assign) nilai ke dalam suatu variabel | C = 5                                    |
| Operator unary      |                                                   |                                          |
| +                   | Membuat nilai positif                             | X = +10                                  |
| -                   | Membuat nilai negatif                             | Y = -12                                  |
| ++                  | Menaikkan nilai variabel satu nilai               | ++C (pre-increment) C++ (post-increment) |
| --                  | Menurunkan nilai variabel satu nilai              | --C (pre-increment) C-- (post-increment) |
| Operator Binary     |                                                   |                                          |
| +                   | Penjumlahan                                       | 3 + 5 = 8                                |
| -                   | Pengurangan                                       | 72 = 5                                |
| *                   | Perkalian                                         | 5 * 2 = 10                               |
| /                   | Pembagian                                         | 6 / 3 = 2                                |
| %                   | Sisa hasil bagi (modulus)                         | 5 / 2 = 1                                |
| Operator Logika     |                                                   |                                          |
| &&                  | AND                                               | 1 && 1 = 1                               |
| \|\|                | OR                                                | 1 \|\| 0 = 1                             |
| !                   | NOT                                               | !0 = 1                                   |
| Operator Relasional |                                                   |                                          |
| >                   | Lebih besar                                       | (5 > 4) = 1                              |
| <                   | Lebih kecil                                       | (5 < 4) = 0                              |
| >=                  | Lebih besar atau sama dengan                      | (4 >= 4) = 1                             |
| <=                  | Lebih kecil atau sama dengan                      | (5 <= 4) = 0                             |
| ==                  | Sama dengan                                       | (5 ==4) = 0                              |
| !=                  | Tidak sama dengan                                 | (5 != 4) = 1                             |
| Operator Bitwise    |                                                   |                                          |
| &                   | AND                                               | 1 & 0 = 0                                |
| \|                  | OR                                                | 1 \| 0 = 1                               |
| ^                   | XOR                                               | 1 ^ 1 = 0                                |
| ~                   | NOT                                               | ~0 = 1                                   |
| Operator Ternary    |                                                   |                                          |
| ?:                  | Digunakan operand jika melibatkan tiga            | 1 & 0 = 0                                |

8. Program Control Structure 

The program control structure in C++ is generally the same as VB and Java that you have learned. What is different is the writing syntax. For branching, C++ provides the if (without then) and switch ... case commands. While for repetition, C++ provides the for, while, and do-while commands. In addition, repetition also provides break and continue facilities. The following will be presented sequentially the program codes to implement the control structure. Type the codes, then run them and observe what happens.

Example 9.7. Using a simple if branching structure

#include <iostream> using namespace std;
 int main() {   int bil;
  cout<<"Masukkan sebuah bilangan bulat : ";    cin>>bil;

  // Melakukan pengecekan bilangan dengan operator modulus    if (bil % 2 == 0) {
    cout<<bil<<" adalah bilangan genap" << endl;
  } else {
    cout<<bil<<" adalah bilangan ganjil" << endl;
  }    return 0; }

In the example above we use if to check whether a number is even or odd. The operator we use is modulus (%). Note how the if and else structures are written.

Example 9.8. Using the three-conditional if branching structure

#include <iostream> using namespace std; int main() {   int bil;
  cout<<"Masukkan sebuah bilangan bulat : ";    cin>>bil;    if (bil > 0) {
    cout<<bil<<" adalah bilangan POSITIF";
  } else if (bil < 0) {
    cout<<bil<<" adalah bilangan NEGATIF";
  } else {
    cout<<"ini bilangan NOL";
  }    return 0; }

Example 9.8. is an extension of Example 9.7. The selection structure is expanded into three conditions by adding else. If the selection is more than three conditions or many, C++ provides the switch ... case command to facilitate the selection process. Consider the following example.

Example 9.9. Using a branching structure with switch ... case

#include <iostream> using namespace std;
 int main() {   int bil;
  cout<<"Masukkan sebuah bilangan (1 s/d 5) : ";   cin>>bil;    switch (bil) {
     case 1 : cout<<"Bilangan anda adalah : SATU";                break;
     case 2 : cout<<"Bilangan anda adalah : DUA";               break;
     case 3 : cout<<"Bilangan anda adalah : TIGA";               break;
     case 4 : cout<<"Bilangan anda adalah : EMPAT";               break;
     case 5 : cout<<"Bilangan anda adalah : LIMA";               break;
     default : cout<<"Anda memasukkan di luar batas";
  }    return 0; }

Example 9.9. is an example of branching with switches to convert from numbers to text. Note how the switches and cases are written.

As in Java, a for loop is used when we know exactly how many iterations will be performed. Here is an example of using a for loop.

Example 9.10. Using the repetition structure with for

#include <iostream> using namespace std;
 int main() {   int C, J;
  cout<<"Cetak angka dari kecil ke besar :"<<endl;   for (C=0; C<10; C+3) {     cout<<C+1<<endl;
  }    cout<<endl;
  cout<<"Cetak angka dari besar ke kecil"<<endl;   for (J=10; J>0; J--) {     cout<<J<<endl;
  }    return 0; }

Example 9.10. is an example of using for for a simple case. There are two for loops above, namely printing numbers from 1 to 10 and from 10 to 1. Note the use of increment ++ and --. The way of writing above is very similar to the writing in Java that you have learned before. In the following example 9.11, the for loop is developed to be a little more complicated by implementing nested for.

Example 9.11. Using a loop structure with nested for loops.

#include <iostream> using namespace std;
 int main() {   for (int j=1; j<=4; j++) {     for (int k=1; k<=3; k++) {     cout<<k+j<<' ';
    }     cout<<endl;
  }    return 0; }

There are two loops in example 9.11. The first one uses j as the counter variable. The second one uses the counter variable k nested inside the j loop. What do you think the output of the program code above is?

The use of while in loops is not much different from what you have learned in Java and VB. Consider examples 9.12 and 9.13 below.

Example 9.12. Using a simple while loop structure

#include <iostream> using namespace std;
 int main() {
  int C;
  C = 1;   // inisialisasi nilai C
   while (C<10) {
     cout<<"Saya tidak nakal lagi"<<endl;      C++;   // increment
  }    return 0; }

Example 9.13. Using a loop structure with nested while loops.

#include <iostream> using namespace std;
 int main() {
  int x, y;
x = 1;   //inisialisasi variabel x
   while (x<=4){
y = 1;   //inisialisasi variabel y     while (y<=3){       cout<<y+x<<' ';       y++;       }     cout<<endl;     x++;
  }    return 0;
}

Look at example 9.12 above, what do you think the output of the program code is. Try comparing it with example 9.11. Try moving the initialization for the y variable. Place it after the initialization of the x variable. What is the result?

The next form of repetition in C++ is by using do-while. Slightly different from while, the checking condition in do-while is placed at the end of the loop body. Example 9.14 provides an illustration of how do-while is used in C++.

Example 9.14. Using the repetition structure with do-while

#include <iostream> using namespace std;
 int main() {   int J = 5;   int K;    do {      K = 1;      do {
       cout<<K*J<<' ';
       K++;      } while (K <= J);      cout<<endl;      J--;
  } while (J >= 1);

  return 0; }

Example 9.14 appears to display a fairly complicated program code. However, if we look closely, this is a program code with nested do while loops. Pay attention to the way the program is written and the flow of logic. The outer dowhile uses the counter variable J and this is a loop from large to small (note that J is initialized with the value 10 and the condition in while J >= 1). While the inner do-while has a counter variable K with a loop from small to large. What are the results of executing the program code above? Pay attention to the output below. Try to trace the program code so that you really understand why the program output can be like this.

5 10 15 20 25
4 8 12 16
3 6 9
2 4
1

9. Input/Output

Up to this point, you have practiced quite a lot of C++ programming code. However, we have not even studied the input/output statements in C++. Actually, if you are observant, you have indirectly studied the input and output statements. The cout and cin commands that you have used are the most frequently used input/output statements.

Both cout and cin commands are classified as streams that are included in the iostream class. That is why every time we want to use these two commands we have to call the iostream header file at the beginning of the program.

Stream is a logic device that is useful for getting or giving information. Stream is related to hardware such as keyboard, monitor screen, printer through I/O system.

The cin command is a stream for standard input. This command will record what we type from the keyboard. Note how it is written in example 9.15.

Example 9.15. Use of cin and cout

#include <iostream> using namespace std;
 int main() {   int bil1, bil2;

  //cin bagian satu
  cout<<"Masukkan bilangan pertama : ";    cin>>bil1;
  cout<<"Masukkan bilangan kedua : ";    cin>>bil2;
  cout<<"Hasil kali kedua bilangan = "<<bil1*bil2<<endl;

  //cin bagian dua
  cout<<"Masukkan dua buah bilangan : ";    cin>>bil1>>bil2;
  cout<<"Hasil kali kedua bilangan = "<<bil1*bil2<<endl;
   return 0; }

The cin command can be used to insert data one by one as in example 9.15 (see the section below //cin part one) or to insert data directly sequentially (see the section below //cin part two). The cin command must be followed by the >> operator.

The cout command is a command to perform standard output on the monitor screen. The cout command must be followed by the operator <<. Consider example 9.15 above. cout can be used to directly print characters (marked with " and ending with ") or the contents of variables. Like cin, cout can be used for output one by one or sequentially at once. In the example above, the endl statement is a statement to print a new line.

Even-Odd Calculation & Explanation

Questions asked by Surya Guntur

Previously, thank you very much to the Admin for allowing me to join here.

My visit not only wanted to learn but also brought questions, just in case someone was willing to help... regarding "How to calculate odd and even numbers while also providing explanations?" I've tried fiddling with the coding but haven't found it yet...

The output image is like this:

--------- Perhitungan Genab Ganjil------------
-----------------------------------------------------------
Nilai 1                Keterangan
-----------------------------------------------------------
1                      Ganjil
2                      Genab
3                      Ganjil
4                      Genab
[...]
9                      Ganjil
10                     Genab

Please explain, Master... Respectful greetings from a Newbie... Thanks in advance...

Answer

The display as above explains the program below, I hope, this little example can help Mr. Surya in understanding the concept of finding odd-even, and I hope with this handful of sources Mr. Surya can develop his creativity, thank you and happy learning.

Source code

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

void main(){
int input;
for (int i=10; input!=0; i--){
//menggunakan modulus (%) untuk mengetahui sisa pembagian, sehingga dapat digunakan untuk menentukan apakah nilai itu genap atau ganjil

cout<<"masukan bilangan genap : ";
cin>>input;
if (input % 2 ==0){
cout<<"genap"<<endl;

Post a Comment

Previous Next

نموذج الاتصال