C++ Programming: An Introduction

C++ is a versatile programming language that empowers developers to craft robust and efficient software solutions. Its object-oriented paradigm enables code reusability, reducing development time and costs. Widely used in game development, operating systems, and embedded systems, C++ stands as a cornerstone of modern programming.

C C++: Python, Git, Windows, and many more programs employ the fundamental programming language C. Learning C can facilitate learning other languages. Dennis Ritchie was the creator of C. C++ is essentially a more feature-rich version of C, designed to simplify tasks like inheritance and encapsulation. Without modification, C++ can run most C programs. It’s safer than C and more structured. Due to their flexibility and power, C and C++ are widely used in software development.

Introduction to C++

Dennis Ritchie created the programming language C in 1972 for use in creating computer systems. It is helpful for many applications, including creating databases and operating systems. Knowing C is like knowing programming fundamentals; it makes learning other languages easier.

C++ is essentially Bjarne Stroustrup’s sophisticated version of C. It works well for creating operating systems, games, and applications. It manages computer resources. Within the realm of programming, both C and C++ hold significance. You can learn about computer memory using C, and you can create more complicated software with C++.

What is C++?

C++ is a multifaceted programming language that excels in various domains, from game development to operating systems. Its object-oriented design promotes code reusability and modularity, while its control over hardware resources and memory ensures high performance. C++’s versatility has cemented its place as a cornerstone of modern programming, shaping the development of complex applications across diverse sectors.

Bjarne Stroustrup created C++ in 1979 as a part of his doctoral research. It is an expanded and improved version of the C programming language. Since the current programming languages were unsuitable for large-scale projects, Bjarne created “C with Classes,” which was eventually titled C++. Since C was already a general-purpose language with quick processing speeds, he utilized it to create what he desired.

The general-purpose programming language C++ is intelligent, practical, and versatile. Intermediate-level programmers are best suited for this free-form, statically typed, multi-paradigm, and usually compiled programming language. However, those who begin learning to program using C++ will discover that they may pick up the programming fundamentals fast, which will help them in future endeavors. 

Also Check: C Syllabus Foundation, Important Topics, Course – PW Skills 

Why Use C++?

C++ boasts several advantages that make it a popular choice among developers:

  • C++ is Prevalent for OS, GUIs, and embedded systems.
  • Object-oriented for structured code and reusability.
  • Cross-platform app development.
  • Versatile, it facilitates transitioning between languages.
  • C++ is powerful yet enjoyable to learn.

Difference Between C and C++

While C++ is an extension of the C language, there is a fundamental difference between the two. C++ introduces the concept of classes and objects, which C does not support. This object-oriented approach is a significant differentiator and one of the key features of C++.

Getting Started with C++

To begin with C, you require two essentials:

  • A text editor (e.g., Notepad) for writing C code.
  • A compiler (e.g., GCC) to translate C code into a computer-readable language.

C++ Install IDE

IDEs (Integrated Development Environments) serve for code editing and compilation. Notable free IDEs, such as Code::Blocks, Eclipse, and Visual Studio, enable C code editing and debugging.

C++ Quick Start

Let’s create your first C++ program using Codeblocks, a commonly used IDE:

  1. Open Codeblocks and create a new empty file named myfirstprogram.cpp. 
  2. Write the following C++ code:

myfirstprogram.cpp

#include <iostream>

Using namespace std;

int main() {

  cout << “Hello World!”;

  return 0;

}

  1. Save the file as myfirstprogram.cpp (File > Save File as)
  2. Build and run the program from within Codeblocks.

You should see the output: “Hello World!” and some execution details. 

In Codeblocks, it should look like this:

Next, to run the application, select Build > Build and Run. The outcome will be like this:

Hello World!

Process returned 0 (0x0) execution time: 0.011 s

Press any key to continue.

C++ Syntax

Here’s a breakdown of the code example to help you understand it better:

Example: 

#include <iostream>

using namespace std;

