[go: up one dir, main page]

0% found this document useful (0 votes)
39 views19 pages

Unit-1 Intro To C++

Free

Uploaded by

omshuka129
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)
39 views19 pages

Unit-1 Intro To C++

Free

Uploaded by

omshuka129
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/ 19

Unit-1

Introduction to C++
C++ is a general-purpose, object-oriented programming language created by
Bjarne Stroustrup in the early 1980s as an extension of the C language. C++
supports various programming paradigms like procedural, object-oriented, and
generic programming, making it a versatile tool for software development. Its
syntax includes standard input (cin>>) and output (cout<<), which are used for
handling user input and displaying output respectively.
Conditional Statements
Conditional statements allow the program to make decisions based on certain
conditions:
1. if statement: Executes a block of code if a specified condition is true. If
the condition evaluates to false, the program skips the block.
Syntax
if (condition) {
// Code to execute if condition is true
}
2. if-else statement: If the condition is true, it executes the code inside the
if block; otherwise, the code inside the else block is executed.
Syntax

if (condition) {
// Code if condition is true
} else {
// Code if condition is false
}
3. Nested if-else statement: Allows multiple conditional evaluations by
placing an if or else-if inside another if or else block.
Syntax
if (condition1) {
// Code if condition1 is true
} else if (condition2) {
// Code if condition2 is true
} else {
// Code if both are false
}
4. Switch statement: The switch statement evaluates an expression and
executes the corresponding case block if a match is found. It simplifies
multiple if-else conditions.
Syntax

switch (expression) {
case value1:
// Code for value1
break;
case value2:
// Code for value2
break;
default:
// Code if no case matches
}
Loops
Loops are used to execute a block of code repeatedly until a certain condition is
met:
1. while loop: Continuously executes the block of code as long as the
condition is true.
Syntax

while (condition) {
// Code to execute while condition is true
}
2. do-while loop: Similar to while, but ensures that the block of code
executes at least once before checking the condition.
Syntax

do {
// Code to execute
} while (condition);
3. for loop: Typically used when the number of iterations is known. It
consists of an initialization, a condition, and an increment step.
Syntax

for (initialization; condition; increment) {


// Code to execute
}
Manipulators in C++
Manipulators are used to control the formatting of output. They are included in
the <iomanip> library.
1. setw(): Sets the width for the next output.
Syntax
cout << setw(10) << value;
2. setfill(): Fills the remaining width with a specified character.
Syntax

cout << setfill('*') << setw(10) << value;


3. setprecision(): Sets the precision of floating-point numbers.
Syntax

cout << setprecision(2) << fixed << value;


4. setbase(): Changes the numerical base of output (e.g., base 8, 10, or 16).
Syntax

cout << setbase(16) << value;


Data Types, Identifiers, and Typecasting
• Data Types: C++ supports basic data types such as int, char, float, and
double. These define the type of data a variable can store.
• Identifiers: Names given to variables, functions, arrays, etc. They must
begin with a letter or underscore and can contain letters, digits, and
underscores.
• Typecasting: This is the process of converting one data type into another,
either implicitly (automatic conversion by the compiler) or explicitly
(forced by the programmer using casting operators like (int)).
Arrays
An array is a collection of elements of the same data type, stored in contiguous
memory locations.
1. 1-D Array: A linear arrangement of elements that can be accessed using
indices.
Syntax
int arr[5] = {1, 2, 3, 4, 5};
2. 2-D Array: A matrix-like arrangement of rows and columns.
Syntax

int arr[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};


Character Array and String Functions
In C++, strings can be represented as character arrays or using the string class.
Common string functions include:
• strlen(): Returns the length of a string.
Syntax

int len = strlen(str);


• strcmp(): Compares two strings lexicographically.
Syntax

if (strcmp(str1, str2) == 0) {
// Strings are equal
}
• strcat(): Concatenates two strings.
Syntax

