Introduction

Before learning the C/C++ programming language, it is generally recommended to study a few foundational concepts that will facilitate your understanding of C/C++.

Overview

At the outset, students are introduced to small programs that contain the building blocks of programming: expressions, assignments, conditionals, and loops. In reality, a program is a mixture of these building elements. Students need to synthesize and integrate their knowledge by “deconstructing” sample programs, extracting elements for adaptation, and then reconstructing a complete program to solve the problems they face.

This embodies the essence of Computational Thinking. Problem decomposition is done by breaking a program down into small syntactical elements to form a cohesive solution. Patterns are expected to emerge from the basic syntactical elements learned through small programs, leading to solution patterns for larger problem types. Based on this approach, “Starting Basic Programming with C/C++” consists of several modules:

  • Introduction: Covers the history of C/C++, example applications, and relevant terminology, including recommended IDEs.
  • Small Programs in C/C++: Introduces C/C++ through the simplest program, “Hello World.”
  • Initialization and Assignment: Explains variables and basic data types like integers, real numbers, and characters/strings, as well as the two ways to assign values to variables: initialization and assignment.
  • Constants: Introduces the concept of constants, which are variables that cannot be changed, and distinguishes between constants and variables.
  • Input/Output: Teaches how to read and write values to variables.
  • Simple Operations in C/C++: Covers operations in C/C++, including arithmetic, boolean, comparisons, etc.
  • Conditional Statements: Introduces conditional instructions to control the program flow.
  • Loops: Introduces looping constructs for repeating instructions, such as for, while-do, do-while, and for.
  • Arrays: Introduces arrays for storing multiple values in a matrix format.
  • Subprograms: Introduces functions and procedures as abstractions of computational processes that can be called by a program.
  • Conclusion: Tests understanding of C/C++ through exercises that reinforce concepts in a simple program, including computation operations, conditional statements, loops, arrays, and functions.

Programming algorithm learning will emphasize practice, with a class composition of 20% theory and 80% practice, ensuring more time is spent writing code than on theoretical concepts.

Introduction to C/C++

C (pronounced /si:/ like the letter C in English) is a general-purpose, imperative programming language that supports structured and recursive programming. C uses static typing, meaning data types must be defined manually.

General-purpose means it can be used for various applications, such as CLI applications, desktop software, operating systems, IoT, games, and more. The imperative paradigm means programming in C is done using statements or commands. A programming paradigm is a method or technique for writing code and can be thought of as a perspective for solving problems. Since it uses the imperative paradigm, C also supports structural and procedural paradigms. However, C does not support Object-Oriented Programming (OOP). For OOP, it is advisable to use C++ since it includes features like classes, objects, and interfaces.

The C language was developed by Dennis M. Ritchie and Brian W. Kernighan in the early 1970s. It evolved in the UNIX environment (approximately 90% of UNIX operating systems are written in C). There are several standards for C, which serve as guidelines for writing the language. Some of these standards include:

• Kernighan & Ritchie (K&R) Definition
• ANSI-C (X3.159 - 1989) [Standard used for learning]
• AT&T Definition (for the C superset, C++)
• GNU Coding Standards

Examples of PC versions include:
• Lattice C
• Microsoft C/Microsoft QuickC
• Turbo C/Borland C++

C is widely used for
• Creating operating systems and system programs.
• Programming that is “close” to hardware (e.g., for equipment control and embedded system).
• Developing toolkits.
• Writing application programs.

The advantages of C, making it a preferred choice for such applications, include its ability to create compact, efficient code without sacrificing readability (unlike assembly language, which is efficient but hard to read, or other high-level languages that are readable but not efficient). However, it cannot be denied that C code can be more difficult to read compared to other high-level languages due to its compactness.

In 1986, a C superset (compatible with C but equipped with object-oriented programming capabilities) was developed by Bjarne Stroustrup, known as C++ (C with Classes). As the name suggests, the “++” symbol in C indicates an increment from C. Essentially, C++ is similar to C but has more features, such as classes, objects, interfaces, etc. This is why it is called C++ (read as “C plus plus”).

Introduction to Basic Programming Algorithms

