Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

Introduction to C++ Programming, Study notes of Programming Languages

An overview of the C++ programming language, covering its basic syntax, data types, control structures, and object-oriented programming concepts. It introduces the fundamentals, including setting up a development environment, writing and running a 'hello, world!' program, and exploring keywords. The document delves into data types, operators, variable declaration and initialization, and input/output functions. It also examines control structures and highlights the differences between primitive and non-primitive data types.

Typology: Study notes

2022/2023

Available from 07/30/2024

jay-kumar-9
jay-kumar-9 🇮🇳

7 documents

1 / 45

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Object Oriented Programming Language with C++
Introduction: This book is designed to introduce students to the fundamentals of the C++ programming language.
Students will learn the basics of C++ syntax, data types, control structures, functions, and object-oriented
programming concepts. By the end of the book, students should be able to write, compile, and debug simple C++
programs.
Module 1: Introduction to C++
Overview of C++ programming languages
Setting up a C++ development environment
Writing and running a "Hello, World!" program
Keywords in C++
Module 2: Data Types and Input/Output Functions
Fundamental data types (int, float, double, char)
Operators
Declaring and initializing variables
Input using cin and output using cout
Module 3: Control Structures
If statements and conditionals
Switch statements
Loops: for, while, do-while
Continue and goto statement
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d

Partial preview of the text

Download Introduction to C++ Programming and more Study notes Programming Languages in PDF only on Docsity!

Object Oriented Programming Language with C++

Introduction: This book is designed to introduce students to the fundamentals of the C++ programming language.

Students will learn the basics of C++ syntax, data types, control structures, functions, and object-oriented

programming concepts. By the end of the book, students should be able to write, compile, and debug simple C++

programs.

Module 1: Introduction to C++

  • Overview of C++ programming languages
  • Setting up a C++ development environment
  • Writing and running a "Hello, World!" program
  • Keywords in C++

Module 2: Data Types and Input/Output Functions

  • Fundamental data types (int, float, double, char)
  • Operators
  • Declaring and initializing variables
  • Input using cin and output using cout

Module 3 : Control Structures

  • If statements and conditionals
  • Switch statements
  • Loops: for, while, do-while
  • Continue and goto statement

Module 1: Introduction to C++

1.2 Overview of C++ programming language

C++ is a high-level programming language that was developed by Bjarne Stroustrup in the early 1980s. It is as an

extension of the C programming language. It was originally developed to provide additional features for system

programming while retaining the efficiency and low-level control of C.

C++ is a widely-used, general-purpose programming language Well-

known for its versatility and power. Rooted in the foundation of C, it

combines imperative, object-oriented, and generic programming models,

offering developers the flexibility to tackle a diverse array of tasks. C++

features a rich standard library, the Standard Template Library (STL),

which provides pre-built data structures and algorithms for efficient

development. This compiled language gives developers fine-grained

control over memory management and is known for its high-

performance capabilities, making it a go-to choose for systems

programming, game development, and resource-intensive applications.

Despite its powerful features, C++ does require careful attention to memory management and can have a

steeper learning curve compared to some other languages, but its active community and extensive toolset

make it a compelling choice for a wide range of projects.

Following are some key features of the C++ programming language: -

Object-Oriented Programming (OOP): C++ supports OOP principles, allowing you to create classes and

objects for organizing code and data into reusable structures. It facilitates encapsulation, inheritance, and

polymorphism.

Class and Object: C++ enables the definition of user-defined classes, which serve as blueprints for creating

objects. Objects are instances of these classes, containing both data (attributes) and functions (methods).

Inheritance: C++ supports inheritance, allowing one class to inherit properties and behaviours from another

class. This encourages the reuse of code and the development of interconnected class hierarchies

Polymorphism: C++ supports polymorphism, which means objects of different classes can be treated as

objects of a common base class. This enables dynamic method binding and flexibility in function calls.

