0% found this document useful (0 votes)
5 views9 pages

C++ Unit 1

This document provides an overview of C++ programming basics, including core syntax, data types, operators, control flow, and loops. It covers fundamental concepts such as input/output operations using cin and cout, conditional statements, and the structure of loops (for, while, do-while). Additionally, it introduces object-oriented programming principles and memory management techniques in C++.

Uploaded by

sosaxix663
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)
5 views9 pages

C++ Unit 1

This document provides an overview of C++ programming basics, including core syntax, data types, operators, control flow, and loops. It covers fundamental concepts such as input/output operations using cin and cout, conditional statements, and the structure of loops (for, while, do-while). Additionally, it introduces object-oriented programming principles and memory management techniques in C++.

Uploaded by

sosaxix663
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

C++ Basics: Core Syntax, Input / Output (cin / cout), Data Types, Operators.

Control Flow: Conditional Statements (if / else, switch case).


Loops: for, While, Do – while.
Functions & Memory: Modular Programming, Pass – by – values . references, and Pointer arithmetic.
OOP Fundamentals: Classes, Objects, Constructors and Access Specifiers (Public / Private ),
Templates.

C++ Basics
C++ is a powerful, object-oriented, general-purpose programming language that provides
high-level control over system resources and memory. Key basics include the fundamental
program structure, data types, variables, operators, and control flow.
#include <iostream>

using namespace std;

int main() {
cout << "Hello, World!";
return 0;
}

 #include <iostream> : This is a preprocessor directive that includes the input/output stream
library, which is necessary to use cin (for input) and cout (for output).
 using namespace std; : This statement allows the use of standard library names
like cout without having to prefix them with std:: .
 int main() : This is the main function, where program execution begins and ends.
 { ... } : Braces define a block of code, in this case, the body of the main function.
 cout << "Hello, World!"; : This statement prints the text "Hello, World!" to the console using
the stream insertion operator ( << ).
 return 0; : This statement terminates the main function and indicates that the program
executed successfully.

Core Concepts
Data Types
C++ has various data types to handle different kinds of information:
 int : Stores whole numbers (integers).
 double : Stores floating-point numbers (numbers with decimals).
 char : Stores single characters, such as 'a' or 'B' , within single quotes.
 bool : Stores boolean values, which can be either true or false .
 string : Stores sequences of characters, such as "Hello" , within double quotes. This requires
including the <string> library.

Variables and Constants


 Variables are memory locations whose content can be modified during program execution.
They must be declared with a name and a data type before use.
o Example: int myVariable = 10;
 Named Constants are memory locations whose data cannot change. They are declared using
the const keyword.
o Example: const double PI = 3.14;

Operators
Operators are used to perform operations on variables and values:
 Arithmetic: + (addition), - (subtraction), * (multiplication), / (division), % (modulus).
 Assignment: = (assignment), += , -= , *= , /= , etc..
 Comparison: == (equality), != (inequality), > (greater than), < (less than), etc..
 Logical: && (and), || (or), ! (not).

Control Flow
Control flow statements determine the order in which instructions are executed:
 Conditional Statements: if , else if , else , and switch statements allow the program to
make decisions based on certain conditions.
 Loops: for , while , and do-while loops repeat a block of code multiple times.

Core Syntax
The core syntax of C++ defines the fundamental rules for writing a program, largely
inherited from the C language, but with added object-oriented features.

Basic Program Structure


A typical C++ program follows a standard structure:
 Preprocessor Directives: Lines starting with # are processed before compilation. #include
<iostream> is essential for input/output operations.
 Namespace Declaration: using namespace std; allows the use of standard library
components like cout and cin without prefixing them with std:: .
 Main Function: The int main() function is the entry point where the program's execution
begins.
 Function Body: Code to be executed is enclosed in curly braces {} within the main function
(or other functions).
 Return Statement: return 0; terminates the main function and indicates successful
execution to the operating system.
Key Syntax Elements
 Semicolons and Statements: Every single statement in C++ must end with a semicolon ( ; ).
 Comments:
o Single-line comments start with // .
o Multi-line comments start with /* and end with */ .

 Identifiers: Names given to variables, functions, classes, etc. They can contain letters, digits,
and underscores, but must start with a letter or an underscore. C++ is case-sensitive
(e.g., count and Count are different).
 Keywords: Reserved words with special meanings that cannot be used as identifiers
(e.g., class , int , return , if , while , new ).
 Data Types: C++ is a strongly typed language. Variables must be declared with a specific
data type, such as int , char , double , float , or bool .
 Variables and Constants: Variables are used to store data and must be declared before use.
The const keyword makes a variable's value immutable.
 Operators: Symbols that perform operations on data, including arithmetic
( + , - , * , / , % ), comparison ( == , != , < , > ), logical, and assignment operators.

Input / Output (cin / cout)

In C++, cin and cout are stream objects used for standard input and output
operations, respectively, and are defined in the <iostream> header file.
Using cout (Standard Output)
The cout object is an instance of the ostream class and is used to display output on
the standard output device, typically the screen.
 Operator: It is used with the insertion operator ( << ).
 Purpose: To send data (strings, numbers, variable values) from the program's memory to the
display.

Ex:
#include <iostream>

int main() {
std::cout << "Hello, World!" << std::endl;
return 0;
}
Explanation: The << operator inserts the string "Hello, World!" into
the std::cout stream. std::endl adds a newline character and flushes the output buffer.
Using \n instead of std::endl is often more efficient if you don't need to force an immediate
flush.
Using cin (Standard Input)
The cin object is an instance of the istream class and is used to read input from the
standard input device, typically the keyboard.
 Operator: It is used with the extraction operator ( >> ).
 Purpose: To extract data from the input stream and store it in a variable.

 Example
#include <iostream>
#include <string> // Required for std::string
int main() {
int age;
std::string name;
std::cout << "Enter your name and age: ";
// Reading multiple values in a single statement
std::cin >> name >> age;
std::cout << "Name: " << name << ", Age: " << age << std::endl;
return 0;
}

Data Types, Operators

C++ categorizes data types into three main groups: Primitive, Derived, and User-
Defined.

Primitive (Built-in) Data Types


These are the fundamental data types the language provides. Key primitive types include:
 int : Stores whole numbers, typically 4 bytes.
 float : Stores single-precision decimals, 4 bytes with about 7 decimal digits of precision.
 double : Stores double-precision decimals, 8 bytes with about 15 decimal digits of precision.
 char : Stores a single character or ASCII value, typically 1 byte.
 bool : Stores true (1) or false (0), 1 byte.
 void : Represents the absence of a value.
 wchar_t : Used for wide characters for international character sets.
Modifiers like short , long , signed , and unsigned can adjust the size and range of integer
types.

Derived Data Types


These are built upon primitive types. Examples include:
 Arrays: Collections of the same data type in contiguous memory.
 Pointers: Variables holding memory addresses.
 References: Aliases for existing variables.
 Functions: Code blocks for specific tasks.
User-Defined Data Types
Defined by programmers. These include:
 Classes: Used to create objects in object-oriented programming.
 Structures ( struct ): Group variables of different types under one name.
 Unions ( union ): Store different data types in the same memory location.
 Enumerations ( enum ): Assign names to integral constants.
C++ Operators
Operators perform operations on operands. Categories include:
 Arithmetic Operators: For mathematical operations ( + , - , * , / , % , ++ , -- ).
 Assignment Operators: Assign values ( = , += , -= , *= , /= , %= ).
 Relational Operators: Compare operands ( == , != , > , < , >= , <= ).
 Logical Operators: Combine conditions ( && , || , ! ).
 Bitwise Operators: Operate on individual bits ( & , | , ^ , ~ , << , >> ).
 Other Operators: Miscellaneous operations ( sizeof , ?: , & , * , . , -> ).

Control Flow: Conditional Statements (if / else, switch case).


In C++, control flow is managed using conditional statements,
primarily if / else constructs and switch statements, which allow programs to execute
different blocks of code based on certain conditions.

if , else if , and else Statements