int main() {

  cout << “Hello World!”;

  return 0;

}

C++ code is structured in a specific way. Let’s break down the code from the example above:

Here’s a summary of what each part of the code does:

  1. Line 1 (#include <iostream>): This line includes the <iostream> header file, which provides functionality for input and output operations. It allows you to use objects like cout for printing text to the console.
  2. Line 2 (using namespace std;): This line specifies that you want to use names for objects and functions from the std (standard) namespace. In this case, it allows you to use cout without prefixing it with std::. The std namespace contains various standard C++ libraries.
  3. Line 3: A blank line, which is used for better code readability. C++ ignores whitespace, but using it helps make the code more organized and understandable.
  4. Line 4 (int main()): This line defines the primary function, which serves as the entry point for the C++ program. Any code enclosed within the curly braces {} will be executed when the program runs.
  5. Line 5 (cout << “Hello World!”;): In this line, the cout object (pronounced “see-out”) is used in combination with the insertion operator (<<) to print the text “Hello World!” to the console. The semicolon; at the end indicates the end of the statement. This is the part of the code that performs the actual output.
  6. Line 6 (return 0;): This line marks the end of the primary function and returns an integer value of 0. In C++, returning 0 from the main typically indicates a successful program execution. The return statement is used to exit the primary function.
  7. Line 7 (}): The closing curly brace marks the end of the primary function. It must be included to terminate the function and the program correctly.

Also Check: HTML Vs. HTML5 In Web Development

Omitting Namespace

While using namespace std line is common, you may encounter C++ programs that omit it. In such cases, you need to use the std keyword followed by the :: operator for objects from the standard library:

Example

#include <iostream>

int main() {

  std::cout << “Hello World!”;

  return 0;

}

C++ Output 

  • Print Text

In C++, you can use the cout object from the <iostream> library along with the << operator to print text and values to the standard output (typically the console). The cout object allows you to display text and variables, and you can use as many cout objects as you need in your program.

In the first example, you have a simple C++ program that uses cout to print the text “Hello World!” to the console:

Example

#include <iostream>

using namespace std;

int main() {

  cout << “Hello World!”;

  return 0;

}

When you run this program, it will display “Hello World!” in the console.

In the second example, you continue to use cout to print text, but this time, you have multiple cout statements one after the other:

Example

#include <iostream>

using namespace std;

int main() {

  cout << “Hello World!”;

  cout << “I am learning C++”;

  return 0;

}

  • C++ New Lines

In C++, multiple ways exist to insert new lines in your output. As mentioned, you can use the “\n” character and the “endl” manipulator to achieve this. Here’s a brief explanation of each:

  1. Using “\n”: The “\n” character is an escape sequence representing a newline character. When you include “\n” in a string, it tells the program to start a new line.

Example

#include <iostream>

using namespace std;

int main() {

  cout << “Hello World! \n;

  cout << “I am learning C++”;

  return 0;

}

  • In this example, the “\n” is used to start a new line after “Hello World!”.
  • You can also use multiple “\n” characters to create blank lines:

Example

#include <iostream>

using namespace std;

int main() {

  cout << “Hello World! \n\n;

  cout << “I am learning C++”;

  return 0;

}

  • Using “endl”: “endl” is a C++ stream manipulator that not only inserts a newline character but also flushes the output buffer, ensuring that the output is written immediately to the screen. This can be useful when you need to ensure immediate output.

Example

#include <iostream>

using namespace std;

int main() {

  cout << “Hello World!” << endl;

  cout << “I am learning C++”;

  return 0;

}

C++ Comments

Comments in C++ provide explanations or documentation within the code, making it more understandable for developers and readers. They also serve the purpose of temporarily turning off certain sections of code during testing or debugging.