Abstraction: C++ allows you to create abstract classes and pure virtual functions, which define interfaces

without providing implementation details. This promotes the concept of modularity and the separation of

different aspects.

Templates : C++ offers templates, which allow you to create generic classes and functions. Templates enable

writing code that works with different data types, enhancing code reusability and flexibility.

Standard Template Library (STL): The STL provides a collection of templates for common data structures

(e.g., vectors, lists) and algorithms (e.g., sorting, searching). It simplifies complex data manipulation tasks.

Operator Overloading: C++ permits operator overloading, allowing you to define custom behaviours for

operators in user-defined classes. This can make code more intuitive and readable.

3. Set Up Build Tools:

CMake: CMake is a cross-platform build system that generates build files for various IDEs and compilers.

Many C++ projects use CMake for their build process. Install CMake and learn how to create CMakeLists.txt

files for your projects.

4. Create a Workspace:

Decide on a directory where you want to keep your C++ projects organized. You can create a folder for each

project to keep things clean.

5. Write and Compile Your Code:

Create a new C++ source file with the ".cpp" extension.

Write your C++ code in the file.

Use the terminal or IDE to compile your code. For example, if you're using GCC, you can compile a file called

"my_program.cpp" with the following command:

g++ my_program.cpp - o my_program

6. Debugging (Optional):

Most IDEs provide debugging support. Set breakpoints and use debugging tools to identify and fix issues in

your code.

7. Libraries and Dependencies (Optional):

If your project requires external libraries or dependencies, make sure to install and link them correctly.

CMake is helpful in managing dependencies.

8. Version Control (Optional):

Consider using version control systems like Git to track changes in your code and collaborate with others.

9. Learn and Practice:

C++ is a complex language, so make sure to learn and practice regularly. There are plenty of online tutorials,

courses, and books available to help you improve your C++ skills.

10. Stay Informed:

Keep up with the C++ community and updates to the language and tools. C++ evolves, and staying informed

will help you write better and more efficient code.

Remember that setting up a development environment can be tailored to your specific needs and

preferences, so don't hesitate to explore different tools and configurations until you find what works best for

you.

1.3 Writing and Runing a “Hello, World!” Program

1. Open a Text Editor : You can use a plain text editor like Notepad on Windows, TextEdit on macOS, or any code

editor like Visual Studio Code, Sublime Text, or Dev C++.

2. Write the C++ Code : In your text editor, write the following C++ code:

#include int main () { std :: cout << "Hello, World!" << std :: endl ; return 0 ; } Now, let's explain the code step by step:

  • #include : This line includes the standard input-output stream header file, which is necessary to

use input and output operations in C++.

  • int main() { ... } : This is the main function where the program execution begins. Every C++ program must

have a main function.

  • std::cout << "Hello, World!" << std::endl; : This line uses std::cout to print the text "Hello, World!" to the

console. std::cout represents the standard output stream. << is the insertion operator, and it's used to insert

the text into the stream. std::endl is used to insert a newline character and flush the output stream.

  • return 0; : This line indicates the end of the main function and returns an exit status of 0 to the operating

system, which typically indicates a successful program execution.

3. Save the File : Save the file with a ".cpp" extension, for example, "hello.cpp".

4. Compile the Code : Open your command prompt or terminal, navigate to the directory where you saved the

"hello.cpp" file, and compile the code using a C++ compiler. If you have g++, you can compile the code like

this:

g++ hello.cpp - o hello

This command tells the compiler to compile "hello.cpp" and create an executable file named "hello" (you can

choose any name you like).

5. Run the Program : After compilation, you can run the program by typing:

./hello

You should see the output on the console:

Hello, World!

That's it! You've successfully written and run a "Hello, World!" program in C++. This simple program is often

used as a starting point for learning a new programming language and ensuring that your development

environment is set up correctly.

Header file and Libraries

Header files are files containing declarations of functions, classes, variables, and other code elements that can be

