0% found this document useful (0 votes)
11 views8 pages

C++ Core

The document covers C++ syntax fundamentals, including program structure, variables, data types, and operators. It explains control structures, functions, arrays, and pointers, providing examples for each concept. Key topics include decision-making, loops, function overloading, and the relationship between arrays and pointers.

Uploaded by

SAYAN NAYEK
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)
11 views8 pages

C++ Core

The document covers C++ syntax fundamentals, including program structure, variables, data types, and operators. It explains control structures, functions, arrays, and pointers, providing examples for each concept. Key topics include decision-making, loops, function overloading, and the relationship between arrays and pointers.

Uploaded by

SAYAN NAYEK
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

C++ syntax fundamentals

C++ syntax fundamentals include program structure with main(), variables and data types, and
operators for arithmetic, relational, logical, and bitwise operations.

1. Program Structure & main() Function


• Every C++ program begins with header files like #include <iostream> for input/output.

• The main function int main() { ... } is the entry point of the program.

• Each statement ends with a semicolon ;.

• return 0; indicates the program finished successfully.

2. Variables & Data Types


Variables are used to store data. Each variable has a type:

• int → whole numbers (e.g., int age = 20;)

• double → decimal numbers (e.g., double pi = 3.14;)

• char → single character (e.g., char grade = 'A';)

• bool → true/false values (e.g., bool isPassed = true;)

3. Operators
Operators perform actions on data:

• Arithmetic → + , - , * , / , % (basic math)

• Relational → == , != , > , < , >= , <= (comparison)

• Logical → && , || , ! (conditions)

• Bitwise → & , | , ^ , << , >> (binary-level operations)

💻 Example Program
#include <iostream>
using namespace std;

int main() {
int a = 10, b = 5;
double result;
char grade = 'A';
bool isPassed = true;

// Arithmetic
result = a + b;
cout << "Sum: " << result << endl;
// Relational
cout << "Is a greater than b? " << (a > b) << endl;

// Logical
cout << "Is a>0 AND b>0? " << (a > 0 && b > 0) << endl;

// Bitwise
cout << "Bitwise AND of a & b: " << (a & b) << endl;

cout << "Grade: " << grade << ", Passed: " << isPassed << endl;

return 0;
}

Control Structures in C++

Control structures in C++ include decision-making (if-else, switch, ternary), loops (for, while, do-
while), and jump statements (break, continue, goto). They control the flow of execution in a
program.

💻 Theory
1. Decision Making
• if-else → Executes code based on condition.

• switch → Used when you have multiple possible values for one variable.

• ternary operator (?:) → Short form of if-else.

2. Loops
• for loop → Used when you know how many times to repeat.

• while loop → Runs while condition is true.

• do-while loop → Runs at least once, then checks condition.

3. Jump Statements
• break → Exits loop or switch immediately.

• continue → Skips current iteration and moves to next.

• goto → Jumps to a labeled statement (rarely used, not recommended).

💻 Example Program

#include <iostream>
using namespace std;

int main() {
int num = 3;
// if-else
if (num > 0) {
cout << "Positive number" << endl;
} else {
cout << "Non-positive number" << endl;
}

// switch
switch (num) {
case 1: cout << "Number is One" << endl; break;
case 2: cout << "Number is Two" << endl; break;
case 3: cout << "Number is Three" << endl; break;
default: cout << "Other number" << endl;
}

// ternary operator
string result = (num % 2 == 0) ? "Even" : "Odd";
cout << "Number is " << result << endl;

// for loop
cout << "For loop: ";
for (int i = 1; i <= 5; i++) {
cout << i << " ";
}
cout << endl;

// while loop
cout << "While loop: ";
int j = 1;
while (j <= 3) {
cout << j << " ";
j++;
}
cout << endl;

// do-while loop
cout << "Do-while loop: ";
int k = 1;
do {
cout << k << " ";
k++;
} while (k <= 3);
cout << endl;

// break and continue


cout << "Break and Continue demo: ";
for (int i = 1; i <= 5; i++) {
if (i == 3) continue; // skip 3
if (i == 5) break; // stop at 5
cout << i << " ";
}
cout << endl;

// goto (limited use)


int x = 1;
goto label;
cout << "This will be skipped" << endl;
label:
cout << "Goto jumped here!" << endl;

return 0;
}