strcat(str1, str2);
Pointers
Pointers are variables that store memory addresses. They are fundamental for
dynamic memory management in C++.
1. Dangling Pointer: A pointer pointing to a memory location that has been
freed or deleted, leading to undefined behavior.
2. Void Pointer: A generic pointer that can hold the address of any data
type. It must be explicitly cast to the correct type before dereferencing.
Syntax

void* ptr;
3. Null Pointer: A pointer initialized to nullptr, representing that it points to
nothing.
Syntax

int* ptr = nullptr;


Reference Variables
A reference variable is an alias for another variable, providing an alternative
name to the original variable. It is created using the & operator and is useful in
functions for passing large data structures without copying them.
Syntax

int a = 10;
int& ref = a;
1. Conditional Statements
Solved Program 1: Check if a number is positive, negative, or zero
#include <iostream>
using namespace std;

int main() {
int num;
cout << "Enter a number: ";
cin >> num;

if (num > 0)
cout << num << " is positive.";
else if (num < 0)
cout << num << " is negative.";
else
cout << "The number is zero.";

return 0;
}
Solved Program 2: Find the largest of three numbers using nested if
#include <iostream>
using namespace std;

int main() {
int a, b, c;
cout << "Enter three numbers: ";
cin >> a >> b >> c;

if (a > b) {
if (a > c)
cout << a << " is the largest.";
else
cout << c << " is the largest.";
} else {
if (b > c)
cout << b << " is the largest.";
else
cout << c << " is the largest.";
}

return 0;
}
Solved Program 3: Grade system using switch case
#include <iostream>
using namespace std;

int main() {
char grade;
cout << "Enter your grade (A/B/C/D/F): ";
cin >> grade;

switch(grade) {
case 'A': cout << "Excellent!"; break;
case 'B': cout << "Well done!"; break;
case 'C': cout << "Good!"; break;
case 'D': cout << "Pass"; break;
case 'F': cout << "Fail"; break;
default: cout << "Invalid grade!";
}

return 0;
}
Unsolved Program 1
Write a program to check whether a given year is a leap year or not using an if-
else statement.
Unsolved Program 2
Write a program that takes an integer and prints whether it is odd or even
using a nested if-else.
Unsolved Program 3
Using a switch case, write a program that takes a number from 1 to 7 and prints
the corresponding day of the week.

2. Loops
Solved Program 1: Print numbers from 1 to 10 using a for loop
#include <iostream>
using namespace std;

int main() {
for (int i = 1; i <= 10; i++) {
cout << i << " ";
}
return 0;
}
Solved Program 2: Sum of first 5 natural numbers using while loop
#include <iostream>
using namespace std;

int main() {
int i = 1, sum = 0;

while (i <= 5) {
sum += i;
i++;
}

cout << "Sum of first 5 natural numbers is: " << sum;
return 0;
}
Solved Program 3: Factorial of a number using do-while loop
#include <iostream>
using namespace std;

int main() {
int num, fact = 1, i = 1;
cout << "Enter a number: ";
cin >> num;

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

cout << "Factorial of " << num << " is " << fact;
return 0;
}
Unsolved Program 1
Write a program to print all even numbers between 1 and 50 using a for loop.
Unsolved Program 2
Write a program to find the sum of all odd numbers between 1 and 100 using a
while loop.
Unsolved Program 3
Write a program to reverse a number using a do-while loop.

3. Manipulators
Solved Program 1: Set width using setw()
#include <iostream>
#include <iomanip>
using namespace std;

int main() {
cout << setw(10) << "Name" << setw(10) << "Age" << endl;
cout << setw(10) << "John" << setw(10) << "25" << endl;
cout << setw(10) << "Alice" << setw(10) << "30" << endl;
return 0;
}
Solved Program 2: Set precision using setprecision()
#include <iostream>
#include <iomanip>
using namespace std;

int main() {
double pi = 3.141592653589793;
cout << setprecision(4) << pi << endl;
cout << setprecision(6) << pi << endl;
return 0;
}
Solved Program 3: Change base using setbase()
#include <iostream>
#include <iomanip>
using namespace std;