shared across multiple source files. They typically have a .h or .hpp extension. Header files serve as an interface

between different parts of a program, allowing functions and classes defined in one source file to be used in others.

By including the appropriate header files using the #include preprocessor directive, you can access these

declarations, ensuring that your code is both organized and efficient.

Module 2: Data Types and Input/Output Functions

2.1 Fundamental Data Types (int, float, double, char)

Data Types

Data types are a fundamental concept that defines the type of data a variable can hold and the operations that can

be performed on that data. They specify the size and format of the data, allowing the compiler to allocate memory

and determine how data is stored and manipulated.

C++ provides a range of data types, including fundamental types like int, float, double, and char, which represent

integers, floating-point numbers, and characters, respectively. Also, C++ allows users to define custom data types

through structures, classes, and enumerations, enabling the creation of more complex and specialized data

structures to suit specific programming needs. Understanding data types is important for effective variable

declaration, memory management, and the proper execution of operations in C++ programs.

Primitive Data Types and Non-Primitive (User-Define) Data Types

Data types can be categorized into two main groups: primitive data types and non-primitive data types. Primitive

data types are the fundamental building blocks and include types like int, float, double, and char, which directly

represent basic values such as integers, floating-point numbers, and characters. They have fixed sizes and are directly

supported by the C++ language.

On the other hand, non-primitive data types, also know user-defined data types, are created by combining primitive

types and include arrays, structures, classes, and enumerations. These types allow programmers to define custom

data structures with unique characteristics, encapsulating multiple variables or objects into a single entity. While

primitive data types are essential for storing simple data, non-primitive data types enable the creation of more

complex and customizable data structures, making C++ a versatile and powerful programming language.

Difference between Primitive and Non-Primitive Data Types in C++

Aspect Primitive Data Types Non-Primitive Data Types (User-Defined)

Definition Built-in data types Custom data types defined by users

Memory

Allocation

Typically, fixed size Size varies depending on data structure

Examples int, float, char, bool, etc. struct, class, enum, union, etc.

Operations Limited basic operations Custom operations can be defined

Data Storage Stores single values Can store multiple values and objects

Initialization Automatically initialized with default

values (0, 0.0, '\0', false)

Initialization may require user-defined

constructors

Memory

Management

Automatically managed by the compiler Manual memory management may be

required

Size and Flexibility Fixed size and limited flexibility Variable size and high flexibility

Use Cases Used for simple data storage and

arithmetic operations

Used for complex data structures and

modelling real-world entities

Primitive Data Types:

Advantages:

1. Efficiency: Primitive data types are highly efficient in terms of memory usage and processing speed because

they are built into the language and optimized by the compiler.

2. Portability: Primitive data types have consistent behaviour across different platforms and compilers, making

C++ programs portable.

3. Simplicity: They are easy to use and understand, making them suitable for simple data storage and

manipulation.

4. Built-in Operations: Primitive data types come with built-in operators and functions, allowing for

straightforward mathematical and logical operations.

Limitations:

1. Limited Representations: Primitive types have finite ranges and precisions. For example, int has a limited

range, and float has limited precision. This limitation can lead to issues with large numbers or high precision

requirements.

2. Limited Expressiveness: They may not adequately represent complex real-world entities or data structures,

making them less suitable for modelling certain types of data.

Non-Primitive (User-Defined) Data Types:

Advantages:

1. Customization: User-defined data types allow programmers to create data structures tailored to specific

application requirements, making code more expressive and meaningful.

2. Abstraction: They enable encapsulation and abstraction, making it easier to manage and manipulate

complex data and functionality.

3. Reusability: Once defined, user-defined data types can be reused throughout the program or in different

programs, promoting code reusability and maintainability.

4. Extensibility: They can be extended with member functions and overloaded operators, providing a higher

level of control and functionality.

Limitations:

1. Complexity: Defining and using user-defined data types can be more complex and time-consuming compared