Functions in C++

Functions in C++ can be declared, defined, and called. They support pass by value, pass by
reference, default arguments, and function overloading for flexibility.

1. Function Declaration, Definition, and Prototypes


• Declaration (Prototype) → tells the compiler about the function name, return type, and
parameters. Example: int add(int, int);

• Definition → actual body of the function where logic is written.


Example:
int add(int a, int b) {
return a + b;
}
Calling a function → use the function name in main() to execute it.

2. Pass by Value vs Pass by Reference


• Pass by Value → A copy of the variable is passed. Changes inside the function do not affect
the original variable.

• Pass by Reference → The actual variable (memory address) is passed. Changes inside the
function affect the original variable.
💻 Summary: Value = copy, Reference = original.

3. Default Arguments
• You can give default values to parameters.

• If no value is passed, the default is used. Example:


int add(int a, int b = 5) {
return a + b;
}

Calling add(10) will return 15.


4. Function Overloading
• Same function name but different parameter types or numbers.

• Compiler decides which one to call based on arguments. Example:


int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; }
Summary: Overloading = same name, different parameters.

💻 Example Program

#include <iostream>
using namespace std;

// Function prototype
int add(int, int);

// Pass by value
void passByValue(int x) {
x = x + 10;
cout << "Inside function (value): " << x << endl;
}

// Pass by reference
void passByReference(int &x) {
x = x + 10;
cout << "Inside function (reference): " << x << endl;
}

// Default argument
int multiply(int a, int b = 2) {
return a * b;
}

// Function overloading
int square(int x) { return x * x; }
double square(double x) { return x * x; }

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

int main() {
int num = 5;

// Function call
cout << "Addition: " << add(3, 4) << endl;

// Pass by value
passByValue(num);
cout << "After passByValue: " << num << endl;
// Pass by reference
passByReference(num);
cout << "After passByReference: " << num << endl;

// Default argument
cout << "Multiply with default: " << multiply(5) << endl;
cout << "Multiply with given: " << multiply(5, 3) << endl;

// Function overloading
cout << "Square int: " << square(4) << endl;
cout << "Square double: " << square(4.5) << endl;

return 0;
}

Arrays & Pointers

Arrays store multiple values in continuous memory, while pointers store memory addresses. Arrays
and pointers are closely related because the array name itself acts like a pointer to the first element.
Pointer arithmetic allows traversal of arrays efficiently.

💻 Detailed Theory
1. Arrays
• Declaration → int arr[5]; (creates an array of 5 integers).

• Initialization → int arr[5] = {1, 2, 3, 4, 5};.

• Accessing elements → arr[0] gives first element.

• Multi-dimensional arrays → arrays inside arrays. Example: int matrix[2][3] =


{{1,2,3}, {4,5,6}};.
💻 Summary: Arrays store multiple values of same type in continuous memory.

2. Pointers Basics
• Pointer → variable that stores memory address.

• * (dereference operator) → access value at address.

• & (address-of operator) → gives memory address of variable. Example:

int x = 10;
int *ptr = &x; // ptr stores address of x
cout << *ptr; // prints value of x (10)

💻 Summary: Pointer = variable that holds address of another variable.


3. Pointer Arithmetic & Array-Pointer Relationship
• You can move pointer using arithmetic:

• ptr++ → moves to next memory location.

• ptr-- → moves to previous memory location.

