0% found this document useful (0 votes)
8 views23 pages

Basic C++

The document provides a comprehensive overview of C++ input/output operations, including the use of cout and cin for console interaction, the necessity of including the iostream library, and the syntax for printing and reading data. It also covers data types in C++, including primary, derived, and user-defined types, along with their memory representation and potential issues like integer overflow. Additionally, it discusses preprocessor directives, including macros, file inclusion, and conditional compilation, which enhance code maintainability and flexibility.

Uploaded by

trongnp1812
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views23 pages

Basic C++

The document provides a comprehensive overview of C++ input/output operations, including the use of cout and cin for console interaction, the necessity of including the iostream library, and the syntax for printing and reading data. It also covers data types in C++, including primary, derived, and user-defined types, along with their memory representation and potential issues like integer overflow. Additionally, it discusses preprocessor directives, including macros, file inclusion, and conditional compilation, which enhance code maintainability and flexibility.

Uploaded by

trongnp1812
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Part 1

C++ Input / Output

Before a program can interact with the user, it must be able to display
messages on the screen and receive data from the keyboard. In C++,
this is done through console input/output, mainly by using the objects
cout and cin.

Console output is used to print text, numbers, and variable values to the
screen.
Console input is used to read values typed by the user during program
execution.

These features are provided by the iostream library. Therefore, before using
input/output statements, the program must include the appropriate header
file.

Header File for Input / Output

To use console input and output in C++, we need to include the standard
header file:

Syntax

#include <iostream>

This header provides:

 cout for output

 cin for input

 endl for moving to a new line

Example

#include <iostream>
using namespace std;

int main()
{
cout << "Hello C++";
return 0;
}
In this example, the program includes the iostream library and prints a
message to the console. This matches the same foundational usage shown in
your reference file, where a header is included first before using standard
features.

Namespace in C++ Input / Output

Because cout and cin belong to the std namespace, we usually write:

Syntax

using namespace std;

Without this line, we must write:

std::cout << "Hello";


std::cin >> x;

Example

#include <iostream>
using namespace std;

int main()
{
cout << "Welcome to C++";
return 0;
}

The use of #include <iostream> and using namespace std; is also directly
reflected in the material from the file you sent earlier.

Output in C++ with cout

cout stands for character output. It is used to display messages or values


on the screen.

The operator used with cout is <<, called the insertion operator.

Syntax

cout << data;

Example 1
#include <iostream>
using namespace std;

int main()
{
cout << "C++ is fun!!!";
return 0;
}

Output

C++ is fun!!!

This is very similar to the simple cout example appearing in your document.

Printing a New Line

Sometimes we want the output to move to the next line. In C++, this can be
done using \n or endl.

Example

#include <iostream>
using namespace std;

int main()
{
cout << "First line\n";
cout << "Second line" << endl;
cout << "Third line";
return 0;
}

Output

First line
Second line
Third line

Explanation

 \n inserts a new line character

 endl also moves to the next line


Printing Variables to the Console

cout can print not only text, but also variable values.

Example

#include <iostream>
using namespace std;

int main()
{
int age = 20;
double score = 8.5;

cout << "Age = " << age << endl;


cout << "Score = " << score << endl;

return 0;
}

Output

Age = 20
Score = 8.5

This is useful because a program often needs to display both fixed messages
and computed values.

Input in C++ with cin

cin stands for character input. It is used to receive data typed by the user
from the keyboard.

The operator used with cin is >>, called the extraction operator.

Syntax

cin >> variable;

Example

#include <iostream>
using namespace std;
int main()
{
int number;
cin >> number;
return 0;
}

In this example, the value typed by the user will be stored in the variable
number.

Input and Output Together

In most interactive programs, we first display a message, then ask the user
to enter data, and finally show the result.

Example

#include <iostream>
using namespace std;

int main()
{
int age;

cout << "Enter your age: ";


cin >> age;

cout << "Your age is: " << age << endl;

return 0;
}

Sample Output

Enter your age: 19


Your age is: 19

