[go: up one dir, main page]

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

OOSD unit-04

The document outlines the structure and components of a C++ program, including preprocessor directives, the main function, variables, constants, and control structures. It also covers functions, including their declaration, definition, and calling methods, as well as advanced concepts like inline functions, function overloading, and virtual functions. Key programming concepts such as namespaces, identifiers, operators, and typecasting are also discussed.

Uploaded by

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

OOSD unit-04

The document outlines the structure and components of a C++ program, including preprocessor directives, the main function, variables, constants, and control structures. It also covers functions, including their declaration, definition, and calling methods, as well as advanced concepts like inline functions, function overloading, and virtual functions. Key programming concepts such as namespaces, identifiers, operators, and typecasting are also discussed.

Uploaded by

rayimel830
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

1.

C++ Program Structure

A C++ program typically consists of:

a. Preprocessor Directives

 These lines start with # and are processed before the compilation.
 Used to include libraries or define macros.

b. Main Function

 Every C++ program must have a main() function, which serves as the entry point.

c. Statements and Expressions

 Statements are individual instructions.


 Expressions calculate a value.

Structure Example:

cpp
Copy code
#include <iostream> // Preprocessor directive for input/output

int main() { // Main function


std::cout << "Hello, World!" << std::endl; // Output statement
return 0; // Indicates successful execution
}

2. Namespace

Namespaces avoid naming conflicts in large programs. The standard namespace ( std) includes
common functions like cout, cin.

Example without Namespace:

cpp
Copy code
#include <iostream>

int main() {
std::cout << "Hello!" << std::endl; // std:: needed
return 0;
}

Example with Namespace:

cpp
Copy code
#include <iostream>
using namespace std;

int main() {
cout << "Hello!" << endl; // No need for std::
return 0;
}

3. Identifiers

Identifiers are user-defined names for variables, functions, arrays, etc.

Rules:

 Must start with a letter or _.


 Cannot use reserved keywords (e.g., int, if).

Example:

cpp
Copy code
int age = 25; // age is an identifier
float salary = 5000.5; // salary is an identifier

4. Variables

A variable is a container to store data. It must be declared before use.

Syntax:

cpp
Copy code
data_type variable_name = value;

Types:

 int: Integer values.


 float: Floating-point numbers.
 char: Single characters.
 bool: Boolean values (true or false).

Example:

cpp
Copy code
int age = 30; // Integer variable
float pi = 3.14; // Floating-point variable
char grade = 'A'; // Character variable
bool isPassed = true; // Boolean variable

5. Constants

Constants are variables whose values cannot change during the program execution.

Types of Constants:

1. Literal Constants: Fixed values directly written.

cpp
Copy code
int age = 30; // 30 is a literal constant

2. const Variables: Declared using the const keyword.

cpp
Copy code
const float PI = 3.14159;

3. #define Preprocessor Constants:

cpp
Copy code
#define PI 3.14159

Example:

cpp
Copy code
const int MAX = 100; // Constant variable

6. Enum (Enumerations)

Enums allow you to define a type that includes a set of named integral constants.

Syntax:

cpp
Copy code
enum EnumName { Value1, Value2, Value3 };

Example:

cpp
Copy code
enum Color { RED, GREEN, BLUE };
Color myColor = GREEN;

if (myColor == GREEN) {
cout << "The color is green." << endl;
}

 By default, RED = 0, GREEN = 1, and so on. You can assign custom values.

7. Operators

a. Arithmetic Operators:

 +, -, *, /, % (modulus)

Example:

cpp
Copy code
int a = 10, b = 3;
cout << "Sum: " << a + b << endl; // Outputs 13
cout << "Remainder: " << a % b; // Outputs 1

b. Relational Operators:

 Compare values: ==, !=, <, >, <=, >=

Example:

cpp
Copy code
if (a > b) {
cout << "a is greater than b";
}

c. Logical Operators:

 Combine conditions: && (AND), || (OR), ! (NOT)

Example:

cpp
Copy code
if (a > 0 && b > 0) {
cout << "Both are positive numbers";
}
d. Assignment Operators:

 Assign or modify values: =, +=, -=, *=, /=, etc.

Example:

cpp
Copy code
a += 5; // Equivalent to a = a + 5

8. Typecasting

Converting one data type into another.

a. Implicit Typecasting:

 Automatically done by the compiler.

Example:

cpp
Copy code
int x = 10;
float y = x; // Implicit conversion

b. Explicit Typecasting:

 Done manually by the programmer.

Example:

cpp
Copy code
float x = 5.5;
int y = (int)x; // Explicit conversion

9. Control Structures

Control structures determine the flow of execution.

a. Conditional Statements

1. if Statement:

cpp
Copy code
if (x > 0) {
cout << "Positive number";
}

2. if-else Statement:

cpp
Copy code
if (x > 0) {
cout << "Positive";
} else {
cout << "Non-positive";
}

3. switch Statement:

cpp
Copy code
switch (x) {
case 1: cout << "One"; break;
case 2: cout << "Two"; break;
default: cout << "Other";
}

b. Loops

1. for Loop:

cpp
Copy code
for (int i = 0; i < 5; i++) {
cout << i << " ";
}

2. while Loop:

cpp
Copy code
int i = 0;
while (i < 5) {
cout << i << " ";
i++;
}

3. do-while Loop:

cpp
Copy code
int i = 0;
do {
cout << i << " ";
i++;
} while (i < 5);

c. Jump Statements

1. break:
o Exits the current loop.

cpp
Copy code
for (int i = 0; i < 10; i++) {
if (i == 5) break;
cout << i << " ";
}

2. continue:
o Skips the rest of the current iteration.

cpp
Copy code
for (int i = 0; i < 10; i++) {
if (i == 5) continue;
cout << i << " ";
}

3. return:
o Exits from a function.

cpp
Copy code
return 0;

1. Simple Functions

Functions are blocks of code designed to perform specific tasks. They make programs modular,
reusable, and readable.

Structure:

1. Function Declaration (Prototype): Declares the function signature.

cpp
Copy code
return_type function_name(parameters);
2. Function Definition: Contains the implementation.

cpp
Copy code
return_type function_name(parameters) {
// Code
return value; // Optional for void type
}

3. Function Call: Executes the function.

Example:

cpp
Copy code
#include <iostream>
using namespace std;

// Function Declaration
int add(int a, int b);

// Main Function
int main() {
int x = 5, y = 10;
cout << "Sum: " << add(x, y) << endl; // Function Call
return 0;
}

// Function Definition
int add(int a, int b) {
return a + b;
}

2. Call and Return by Reference

Call by Reference:

 Passes the address of variables to the function.


 Modifications in the function affect the original variables.

Syntax:

cpp
Copy code
void function_name(data_type &parameter) { }

Example:

cpp
Copy code
#include <iostream>
using namespace std;

void increment(int &n) { // Reference parameter


n++; // Modifies the original variable
}

int main() {
int num = 10;
increment(num); // Call by reference
cout << "Value after increment: " << num << endl; // Outputs 11
return 0;
}

Return by Reference:

 Returns a reference to the caller.


 Allows the returned value to be modified directly.

Example:

cpp
Copy code
#include <iostream>
using namespace std;

int& getLargeElement(int arr[], int size) {


int maxIdx = 0;
for (int i = 1; i < size; i++) {
if (arr[i] > arr[maxIdx]) {
maxIdx = i;
}
}
return arr[maxIdx]; // Return reference to the largest element
}

int main() {
int arr[] = {1, 3, 7, 2, 5};
int &largest = getLargeElement(arr, 5);
largest = 10; // Modifies the original array
for (int num : arr) {
cout << num << " "; // Outputs: 1 3 10 2 5
}
return 0;
}

3. Inline Functions

 Defined with the inline keyword.


 Replaces the function call with the function body at compile time.
 Used for small, frequently called functions to reduce function call overhead.
Syntax:

cpp
Copy code
inline return_type function_name(parameters) { }

Example:

cpp
Copy code
#include <iostream>
using namespace std;

inline int square(int x) {


return x * x;
}

int main() {
cout << "Square of 5: " << square(5) << endl; // Replaces with 5 * 5
return 0;
}

4. Macro vs. Inline Functions

Macros:

 Preprocessor directive (#define) replaces code before compilation.


 No type-checking or debugging.

Example:

cpp
Copy code
#include <iostream>
#define SQUARE(x) (x * x) // Macro

int main() {
cout << "Square of 5: " << SQUARE(5) << endl; // Outputs 25
return 0;
}

Differences:

Aspect Macro Inline Function


Type-checking No Yes
Debugging Difficult Easier
Scope Global Within class/file
5. Function Overloading

 Allows multiple functions with the same name but different parameter lists.
 Compiler differentiates based on the number/types of arguments.

Example:

cpp
Copy code
#include <iostream>
using namespace std;

void print(int x) { cout << "Integer: " << x << endl; }


void print(double x) { cout << "Double: " << x << endl; }
void print(string x) { cout << "String: " << x << endl; }

int main() {
print(10); // Calls int version
print(3.14); // Calls double version
print("Hello"); // Calls string version
return 0;
}

6. Default Arguments

 Function parameters can have default values, used if no arguments are provided during
the call.

Syntax:

cpp
Copy code
void function_name(data_type param = default_value) { }

Example:

cpp
Copy code
#include <iostream>
using namespace std;

void greet(string name = "Guest") {


cout << "Hello, " << name << "!" << endl;
}

int main() {
greet(); // Uses default argument
greet("Alice"); // Overrides default argument
return 0;
}
7. Friend Functions

 A friend function can access private/protected members of a class.


 Declared using the friend keyword inside the class.

Example:

cpp
Copy code
#include <iostream>
using namespace std;

class Box {
private:
int width;

public:
Box(int w) : width(w) {}
friend void printWidth(Box b); // Friend function declaration
};

void printWidth(Box b) {
cout << "Width: " << b.width << endl; // Accesses private member
}

int main() {
Box box(10);
printWidth(box);
return 0;
}

8. Virtual Functions

 Declared using the virtual keyword.


 Enables runtime polymorphism (method overriding).
 Ensures the derived class version of the function is called.

Example:

cpp
Copy code
#include <iostream>
using namespace std;

class Base {
public:
virtual void show() { // Virtual function
cout << "Base class function" << endl;
}
};
class Derived : public Base {
public:
void show() override { // Overriding function
cout << "Derived class function" << endl;
}
};

int main() {
Base *b;
Derived d;
b = &d;

b->show(); // Calls Derived class's show() due to virtual


return 0;
}

Neeraj Chaurasiya

You might also like