To start understanding programming algorithms and writing code, we need to grasp some fundamental concepts to facilitate easier learning and engagement with future material.

  1. How to Write and Read Code
    When writing programs, the first thing to consider is how to read and write code. This is similar to our general reading and writing practices. In programming, the concept is to read and write code from top to bottom. Sometimes this is overlooked, leading to serious errors in the code, due to improper sequencing that fails to follow the top-down writing principle. The computer reads our code sequentially from top to bottom, so if it’s not arranged correctly, it can result in significant errors. This seemingly simple point is crucial; hence, a basic understanding of code writing is essential.

  2. Importance of Documentation
    When learning a programming language, it’s important to read the official documentation to minimize potential mistakes and errors. Each programming language has different standards for its syntax; thus, documentation is vital and should be consulted. You can find the official documentation for any programming language you study online.

  3. Indentation & Program Blocks
    Indentation refers to starting text with empty spaces between the text and the margin. A tab is used for indentation, with a tab typically equaling 4 spaces. Indentation is commonly used within program blocks. Different programmers around the world may use varying indentation standards depending on their project guidelines. In individual projects, it’s common to see programmers using 2-space indentation, while in cases like the Linux kernel project initiated by Linus Torvalds, an 8-space standard is used for better code readability. The most common practice, however, is to use 4 spaces for indentation, aligning with the tab character.

    In programming languages, a program block is an approach that allows users to create programs by assembling interrelated blocks of code. A program block generally begins with an opening curly brace “{“ and ends with a closing curly brace “}”. In some programming languages, like Python, curly braces do not represent program blocks; instead, another symbol like “:” is used.

    To declare a program block (from { to }), it can be demonstrated as follows, with syntax explained after the indentation:

    1
    2
    3
    4
    5
    for (i = 0; i < MSG_MAX; i++)
    { // Entering Program Block
    [Tab]<Code>
    [Tab]<Code>
    } // Ending Program Block

    Here’s an example of a nested program block:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    bool fs_tf_analyzeFileUpCommand(char *cmd, int size)
    { // Entering Program Block 1
    [Tab]int i;
    [Tab]for (i = 0; i < size; i++)
    [Tab]{
    [Tab][Tab]<Code>
    [Tab][Tab]<Code>
    [Tab]} // Ending Program Block 2
    [Tab]return OK_CMD;
    } // Ending Program Block 1
  4. Comments
    In writing code, it’s sometimes necessary to add comments in specific sections for clarification. Why is this important? Consider if you’re working in a team on a complex program and you only write code without any comments. How will your teammates understand your work? It would complicate their ability to continue from where you left off. This illustrates the importance of comments in programming. Comments can be single-line or multi-line. A single-line comment typically starts with “//“ and has no ending. For multi-line comments, they usually begin with “/“ and end with “/“. Other programming languages, like Python, may use a different syntax, such as “#” for single-line comments. Therefore, when learning a new programming language, be sure to read its documentation regarding comment syntax.

    Here’s an example of comment usage:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    if (filePtr == null)
    {
    // Single-line comment

    /* Comment
    More
    Than
    One Line */
    return ERR_CMD;
    }

    Note: Single-line comments “//“ are not applicable in C, so to create comments in C, use “/ /“. Single-line comments “//“ can still be used in C++.

  5. Naming Conventions
    When learning a programming language, it’s important to pay attention to the rules for naming variables, functions, classes, etc. Naming conventions are largely similar across languages and help make code easier to read. Here are three key points to consider when naming:

    • Choose names that distinguish different data types.
    • Use data type keywords as part of the naming convention to indicate the contents of a variable/function/class after declaration, which also minimizes errors.
    • Use names that are easily recognizable and understandable (avoid abbreviations that only you and your close associates would know, like x = 5).

    Here are some additional important guidelines for naming:

    • Use these naming conventions as a general reference and adjust them as necessary for the programming language you are using, as each language has its own naming rules (Read the Official Documentation!).
    • Avoid naming anything with keywords (if, else, for, while, etc.), as this will cause errors and make the program unreadable.
    • Refrain from using initials, such as single letters for variable/function/class names in complex programs, as this can be confusing and hard to differentiate.
    • Do not start variable/function/class names with numbers, as the compiler will interpret them as values rather than names. If your variable/function/class requires numbers, those should not be at the beginning.
    • Avoid generic names like “data” for variables/functions/classes. Naming something “data” doesn’t clarify anything and will confuse you when maintaining code or adding new features later. Instead, use names that describe the value of the variable/function/class itself.
    • Variables in languages like JavaScript should start with a letter or an underscore. You cannot create a variable starting with a number or using symbols other than the underscore.
    • Variable/function/class names cannot contain spaces. If a name consists of more than two words, use camelCase (e.g., FirstName, LastName, CatName) or underscores as a substitute for spaces (e.g., First_Name, Last_Name).
    • Variable/function/class names should not contain special characters (!,/,+,*,=, etc.).
    • Avoid using all capital letters for variable names (e.g., NAME, PLACE, LIFE) as these are typically reserved for constants (values that cannot change).

    Here are some rules for creating functions/classes:

    • Avoid using too many parameters in a function unless necessary. If there are too many arguments, it becomes difficult to test or use. If more than three function arguments are needed, consider consolidating or discussing this with your team. Instead of adding numerous function parameters, utilize objects as parameters.
    • Make each function perform a single task. Functions that do too many things can be hard to compile and test. Functions with multiple responsibilities also lack a clear purpose. When a function does more than one thing, try breaking it down so that each function truly performs one task. This also results in cleaner and more readable code.
    • Function names should represent their purpose. Ensure the name reflects the intent or task of the function. This helps other developers/programmers easily understand the purpose of the function you create.
    • Create functions to avoid code duplication. If you find yourself frequently writing repetitive code, you should pay attention to that code. Repeated code is a strong candidate for being made into a function, allowing it to be reused simply by calling the function.
  6. Running Programs
    To run our code, we first need to determine whether the programming language we are learning is executed using a compiler or an interpreter.

    • Compiler: A compiler translates code from a high-level programming language into machine code before the program is executed. The compiler reads the entire file and processes it all at once, outputting the result (whether it runs successfully or produces errors) even if there are errors in the code. Examples of programming languages that use compilers are C/C++ and Java.
    • Interpreter: An interpreter translates code written in a high-level programming language into machine code line by line as the code is executed. The interpreter reads each line, and if an error occurs, the program immediately stops at the line where the error happened. An example of a programming language that uses an interpreter is Python.
  7. Types of Errors
    It wouldn’t be complete without discussing errors in programming algorithms. An error is a mistake that occurs in the writing of code. Generally, there are many types of errors, depending on the programming language. Here are some types of errors that you may encounter when learning a programming language:

    • Logical Error: This is the hardest type of error to detect. It occurs not due to a syntax error or a runtime issue, but because of a mistake in the algorithm written by the programmer. When the logic is wrong, the output will also be incorrect. Detecting logical errors can be quite difficult and time-consuming. Most logical errors arise from calculation mistakes or using the wrong variables. Typically, a logical error will not cause the program to stop completely; the program can still run normally but will not function as intended.
    • Syntax Error: One of the most common types of errors in programming is the syntax error. This error occurs when there is a typo in a keyword or an issue with the structure of the code. When a syntax error occurs, the code will not run correctly because the computer cannot understand it. Fixing this type of error usually just requires careful checking for typos.
    • Runtime Error: This type of error occurs while a program is running. There are several causes for runtime errors, such as input errors, calculation mistakes, and output problems. When a runtime error occurs, there is a significant potential for the program to crash. To fix this type of error, the programmer must go back to the development phase to identify the issue.
    • Compilation Error: This error occurs during the process where code written in a high-level language is converted into a machine-readable format. Various types of errors, such as syntax errors, can arise during this process. Sometimes, even if the syntax is correct, a compilation error may still occur due to issues with the compiler itself. However, don’t worry; this type of error can be fixed during the development phase.
    • Interfacing Error: This type of error is likely to occur due to incompatibility between the software program and the hardware interface being used. In the case of web applications, it often arises from incorrect use of web protocols.
    • Arithmetic Error: This is a type of error that falls under logical errors, but it specifically involves mathematical calculations rather than syntax errors. It generally occurs when the computer cannot perform a calculation as instructed by the programmer. For example, trying to divide by zero can lead to an error that prevents the program from running correctly. To address this, you can:
      • Understand basic mathematical operations.
      • Avoid mistakes with parentheses or the order of operations.
      • Use negative numbers in calculations.
      • Implement error handling methods such as try, catch, except, etc.
    • Resource Error: This type of error occurs when the value of a variable exceeds the maximum limit that the programming environment can handle. A program will use a certain amount of resources provided by the computer to run. When the program requires more resources than the computer can provide, it leads to a resource error. To mitigate this, you can use load-testing applications to understand what happens when you run the same program simultaneously multiple times.
    • Semantic Error: This type of error is similar to a logical error; however, the difference is that a logical error produces incorrect data, while a semantic error produces something that is meaningless.

    Errors mentioned above can often be avoided if you are more meticulous and plan well during the code-writing phase.

Flowchart & Pseudocode

Flowcharts and pseudocode are fundamental tools for learning algorithms and basic programming before writing actual code. To understand the flow of a program, it’s important to visualize how it operates. To simplify this, you can represent it using a flowchart. Another method, besides drawing a flowchart, is to write pseudocode, which consists of statements that represent the code you will write later. For example:

Pseudocode:

1
2
3
4
5
PRINT my name

PRINT my origin

PRINT my job

C/C++ Code:

1
2
3
4
5
6
7
8
#include <iostream>

int main() {
// Write C++ code here
printf("Zulma\n");
printf("Bintaro\n");
printf("Software Quality Assurance\n");
}

First Program

How was that? Quite easy, right? Now try converting the following pseudocode into a program written in C/C++:

1
2
3
4
5
6
7
8
9
PRINT your name

PRINT your origin

PRINT your job

PRINT your country of origin

PRINT something you like