to using primitive types, especially for simple tasks.

2. Resource Overhead: Custom data types may consume more memory and CPU resources than primitive

types, particularly when they include additional functionality and data members.

3. Learning Curve: Understanding and effectively using user-defined types often requires a deeper

understanding of object-oriented programming concepts, which may be challenging for beginners.

Other classification of data types

Signed Data Type:

  • Signed data types can represent both positive and negative values, including zero.
  • The leftmost bit (the most significant bit) is used as the sign bit, with 0 indicating a positive value and 1

indicating a negative value.

  • The remaining bits represent the magnitude of the number.

Floating (float) Data Type

The float data type is a fundamental primitive data type used to store single-precision floating-point numbers. It is

used for variables that represent real numbers with decimal points. Here are some key characteristics of the float

data type:

1. float

The float data type is used to store single-precision floating-point numbers. It occupies 4 bytes of memory and has a

range from approximately - 3.4E38 to 3.4E38, with a precision of about 7 decimal digits.

2. double

The double data type offers double-precision floating-point numbers. It consumes 8 bytes of memory, providing a

broader range from approximately - 1.7E308 to 1.7E308, with a precision of about 15 decimal digits.

3. Long double

In C++, long double is a data type used to represent floating-point numbers with extended precision. It is an

extension of the double data type, providing more significant digits and a wider range of values. The long double

data type is particularly useful when higher precision is required for numerical calculations.

Float Data Type

Data Type Format specifier Memory Range

Float %f 4 bytes 1.2E-38 to 3.4E+

Double %lf 8 bytes 2.3E-308 to 1.7E+

Long double %Lf 10 bytes 3.4E-4932 to 1.1E+

Character Data Type (char)

1. Char:

In C++ programming, char is a data type used to represent individual characters. It stands for "character" and is used

to store single ASCII characters, such as letters, digits, punctuation marks, and special symbols.

2. Unsigned Char:

The unsigned char data type is similar to the char data type but does not include negative values. It is used to

represent only non-negative characters, from 0 to 255, corresponding to their ASCII values.

3. Char Array: A char array, also known as a string in C++, is a sequence of characters stored in consecutive memory locations. It is represented as an array of char data type elements, terminated by a null character '\0'. The null character serves as the string's end and indicates where the sequence of characters stops. Char arrays are commonly used to handle and manipulate text in C++.

Character Data Type (char)

Data Type Format specifier Memory Range

Char %c 1 byte - 128 to 127 or 0 to 255

Unsigned char %c 1 byte 0 to 255

Char array (string) %s 1 byte - 128 to 127

Other Data Types

Besides the fundamental data types mentioned above, C also offers additional data types to meet specific programming requirements:

1. void The void data type is used to indicate the absence of a type. It is commonly used as a return type for functions that do not return any value. 2. Bool The Bool data type is used to represent Boolean values. It can take two values: 0 for false and 1 for true. 3. wchar_t The wchar_t data type is used to represent wide characters, which are used for extended character sets and internationalization.

Note: - In many programming languages, format specifiers are denoted by a percent symbol (%) followed by a

character or characters that represent the data type or formatting instructions.

2.2 Operators

In C++, operators are symbols or special tokens used to perform operations on operands. Operators allow you to

manipulate data and perform calculations in your C++ programs. Here are some of the most commonly used

operators in C++:

1. Arithmetic Operators: -

Arithmetic operators in C++ are symbols used for performing mathematical calculations on numerical operands. They

include addition +, subtraction - , multiplication *, division /, and modulus % operators. The addition operator + adds

two values together, while the subtraction operator - subtracts the right operand from the left operand. The

multiplication operator * multiplies two values, and the division operator / divides the left operand by the right

operand. The modulus operator % returns the remainder of the division operation. These operators are fundamental

for tasks like numeric computations, counting, and generating results based on mathematical formulas in C++

programs.

Arithmetic Operators

Operator Description Example