int main() {
int num = 255;
cout << "Decimal: " << num << endl;
cout << "Hexadecimal: " << setbase(16) << num << endl;
cout << "Octal: " << setbase(8) << num << endl;
return 0;
}
Unsolved Program 1
Write a program that displays numbers in different widths using setw().
Unsolved Program 2
Write a program that displays a floating-point number with varying precision
using setprecision().
Unsolved Program 3
Write a program that displays numbers in binary, octal, and hexadecimal
formats using setbase().

4. Arrays
Solved Program 1: Sum of elements in a 1-D array
#include <iostream>
using namespace std;

int main() {
int arr[5] = {1, 2, 3, 4, 5}, sum = 0;

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


sum += arr[i];
}

cout << "Sum of elements: " << sum;


return 0;
}
Solved Program 2: Transpose of a 2-D array
#include <iostream>
using namespace std;

int main() {
int matrix[2][2] = {{1, 2}, {3, 4}};

cout << "Transpose:\n";


for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
cout << matrix[j][i] << " ";
}
cout << endl;
}

return 0;
}
Solved Program 3: Find largest element in an array
#include <iostream>
using namespace std;

int main() {
int arr[5] = {10, 5, 20, 15, 25}, max = arr[0];

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


if (arr[i] > max) max = arr[i];
}

cout << "Largest element: " << max;


return 0;
}
Unsolved Program 1
Write a program to find the smallest element in a 1-D array.
Unsolved Program 2
Write a program to multiply two 2-D arrays.
Unsolved Program 3
Write a program to sort a 1-D array in ascending order.

5. Strings
Solved Program 1: Find length of a string using strlen()
#include <iostream>
#include <cstring>
using namespace std;

int main() {
char str[50];
cout << "Enter a string: ";
cin.getline(str, 50);

cout << "Length of string: " << strlen(str);


return 0;
}
Solved Program 2: Compare two strings using strcmp()
#include <iostream>
#include <cstring>
using namespace std;

int main() {
char str1[50], str2[50];
cout << "Enter first string: ";
cin.getline(str1, 50);
cout << "Enter second string: ";
cin.getline(str2, 50);

if (strcmp(str1, str2) == 0)
cout << "Strings are equal.";
else
cout << "Strings are not equal.";

return 0;
}
Solved Program 3: Concatenate two strings using strcat()
#include <iostream>
#include <cstring>
using namespace std;

int main() {
char str1[50], str2[50];
cout << "Enter first string: ";
cin.getline(str1, 50);
cout << "Enter second string: ";
cin.getline(str2, 50);

strcat(str1, str2);
cout << "Concatenated string: " << str1;

return 0;
}
Unsolved Program 1
Write a program to reverse a string.
Unsolved Program 2
Write a program to check whether two strings are palindromes of each other.
Unsolved Program 3
Write a program to find the frequency of a character in a string.

6. Pointers
Solved Program 1: Basic pointer example
#include <iostream>
using namespace std;

int main() {
int a = 10;
int* p = &a;
cout << "Value of a: " << a << endl;
cout << "Address of a: " << p << endl;
cout << "Value pointed by p: " << *p << endl;

return 0;
}
Solved Program 2: Null pointer example
#include <iostream>
using namespace std;

int main() {
int* p = nullptr;

if (p == nullptr)
cout << "Pointer is null.";
else
cout << "Pointer is not null.";

return 0;
}
Solved Program 3: Dangling pointer example
#include <iostream>
using namespace std;

int main() {
int* p = new int(10);
delete p; // Pointer is now dangling

// Accessing p after deletion causes undefined behavior


// cout << *p;

return 0;
}
Unsolved Program 1
Write a program to swap two numbers using pointers.
Unsolved Program 2
Write a program to reverse an array using pointers.
Unsolved Program 3
Write a program to dynamically allocate memory for an array using pointers
and then free it.

You might also like