This is one of the most basic and important forms of console interaction in
C++.
Reading More Than One Variable

We can use cin to read multiple values in one program.

Example

#include <iostream>
using namespace std;

int main()
{
int a, b;

cout << "Enter two integers: ";


cin >> a >> b;

cout << "a = " << a << endl;


cout << "b = " << b << endl;
cout << "Sum = " << a + b << endl;

return 0;
}

Sample Output

Enter two integers: 5 7


a=5
b=7
Sum = 12

Input and Output with Different Data Types

C++ input/output can work with many data types such as:

 int

 float

 double

 char

 string

Example
#include <iostream>
using namespace std;

int main()
{
int age;
double height;
char grade;

cout << "Enter age: ";


cin >> age;

cout << "Enter height: ";


cin >> height;

cout << "Enter grade: ";


cin >> grade;

cout << "Age = " << age << endl;


cout << "Height = " << height << endl;
cout << "Grade = " << grade << endl;

return 0;
}

The idea of variables and data types is also introduced in your source
material, so this section extends it specifically for input/output use.

Example: A Simple Interactive Program

#include <iostream>
using namespace std;

int main()
{
string name;
int age;

cout << "Enter your name: ";


cin >> name;
cout << "Enter your age: ";
cin >> age;

cout << "Hello, " << name << "!" << endl;
cout << "You are " << age << " years old." << endl;

return 0;
}

Sample Output

Enter your name: John


Enter your age: 18
Hello, John!
You are 18 years old.

Notes on cin

When using:

cin >> name;

the program reads only one word.


If the user enters a full name with spaces, cin will stop reading at the first
space.

For example:

 Input: John Smith

 Stored value: John

This is an important limitation students should remember when learning


basic console input.

Common Mistakes in C++ Input / Output

1. Forgetting to include the library

#include <iostream>

2. Forgetting using namespace std;


Then cout and cin may not work unless written as std::cout and std::cin.

3. Using undeclared variables

cin >> age; // wrong if age was not declared before

4. Missing semicolon

cout << "Hello"

5. Input type mismatch

If the program expects an integer and the user enters text, the input may
fail.

Summary

C++ console input/output is one of the most fundamental parts of


programming.

 cout is used to print output to the console

 cin is used to get input from the keyboard

 #include <iostream> is required to use standard input/output

 using namespace std; helps simplify code writing

 << is used with cout

 >> is used with cin

By combining cout and cin, we can create simple interactive programs that
communicate with the user.

Short version to paste into slide bullets

Slide: C++ Input / Output

 cout is used to display output on the console

 cin is used to receive input from the keyboard

 Both are provided by the iostream library

 << is the output operator

 >> is the input operator


Slide: Example

#include <iostream>
using namespace std;

int main()
{
int age;
cout << "Enter your age: ";
cin >> age;
cout << "Your age is: " << age;
return 0;
}

Part 2

1. Classification of Data Types

C++ provides a rich set of data types to handle different kinds of data
efficiently. They are categorized into three main groups.

A. Primary (Built-in) Data Types

These are fundamental types provided by the language.

 Examples: int, char, float, double, bool, void.

Code Example:

C++

#include <iostream>

using namespace std;