+ Addition a + b = 15

- Subtraction a - b = 5

* Multiplication a * b = 50

/ Division b / a = 2

% Modulus (Remainder) b % a = 0

operators are widely used for updating variables with new values, and they play a crucial role in C++ programming,

especially in loops and mathematical calculations.

Assignment Operators

Operator Description Examples

= Simple Assignment a = 10; // Assign 10 to 'a'

+= Add and Assign a += 5; // Equivalent to a = a + 5

- = Subtract and Assign a - = 3; // Equivalent to a = a - 3

*= Multiply and Assign a *= 2; // Equivalent to a = a * 2

/= Divide and Assign a /= 4; // Equivalent to a = a / 4

%= Modulus and Assign a %= 3; // Equivalent to a = a % 3

5 .logical Operators: -

Logical operators in C++ are used to perform logical operations on Boolean values or expressions. Logical operators

are commonly used in conditional statements and control flow to make decisions based on the truth or falsehood of

conditions. They allow you to create complex conditions by combining simpler ones and are fundamental for creating

robust and expressive programs.

logical Operators

Operator Description Example

&& Logical AND (a && b) // true if both 'a' and 'b' are true

|| Logical OR (a || b) // true if either 'a' or 'b' is true

! Logical NOT !(a) // true if 'a' is false, and false if 'a' is true

6 .Bitwise Operators: -

Bitwise operators in C++ are used to perform operations on individual bits of integral data types (such as integers and

characters). These operators are particularly useful for tasks involving low-level bit manipulation, such as working

with hardware or encoding and decoding data.

Bitwise Operators

Operators Description Example

& Bitwise AND a & b // Bitwise AND of a and b

| Bitwise OR a | b // Bitwise OR of a and b

^ Bitwise XOR (Exclusive OR) a ^ b // Bitwise XOR of a and b

~ Bitwise NOT (Complement) ~a // Bitwise NOT (Complement) of a

7. Ternary Operators: -

In C++, the ternary operator, also known as the conditional operator, is a unique operator that allows you to express

conditional statements in a concise and compact form. It takes the form of condition? expression1 : expression2,

where the condition is evaluated first. If the condition is true, expression1 is executed; otherwise, expression2 is

executed. The ternary operator enhances code readability and conciseness for simple conditional assignments or

expressions.

Example to demonstrate the operators in c++ #include using namespace std ; // Declaring global variables int a = 10 , b = 5 ; int x = 7 , y = 7 ; int count = 10 ; int num = 42 ; bool p = true, q = false; int num1 = 5 , num2 = 3 ; int main () { // Arithmetic operators cout << "Arithmetic Operators:" << endl ; cout << "a + b = " << a + b << endl ; cout << "a - b = " << a - b << endl ; cout << "a * b = " << a ***** b << endl ; cout << "a / b = " << a / b << endl ; cout << "a % b = " << a % b << endl ; // Relational operators cout << "\nRelational Operators:" << endl ; cout << "x == y: " << ( x == y ) << endl ; cout << "x != y: " << ( x != y ) << endl ; cout << "x > y: " << ( x > y ) << endl ; cout << "x < y: " << ( x < y ) << endl ; cout << "x >= y: " << ( x >= y ) << endl ; cout << "x <= y: " << ( x <= y ) << endl ; // Increment and Decrement operators cout << "\nIncrement and Decrement Operators:" << endl ; cout << "count++: " << count ++ << endl ; cout << "++count: " << ++ count << endl ; cout << "count--: " << count -- << endl ; cout << "--count: " << -- count << endl ; // Assignment operators cout << "\nAssignment Operators:" << endl ; num += 8 ; cout << "num += 8: " << num << endl ; num - = 5 ; cout << "num - = 5: " << num << endl ; num *= 2 ; cout << "num *= 2: " << num << endl ; num /= 4 ; cout << "num /= 4: " << num << endl ; num %= 3 ; cout << "num %= 3: " << num << endl ; // Logical operators cout << "\nLogical Operators:" << endl ; cout << "p && q: " << ( p && q ) << endl ; cout << "p || q: " << ( p || q ) << endl ; cout << "!p: " <<! p << endl ;