The if statement is the most basic form of conditional control flow. It evaluates a
condition, and if the condition is true, the associated code block is executed.
Ex:
#include <iostream>

int main() {
int number = 10;
// if statement
if (number > 0) {
std::cout << "The number is positive." << std::endl;
}
// else if and else statements
if (number > 15) {
std::cout << "The number is greater than 15." << std::endl;
} else if (number > 5) {
std::cout << "The number is greater than 5 but less than or equal to 15." << std::endl;
} else {
std::cout << "The number is 5 or less." << std::endl;
}

return 0;
}
switch Statements
The switch statement provides a clean way to handle multiple possible values for a
single variable, offering an alternative to a long chain of if / else if statements when
checking an integral or enum value

#include <iostream>

int main() {
char grade = 'B';

switch (grade) {
case 'A':
std::cout << "Excellent!" << std::endl;
break;
case 'B':
case 'C':
std::cout << "Well done." << std::endl;
break;
case 'D':
std::cout << "You passed." << std::endl;
break;
case 'F':
std::cout << "Better try again." << std::endl;
break;
default:
std::cout << "Invalid grade." << std::endl;
}

return 0;
}

Comparison.
[Link] Feature if – else switch – case
1. Conditions Can evaluate complex Primarily used for testing a single
conditions and relational variable against multiple discrete
expressions integral/enum values
2. Flexibility Highly flexible, can handle a Less flexible, more structured for
wide range of logical specific value checks
scenarios
3. Execution Checks conditions Jumps directly to the
sequentially until one is true matching case block for
efficiency
4. Break Not needed break statements are crucial to
prevent unintended fall-through
Loops: for, while, do – while.
In C++, loops are control structures used to repeatedly execute a block of code until a
specified condition is met. The three primary types of loops are for , while , and do-while ,
which differ in their syntax and the point at which the condition is checked.

1. The for Loop


The for loop is typically used when the number of iterations is known in
advance. It is an entry-controlled loop, meaning the condition is checked before the
loop body executes.

Syntax: for (initialization; condition; update) {


// body of the loop
}

1. #include <iostream>

int main() {
for (int i = 0; i < 5; i++) {
std::cout << i << " "; // Prints 0 1 2 3 4
}
return 0;
}

2. #include <iostream>
using namespace std;

int main() {
int n;
long long fact = 1;

cout << "Enter a number: ";


cin >> n;

for (int i = 1; i <= n; i++) {


fact *= i;
}

cout << "Factorial of " << n << " is " << fact;
return 0;
}

2. The while Loop


The while loop is used when the number of iterations is not known beforehand, and
the loop continues as long as a specified condition remains true . It is also an entry-controlled
loop.
Syntax
while (condition) {
// body of the loop
// update expression (must be included manually)
}

 The loop variable must be initialized before the loop, and updated within the loop body to
avoid an infinite loop.
#include <iostream>

int main() {
int i = 0; // Initialization outside the loop
while (i < 5) {
std::cout << i << " "; // Prints 0 1 2 3 4
i++; // Update inside the loop
}
return 0;
}

#include <iostream>
using namespace std;

int main() {
int n, i = 1;
long long fact = 1;

cout << "Enter a number: ";


cin >> n;

while (i <= n) {
fact *= i;
i++;
}

cout << "Factorial of " << n << " is " << fact;
return 0;
}

3. The do-while Loop


The do-while loop is a variant of the while loop with one key difference: it is an
exit-controlled (or post-tested) loop. The loop body is executed at least once before the
condition is evaluated. This makes it useful for scenarios like user input validation, where
you need to prompt the user at least once.
do {
// body of the loop
// update expression
} while (condition); // Note the required semicolon

#include <iostream>

int main() {
int i = 0;
do {
std::cout << i << " "; // Prints 0 1 2 3 4
i++;
} while (i < 5); // Condition checked after the first execution
return 0;
}

#include <iostream>
using namespace std;

int main() {
int n, i = 1;
long long fact = 1;

cout << "Enter a number: ";


cin >> n;

do {
fact *= i;
i++;
} while (i <= n);

cout << "Factorial of " << n << " is " << fact;
return 0;
}

You might also like