• Array-Pointer relationship → array name itself acts like a pointer to first element.
Example:
int arr[3] = {10, 20, 30};
int *ptr = arr; // same as &arr[0]
cout << *(ptr+1); // prints 20
💻 Summary: Arrays and pointers are closely related; array name is pointer to first element.

💻 Example Program

#include <iostream>
using namespace std;

int main() {
// Array declaration and initialization
int arr[5] = {10, 20, 30, 40, 50};

cout << "Array elements: ";


for (int i = 0; i < 5; i++) {
cout << arr[i] << " ";
}
cout << endl;

// Multi-dimensional array
int matrix[2][3] = {{1,2,3}, {4,5,6}};
cout << "Matrix element [1][2]: " << matrix[1][2] << endl;

// Pointer basics
int x = 100;
int *ptr = &x;
cout << "Value of x using pointer: " << *ptr << endl;
cout << "Address of x: " << ptr << endl;

// Pointer arithmetic
cout << "Array using pointer: ";
int *p = arr; // points to first element
for (int i = 0; i < 5; i++) {
cout << *(p+i) << " "; // pointer arithmetic
}
cout << endl;

return 0;
}
💻 Explanation of Example
• Array → arr[5] stores 5 integers.

• Matrix → matrix[2][3] is a 2x3 multi-dimensional array.

• Pointer → ptr stores address of x, *ptr gives value of x.

• Pointer arithmetic → (p+i) moves pointer to next element of array.

Common questions

Powered by AI

'If-else' statements execute code based on boolean conditions; 'switch' is used for multiple potential values of a single variable and passes control to matching case statements; 'ternary' operators condense simple 'if-else' checks into a single line, often used for quick assignments based on conditions .

Loops such as 'for', 'while', and 'do-while' are efficient for iterating over sets of data when the number of iterations is known or depends on a condition. They repeat code execution until a condition is false. Conditional statements like 'if-else' or 'switch' execute based on conditions but are not naturally designed for repeated execution, making loops generally more efficient for iteration .

In C++, 'int' is used for whole numbers such as 20, 'double' is for decimal numbers like 3.14, 'char' is for single characters such as 'A', and 'bool' is for true/false values .

Using 'goto' in C++ can lead to spaghetti code, reducing code readability and maintainability due to its ability to jump to arbitrary code sections, complicating the control flow. Typically, structured constructs like loops and function calls can replace 'goto', making its use rare. However, in certain low-level programming tasks where direct control transfer is unavoidable, its benefits might justify the drawbacks under strict control and minimal use .

Function overloading in C++ allows multiple functions to have the same name with different parameter types or numbers. This promotes flexibility by enabling functions to respond to the same operation with different data types and increases readability by using meaningful function names without artificially creating variations to distinguish different parameter types .

In C++, the 'main()' function serves as the starting point of any program execution, establishing the basic structure required for the syntax; it requires proper declarations, includes header files like #include <iostream>, and ends execution with 'return 0;' signaling successful completion .

C++ functions can utilize default arguments to allow parameters to assume a default value if no argument is provided during the function call. This simplifies function calls by reducing the number of required arguments and allows flexibility for optional parameter usage without overloading multiple functions for different argument scenarios .

'Pass by value' in C++ means the function receives a copy of the variable, preventing any change to the original variable and ensuring data protection. 'Pass by reference', however, passes the variable's address, allowing the function to modify the original variable directly, making it useful for operations where changes need to reflect post-function execution but also risk unwanted data alteration .

Pointer arithmetic in C++ allows direct memory address manipulation, enabling efficient iteration over an array by incrementing the pointer to access contiguous memory locations. Compared to standard array indexing, pointer arithmetic can reduce overhead in some operations and offers a more granular control over data manipulation, particularly beneficial in performance-critical applications .

Arrays and pointers in C++ are closely related because the name of an array is a pointer to its first element. Pointers allow for efficient traversal and manipulation of arrays using pointer arithmetic, moving through memory locations directly, which facilitates better control and management of resources .

You might also like