num1 ^ num2: 6 ~num1: - 6 num1 << 2: 20 num1 >> 1: 2 Example 1: num1 is greater Example 2: The maximum number is 5 Example 3: The maximum value is 10 8. Miscellaneous Operators: - In C++, miscellaneous operators encompass a group of operators that serve various specialized purposes. These operators include:

  1. sizeof Operator: The sizeof operator is used to determine the size in bytes of a data type or an object. It is often used when allocating memory dynamically or when working with data structures that require knowing the size of elements.
  2. Comma Operator: The comma operator, allows you to evaluate multiple expressions sequentially, returning the result of the last expression. It is commonly used in for loops and function calls where multiple expressions need to be executed in order.
  3. Address-of Operator: The & operator, known as the address-of operator, returns the memory address of a variable. It is essential for working with pointers and passing variables by reference to functions.
  4. Pointer Dereference Operator: The * operator is used to access the value pointed to by a pointer. It is crucial for manipulating data through pointers and working with dynamic memory allocation.
  5. typeid Operator: The typeid operator allows you to retrieve type information at runtime. It is commonly used in conjunction with polymorphism to determine the actual type of an object in a class hierarchy. These miscellaneous operators provide additional functionality and flexibility in C++ programming, enabling tasks such as memory management, type identification, and expression evaluation in a concise and effective manner. 2.3 Declaring and Initializing Variables

Variables

variables are fundamental elements used to store and manipulate data within a program. Each variable has a specific

data type (such as integer, float, character, or custom types), which defines the kind of data it can hold. Variables

provide a named memory location where values can be stored, accessed, and modified during the execution of a C++

program. By using variables, programmers can work with data, perform calculations, and manage information,

making them an essential building block for creating functional and dynamic software applications.

Type of variables

1. Local Variables:

  • Local variables are declared within a specific block of code, such as within a function or a block of

code enclosed by curly braces {}.

  • They have limited scope and are only accessible within the block where they are declared.
  • Local variables are typically used for temporary storage and are destroyed when the block exits.

2. Global Variables:

  • Global variables are declared outside of any function or block and have global scope.
  • They can be accessed from any part of the program, including functions and blocks.
  • Global variables persist throughout the program's execution and can have a significant impact on

program organization and maintainability.

3. Static Variables:

  • Static variables are declared using the static keyword within a function or block.
  • They retain their values between function calls and have a longer lifetime than local variables.
  • Static variables are often used when you need to preserve data between function invocations.

4. Constant Variables:

  • Constant variables are declared using the const keyword.
  • Once initialized, their values cannot be changed throughout the program's execution.
  • They are commonly used for defining constants that should not be modified accidentally.

5. Reference Variables:

  • Reference variables are aliases to existing variables.
  • They are declared using the & symbol and allow you to manipulate variables indirectly.
  • Reference variables are often used in function parameters to pass variables by reference, avoiding

unnecessary copying of data.

6. Pointer Variables:

  • Pointer variables store memory addresses, allowing you to indirectly access and manipulate data.
  • They are declared using an asterisk * symbol and can be used for dynamic memory allocation and

complex data structures.

7. Class Member Variables:

  • Member variables belong to a class or structure and are used to represent the attributes or

properties of objects created from that class.

  • They are accessed using the dot. operator on objects of the class.

8. Enumerated (Enum) Variables:

  • Enum variables allow you to create user-defined data types with a set of named constants.
  • They are often used to improve code readability by giving meaningful names to numeric values. Declaring a Variable :
  • Declaring a variable means telling the compiler what type of data the variable will hold (e.g., integer, float, character, etc.) and giving it a name.
  • It's essentially creating a placeholder or a memory location with a specific data type for future use.