int main() {

int studentID = 67; // Integer

double gpa = 3.9; // Floating-point

char grade = 'A'; // Character

bool isGraduated = false; // Boolean


cout << "ID: " << studentID << " | Grade: " << grade << " | GPA: " <<
gpa << endl;

return 0;

Execution Output: ID: 67 | Grade: A | GPA: 3.9

B. Derived Data Types

These types are derived from the primary data types.

 Examples: Arrays, Pointers, References, Functions.

Code Example:

C++

#include <iostream>

using namespace std;

int main() {

int scores[3] = {85, 90, 95}; // Array

int* ptr = scores; // Pointer (points to the first element)

int& ref = scores[1]; // Reference to the second element

cout << "First score (via pointer): " << *ptr << endl;

cout << "Second score (via reference): " << ref << endl;

return 0;

Execution Output: First score (via pointer): 85 Second score (via


reference): 90

C. User-defined Data Types


Defined by the programmer to model complex objects.

 Examples: struct, class, enum, union.

Code Example:

C++

#include <iostream>

using namespace std;

struct Internship {

string company;

int durationMonths;

};

int main() {

Internship fpt = {"FPT Software", 3};

cout << "Interning at: " << [Link] << " for " << [Link]
<< " months." << endl;

return 0;

Execution Output: Interning at: FPT Software for 3 months.

2. Data Type Size and Memory Representation

In C++, the memory size of data types can vary depending on the
architecture (e.g., 32-bit vs. 64-bit).

Code Example:

C++

#include <iostream>

using namespace std;


int main() {

cout << "Size of char: " << sizeof(char) << " byte" << endl;

cout << "Size of int: " << sizeof(int) << " bytes" << endl;

cout << "Size of double: " << sizeof(double) << " bytes" << endl;

return 0;

Execution Output (on Windows 64-bit): Size of char: 1 byte Size of int: 4
bytes Size of double: 8 bytes

3. Integer Overflow and Response

This is a critical behavior where a variable exceeds its maximum or minimum


storage capacity.

Concept: Wrap-around Behavior

When an integer exceeds its upper limit, it "wraps around" to the lowest
possible value for that type.

Code Example:

C++

#include <iostream>

#include <limits> // To access INT_MAX

using namespace std;

int main() {

int maxVal = numeric_limits<int>::max();

cout << "Max Integer: " << maxVal << endl;

int overflowed = maxVal + 1; // Triggering overflow

cout << "After Overflow (max + 1): " << overflowed << endl;
return 0;

Execution Output: Max Integer: 2147483647 After Overflow (max + 1): -


2147483648

Part 3

Before your C++ code is compiled into an executable program, it goes


through a preprocessing phase. During this phase, the preprocessor reads
your code and performs various text manipulations based on special
instructions called preprocessor directives. These directives begin with a
hash symbol (#) and are executed before the actual compilation starts.

Preprocessor directives can be thought of as instructions to the compiler's


preprocessor to perform specific text-based operations on your source code.
They are powerful tools that can help you write more maintainable, flexible,
and platform-independent code.

I. Macros

Macros are shortcuts or placeholders that the preprocessor replaces before


the code is compiled. They are defined using #define and can be used to
create constants or code snippets.

Syntax

#define MACRO_NAME macro_definition

MACRO_NAME: It is the name we give to the macro.

macro_definition: It is the code that the preprocessor will substitute


whenever the macro is used.

Example: #include <iostream>

// macro definition

#define LIMIT 5

int main()

{
for (int i = 0; i < LIMIT; i++)

std::cout << i << "\n";

return 0;

Types of Macros in C++

Macros can be classified into types in C++:

1. Object-Like Macros

These are used to define constant values — like replacing a word with a fixed
number or text.

Example:

// C++ program to illustrate the object like macros

#include <iostream>

using namespace std;

// Define a constant for the value of PI

#define PI 3.14159

int main()

double radius = 4.0;

// Calculate the area of the circle

double area = PI * radius * radius;

cout << "Area of circle with radius " << radius


<< " is " << area;

return 0;

2. Function-Like Macros

These macros look like functions, but they are just text replacements.

#include <iostream>

using namespace std;

#define SQUARE(x) ((x) * (x))

int main()

double x = 4.0;

// Calculate the area of the Square

double area = SQUARE(x);

cout << "Area of circle with radius: "<< area;

return 0;

II. File Inclusion


This type of preprocessor directive tells the compiler to include a file in the
source code program. There are two types of files which can be included by
the user in the program:

 Standard files(Pre-Existing Header Files): The pre-existing header files


come bundled with the compiler and reside in the standard system file
directory. This file contains C++ standard library function declarations
and macro definitions to be shared between several source files.
Functions like the printf(), scanf(), cout, cin, and various other input-
output or other standard functions are contained within different Pre-
Existing header files.

Syntax: #include <header_file>

Example: #include <iostream>

#include <cmath>

#define M_PI 3.14

using namespace std;

int main() {

double x = 16.0;

// Tính căn bậc hai

cout << sqrt(x) << endl;

// Tính lũy thừa

cout << pow(2, 3) << endl;

// Tính giá trị tuyệt đối

cout << abs(-5) << endl;

// Tính sin, cos, tan

cout << sin(M_PI / 2) << endl;

cout << cos(0) << endl;

cout << tan(M_PI / 4) << endl;

return 0;

}
 User defined files: These files resemble the header files, except for the
fact that they are written and defined by the user itself. This saves the
user from writing a particular function multiple times.

Syntax: #include "user-defined_file"

math_utils.h: used to declare functions.

#ifndef MATH_UTILS_H

#define MATH_UTILS_H

int add(int a, int b);

int multiply(int a, int b);

#endif

math_utils.cpp: used to define (implement) the functions declared in the .h


file.

#include "math_utils.h"

int add(int a, int b) {

return a + b;

int multiply(int a, int b) {

return a * b;

[Link]:

#include <iostream>

#include "math_utils.h"

using namespace std;

int main() {

cout << "Sum: " << add(5, 3) << "\n";

cout << "Product: " << multiply(5, 3) << "\n";


return 0;

III. Conditional Compilation

Conditional compilation is a feature in C++ that lets you include or exclude


parts of code during compilation based on certain conditions using
preprocessor directives. It allows the compiler to compile only specific
sections of a program or skip others depending on defined conditions.

1,#ifdef , #endif

#ifdef is a preprocessor directive used to check whether a macro is defined


or not.

#endif: Marks the end of the conditional block.

syntax:

#ifdef MACRO_NAME

statement1;

statement2;

#endif

If the macro name is defined the block of statements will execute but if it is
not defined, the compiler will skip.

Example:

#define DEBUG

#ifdef DEBUG
cout << "Debug mode is enabled" << endl;
#endif

2,#if, #elif, #else

These are preprocessor directives used for conditional compilation, allowing


you to control which parts of the code are included or excluded before
compilation.

a, #if

Checks a condition (must be a constant expression or macro)

If the condition is true → code is compiled


If false → code is removed

b, #elif

Used to check another condition if the previous #if is false

c, #else

Default case when all previous conditions are false

Syntax:

#if condition

// code if condition is true

#elif condition2

// code if condition2 is true

#elif condition3

// you can have multiple elif blocks

#else

// code if all conditions are false

#endifExample:

#define VERSION 2

#if VERSION == 1
cout << "Running Version 1\n";
#elif VERSION == 2
cout << "Running Version 2\n";
#else
cout << "Unknown Version\n";
#endif

3, #ifndef

#ifndef is a preprocessor directive used to check whether a macro is not


defined.

#ifndef MACRO_NAME

// code will be compiled if the macro is NOT defined

#endif
Example: #ifndef MAX_SIZE

#define MAX_SIZE 100

#endif

IV. Other Directives

1. #undef

#undef is a preprocessor directive used to remove (undefine) a macro that


was previously defined with #define.

Example:

#define DEBUG

#ifdef DEBUG

cout << "Debug mode ON";

#endif

#undef DEBUG

#ifdef DEBUG

cout << "Still debug";

#else

cout << "Debug mode OFF";

#endif

2, #Pragma directive

#pragma is a preprocessor directive used to give special instructions to the


compiler.

Syntax: #pragma instruction

a. #pragma once

#pragma once is a preprocessor directive used to ensure that a header file


(.h) is included only once during compilation.

Example:
In this example, the inclusion of grandparent.h in both parent.h and child.c
would ordinarily cause a compilation error, because a struct with a given
name can only be defined a single time in a given compilation.

The #pragma once directive serves to avoid this by ignoring subsequent


inclusions of grandparent.h.

b. #pragma message

used at compile time to print custom messages.

Example:

#define DEBUG
#ifdef DEBUG

#pragma message("Debug mode is enabled")

#endif

You might also like