Here’s a summary of the two types of comments you mentioned:

  • Single-line Comments:
  • Single-line comments are used for short explanations or notes.
  • They start with two forward slashes (//).
  • Anything after // on the same line is treated as a comment and is not executed by the compiler.
  • They often clarify code on the same line or provide context for a specific statement.

Example: uses a single-line comment before a line of code:

// This is a comment

cout << “Hello World!”;

Example uses a single-line comment at the end of a line of code:

Example

cout << “Hello World!”; // This is a comment
  • Multi-line Comments:
  • Multi-line comments are used for longer explanations or to comment on multiple lines of code.
  • They start with /* and end with */.
  • Everything between /* and */ is considered a comment and is not executed by the compiler.
  • Multi-line comments are typically used when you need to provide detailed documentation or temporarily disable a block of code.

Example

/* The code below will print the words Hello World!

to the screen, and it is amazing */

cout << “Hello World!”;

C++ Variables

  • Variable Types:
  • Int: Stores integers (whole numbers) without decimals.
  • Double: Stores floating-point numbers with decimals.
  • Char: Stores single characters enclosed in single quotes.
  • String: Stores text as a sequence of characters enclosed in double quotes.
  • bool: Stores boolean values with two states, true or false.
  • Declaring (Creating) Variables:

To create a variable, you specify the type and assign it a value using the following syntax:

Syntax

type variableName = value;
  • ‘type’ represents one of the C++ types (e.g., int, double).
  • ‘variableName’ is the name of the variable.
  • ‘value’ is the initial value assigned to the variable.
  • Example:

You can declare and assign a value to a variable like this:

Example

Create a variable called myNum of type int and assign it the value 15:

int myNum = 15;

cout << myNum;

This example creates an integer variable called myNum with an initial value of 15 and then prints its value.

  • Assigning Values Later:

You can also declare a variable without assigning a value initially and assign it later in your code:

Example

int myNum;

myNum = 15;

cout << myNum;

  • Variable Modification:

If you assign a new value to an existing variable, it will overwrite the previous value:

Example

int myNum = 15;  // myNum is 15

myNum = 10;  // Now myNum is 10

cout << myNum;  // Outputs 10

  • Other Types

A demonstration of other data types:

Example

int myNum = 5;               // Integer (whole number without decimals)

double myFloatNum = 5.99;    // Floating point number (with decimals)

char myLetter = ‘D’;         // Character

string myText = “Hello”;     // String (text)

bool myBoolean = true;       // Boolean (true or false)

  • Displaying Variables:

You can use the cout object and the << operator to display variables and the text. Here’s an example:

Example

int myAge = 35;

cout << “I am “ << myAge << ” years old.”;

In this example, the << operator is used to combine the text (“I am “) and the myAge variable (35) to produce the output “I am 35 years old.”

Adding Variables Together:

You can use the + operator to add variables together. Here’s an example:

Example

int x = 5;

int y = 6;

int sum = x + y;

cout << sum;

In this example, the + operator adds the values of x and y together, and the result (11) is displayed using cout.

  • C++ Declare Multiple Variables

To declare multiple variables of the same type, use a list separated by commas.”

Example

int x = 5, y = 6, z = 50;

cout << x + y + z;

  • One Value to Multiple Variables

Alternatively, you can declare and initialize multiple variables more concisely as follows:

Example

int x, y, z;

x = y = z = 50;

cout << x + y + z;

  • C++ Identifiers

In C++, identifiers are unique names for variables, functions, and other program elements. They must start with a letter or underscore, are case-sensitive, and can include letters, digits, and underscores. Descriptive names are recommended for clarity, and there are naming conventions for consistency. Avoid using reserved words and keep identifiers reasonably short and meaningful.

Example

// Good

int minutesPerHour = 60;

// OK, but it is not so easy to understand what m is

int m = 60;

The general rules for naming variables in C++ are quite effective. Here’s a concise version of those rules:

  • Characters, numbers, and underscores can all be found in variable names.
  • Variable names must begin with an underscore or letter.
  • Case matters when naming variables; for example, “myVar” and “myvar” differ.
  • Spaces and other special characters like! #, %, etc., are not allowed in variable names.
  • You cannot utilize reserved words (as C++ keywords) as variable names.

 

  • C++ Constants

In C++, variables are read-only and unchangeable by declaring them using the const keyword. Using constants with suitable titles is demonstrated by the following examples:

  • Integer Constant:
const int MY_NUM = 15;  // MY_NUM will always be 15
  • Constant for Minutes per Hour:
const int MINUTES_PER_HOUR = 60;
  • Floating-Point Constant for Pi:
const float PI = 3.14;

By using const with meaningful variable names and titles, you can create more readable and maintainable C++ code.

C++ User Input

In C++, you can use cin to get input from the user. It’s like asking the user a question and listening for their answer. To do this, we create a variable (let’s call it ‘x’ for this example) to hold the user’s answer.

Here’s how it works step by step:

  • You ask the user for some input, like a number, by using cin.
  • The user types in their answer on the keyboard.
  • The >> symbol is like grabbing what the user typed and storing it in the variable ‘x’.
  • Once you have the user’s input stored in ‘x’, you can use it in your program, like printing it out with cout.

Here’s a simple example:

Example

int x; 

cout << “Type a number: “; // Type a number and press enter

cin >> x; // Get user input from the keyboard

cout << “Your number is: “ << x; // Display the input value

So, in this code, the user is prompted to enter a number, and their input is stored in the variable ‘x’, which is then displayed on the screen.

Explanation of how to create a simple calculator in C++ 

Here’s a simpler explanation of how to create a simple calculator in C++ that adds two numbers entered by the user:

Example

int x, y;

int sum;

cout << “Type a number: “;

cin >> x;

cout << “Type another number: “;

cin >> y;

sum = x + y;

cout << “Sum is: “ << sum;

C++ Data Types

In C++, data types are used to specify the type of data that a variable can hold. Here are some commonly used data types in C++:

Example

int myNum = 5;               // Integer (whole number)

float myFloatNum = 5.99;     // Floating point number

double myDoubleNum = 9.98;   // Floating point number

char myLetter = ‘D’;         // Character

bool myBoolean = true;       // Boolean

string myText = “Hello”;     // String

Basic data types

This table provides a quick reference to the standard data types used in programming, their typical sizes, and descriptions.

Basic data types

Data Type Size Description
boolean 1 byte Stores true or false values
char 1 byte Stores a single character/letter/number or ASCII values
int 2 or 4 bytes Stores whole numbers without decimals
float 4 bytes Stores fractional numbers containing one or more decimals. Sufficient for storing 6-7 decimal digits
double 8 bytes Stores fractional numbers containing one or more decimals. Sufficient for storing 15 decimal digits

Also Check: C++ Programming Basics Every Programming Enthusiast Must Know

Conclusion 

C++ is suited for many applications due to its extensive feature set. Programmers have robust tools to create reliable and practical applications since C is object-oriented and compatible with other C languages. It is necessary to comprehend syntax, variables, and user input before attempting to learn C++. Developers, experienced or novice, have an abundance of options using C++.

FAQs

What is the distinction between C++ and C?

The procedural language C differs from the object-oriented language C++ by encapsulation and inheritance.

Which four OOP fundamentals are there? 

Concepts related to object-oriented programming include inheritance, polymorphism, abstraction, and encapsulation.

Why do we call C++ C++?

The new name, which is wordplay, was adopted in 1983. It is implied that it is superior to C by the "Increment C by 1".

Are C and C++ syntax equivalents?

 Although the syntax is similar, C++ has a more extended grammar and more keywords.

C or C++: which is more straightforward?

Although C is a more straightforward language to learn, the organized ideas of C++ might make writing it easier.

Telegram Group Join Now
WhatsApp Channel Join Now
YouTube Channel Subscribe
Scroll to Top
close
counselling
Want to Enrol in PW Skills Courses
Connect with our experts to get a free counselling & get all your doubt cleared.