Constant and Literals

Constants and literals are both used to represent fixed values within a program, but they differ in their nature and usage. A constant is a named identifier with an unchangeable value, defined using the const keyword. Constants are typically used to make code more readable and maintainable by providing meaningful names for values that should not change during program execution. For example, const int maxAttempts = 3; declares a constant maxAttempts with a value of 3. Literals , on the other hand, are direct representations of values within the code. They can be categorized into various types, such as integer literals (e.g., 42), floating-point literals (e.g., 3.14), character literals (e.g., 'A'), and string literals (e.g., "Hello, World!"). Literals provide a way to include specific values directly in expressions and assignments. While constants offer more flexibility and readability, literals are useful for quick, one-time representations of values without the need for separate declarations. Input/Output Functions

In C++, input and output operations are essential for interacting with a program's users and managing data flow.

Input typically involves receiving data from external sources, such as the keyboard or files, using functions like "cin"

for standard input or file streams for reading from files. Output, on the other hand, allows a program to display

information to the user or store it in files using functions like "cout" for standard output or file streams for writing to

files. These input and output operations play a crucial role in C++ programming, enabling communication between

the program and its environment, facilitating data processing, and making programs more interactive and

informative.

2. 4 Input using cin and output using cout

In C++, cin and cout are predefined objects that facilitate input and output operations. cin stands for "console input"

and is used to read data from the standard input, typically the keyboard. It is commonly employed with the

extraction operator >> to capture and store user-provided data into variables. On the other hand, cout stands for

"console output" and is used to display information on the standard output, typically the console or terminal. It is

often used in conjunction with the insertion operator << to print data, variables, or messages to the screen. Together,

cin and cout are fundamental components of C++ for interactive and informative program execution.

cin (Console Input) :

To read input from the user, you typically use cin with the extraction operator ( >> ).

Syntax for reading a variable from the console:

cin >> variableName ; int age ; cin >> age ; // Reads an integer value from the user and stores it in the 'age' variable. cout (Console Output):

To display output to the console, you use cout with the insertion operator ( << ).

Syntax for displaying data to the console:

cout << dataToDisplay ; int result = 42 ;

cout << "The answer is: " << result << endl ; // Displays "The answer is: 42" on the console.

Remember to include the necessary #include directive at the beginning of your C++ program to use cin

and cout. Additionally, endl is used to insert a newline character and flush the output buffer, causing the text to

appear on the console immediately.

Example #include using namespace std ; int main () { // Declare a variable to store user input int userNumber ; // Prompt the user for input cout << "Please enter a number: " ; // Read user input from the console cin >> userNumber ; // Display the user's input cout << "You entered: " << userNumber << endl ; return 0 ; } Output: - Please enter a number: 4 You entered: 4 Explanation above code

This code is a simple program written in the C++ programming language. Its main purpose is to take a number from

the person using the program and then display that number back to them.

1. #include

This line includes a library called "iostream," which stands for input-output stream. It allows the program to interact

with the user through the console (the text-based interface where you type and see text).

2. using namespace std;

This line tells the program to use the "std" namespace, which is a collection of functions and objects for input and

output. it helps in writing code that handles input and output more conveniently.

3. int main()

This is the beginning of the main function, which is the entry point of the program. Every C++ program must have a

main function, and the code inside it is what gets executed when the program is run.

4. int userNumber;

This line declares a variable named userNumber of type integer (whole numbers). This variable will be used to

store the number entered by the user.

5. cout << "Please enter a number: ";

This line uses cout (which stands for "console output") to display a message asking the user to enter a number. The

message is shown on the console.

6. cin >> userNumber;

This line uses cin (which stands for "console input") to read a number entered by the user and store it in the

userNumber variable. The program will wait for the user to type a number and press Enter.

7. cout << "You entered

" << userNumber << endl;: This line usescout` again to display a message along with the number that the user