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

Unit 2 (C++)

The document contains various C++ programs and algorithms related to array manipulation, sorting techniques, and pointer usage. It includes examples of counting automobile sales, inserting and deleting elements in arrays, and performing linear and binary searches. Additionally, it discusses sorting algorithms like bubble sort, insertion sort, and selection sort, along with examples of pointer types such as null, void, and wild pointers.

Uploaded by

vikasjaat90675
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)
15 views13 pages

Unit 2 (C++)

The document contains various C++ programs and algorithms related to array manipulation, sorting techniques, and pointer usage. It includes examples of counting automobile sales, inserting and deleting elements in arrays, and performing linear and binary searches. Additionally, it discusses sorting algorithms like bubble sort, insertion sort, and selection sort, along with examples of pointer types such as null, void, and wild pointers.

Uploaded by

vikasjaat90675
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

Unit = 2(c++)

#include <iostream>

using namespace std;

const int START_YEAR = 1932;

const int END_YEAR = 1984;

const int SIZE = END_YEAR - START_YEAR + 1;

int main() {

int AUTO[SIZE]; // Array to hold sales data from 1932 to 1984

// Sample input for demonstration

cout << "Enter automobile sales for each year from 1932 to 1984:\n";

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

cout << "Year " << (START_YEAR + i) << ": ";

cin >> AUTO[i];

// Part (a): Count number of years with sales > 300

int NUM = 0;

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

if (AUTO[i] > 300) {

NUM++;
}

cout << "\nNumber of years with sales more than 300: " << NUM << endl;

// Part (b): Print year and number of automobiles sold

cout << "\nYear-wise Automobile Sales:\n";

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

cout << START_YEAR + i << " : " << AUTO[i] << " automobiles\n";

return 0;

Year 1932: 120

Year 1933: 450

Year 1934: 600

Number of years with sales more than 300: 2

Year-wise Automobile Sales:

1932 : 120 automobiles

1933 : 450 automobiles

1934 : 600 automobiles


✅ 1. Algorithm to Insert an Element into an Array
Algorithm InsertElement(A, n, pos, val)

1. Start

2. Input the array A of size n

3. Input the position (pos) where val should be inserted

4. Input the value (val) to insert

5. If pos < 0 or pos > n, print "Invalid position" and exit

6. Shift all elements from position n-1 to pos one position to the right

7. Set A[pos] = val

8. Increment n by 1

9. Print the updated array

10. End

✅ 2. Algorithm to Delete an Element from an Array


Algorithm DeleteElement(A, n, pos)

1. Start

2. Input the array A of size n

3. Input the position (pos) of the element to delete

4. If pos < 0 or pos ≥ n, print "Invalid position" and exit

5. Shift all elements from pos+1 to n-1 one position to the left

6. Decrease n by 1

7. Print the updated array

8. End

✅ 3. Algorithm for Linear Search


Algorithm LinearSearch(A, n, key)

1. Start

2. Input the array A of size n and the value to search (key)

3. Set found = false

4. For i = 0 to n-1, do

5. If A[i] == key, then

6. Print "Element found at index i"

7. Set found = true and break

8. If found == false, print "Element not found"

9. End

✅ 4. Algorithm for Binary Search (Array must be sorted)


Algorithm BinarySearch(A, n, key)

1. Start

2. Input the sorted array A of size n and the key to search

3. Set low = 0, high = n - 1

4. While low ≤ high, do

5. Set mid = (low + high) / 2

6. If A[mid] == key, print "Element found at index mid" and exit

7. Else if A[mid] < key, set low = mid + 1

8. Else set high = mid - 1

9. Print "Element not found" if loop ends

10. End
✅ 1. Bubble Sort – Theoretical Algorithm
Definition:
Bubble Sort is a comparison-based sorting technique. It works by repeatedly comparing
adjacent elements and swapping them if they are in the wrong order. The largest elements
"bubble" to the end with each pass.

🔸 Steps:
1. Begin with the first element of the array.
2. Compare it with the next element.
3. If the current element is greater than the next, swap them.
4. Move to the next pair and repeat the comparison and swap if needed.
5. Continue this process until the end of the array. This completes one pass.
6. Repeat the process for all elements except the last sorted ones.
7. After each pass, the next largest element is placed in its correct position.
8. Continue the passes until no more swaps are needed or all elements are sorted.

✅ 2. Insertion Sort – Theoretical Algorithm


Definition:
Insertion Sort builds the final sorted array one element at a time by inserting each element
into its correct position relative to the sorted part of the array.

🔸 Steps:
1. Start with the second element (since the first element is trivially sorted).
2. Compare it with the elements before it.
3. Shift all larger elements one position to the right.
4. Insert the current element into the position where it is larger than the one before and
smaller than the one after.
5. Repeat the process for all remaining elements.
6. The array gets divided into a sorted and an unsorted part, which gets merged during each
insertion.
7. Continue until all elements are inserted into their correct positions.
8. The array is now sorted.

✅ 3. Selection Sort – Theoretical Algorithm


Definition:
Selection Sort sorts an array by repeatedly finding the minimum (or maximum) element from
the unsorted part and placing it at the beginning.

🔸 Steps:
1. Start from the first element of the array.
2. Find the smallest element in the entire array.
3. Swap this smallest element with the first element.
4. Now, the first element is in the correct position.
5. Move to the second element and repeat the process for the remaining unsorted part.
6. Continue finding the minimum from the remaining unsorted elements and swapping with
the front.
7. Repeat until all elements are placed in their correct positions.
8. The array is now sorted in ascending order.

🔷 Sample Array:
We will use this array for all examples:
A = [5, 2, 9, 1]

✅ 1. Bubble Sort Visualization


Concept: Repeatedly swap adjacent elements if they are in the wrong order.

Pass-by-Pass:

Pass 1:

Compare 5 and 2 → swap → [2, 5, 9, 1]


Compare 5 and 9 → OK → [2, 5, 9, 1]
Compare 9 and 1 → swap → [2, 5, 1, 9]

Pass 2:

Compare 2 and 5 → OK → [2, 5, 1, 9]


Compare 5 and 1 → swap → [2, 1, 5, 9]

Pass 3:

Compare 2 and 1 → swap → [1, 2, 5, 9]

Sorted Array: [1, 2, 5, 9]

✅ 2. Insertion Sort Visualization


Concept: Build the sorted array one item at a time by inserting elements in the correct
position.

Step-by-Step:

Step 1:
2 is compared with 5 → insert before 5 → [2, 5, 9, 1]
Step 2:
9 is compared with 5 → stays in place → [2, 5, 9, 1]

Step 3:
1 is compared with 9, 5, 2 → insert before all → [1, 2, 5, 9]

Sorted Array: [1, 2, 5, 9]

✅ 3. Selection Sort Visualization


Concept: Repeatedly select the minimum from unsorted part and put it in the correct place.

Step-by-Step:

Step 1:
Find min in [5, 2, 9, 1] → 1
Swap with A[0] → [1, 2, 9, 5]

Step 2:
Find min in [2, 9, 5] → 2
Swap with A[1] → [1, 2, 9, 5]

Step 3:
Find min in [9, 5] → 5
Swap with A[2] → [1, 2, 5, 9]

Sorted Array: [1, 2, 5, 9]

✅ Program: Sum of Even and Odd Elements in a 2D Array


#include <iostream>

using namespace std;

int main() {

int rows, cols;

cout << "Enter number of rows and columns: ";

cin >> rows >> cols;

int A[100][100]; // assuming max size 100x100


int evenSum = 0, oddSum = 0;

cout << "Enter elements of the 2D array:\n";

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

for (int j = 0; j < cols; j++) {

cin >> A[i][j];

if (A[i][j] % 2 == 0)

evenSum += A[i][j];

else

oddSum += A[i][j];

cout << "Sum of even numbers: " << evenSum << endl;

cout << "Sum of odd numbers: " << oddSum << endl;

return 0;

🔹 Sample Input:
Enter number of rows and columns: 2 3

Enter elements of the 2D array:

123

456
🔹 Output:
Sum of even numbers: 12

Sum of odd numbers: 9

Null pointer

We can create a null pointer by assigning null value during the pointer declaration. This method is useful
when you do not have any address assigned to the pointer. A null pointer always contains value 0.

Following program illustrates the use of a null pointer:

#include <stdio.h>

int main()

int *p = NULL; //null pointer

printf(“The value inside variable p is:\n%x”,p);

return 0;

Output:

The value inside variable p is:

2. Void Pointer

In C programming, a void pointer is also called as a generic pointer. It does not have any standard data
type. A void pointer is created by using the keyword void. It can be used to store an address of any
variable.

Following program illustrates the use of a void pointer:

#include <stdio.h>

int main()

void *p = NULL; //void pointer

printf("The size of pointer is:%d\n",sizeof(p));


return 0;

Output:

The size of pointer is:4

3. Wild pointer

A pointer is said to be a wild pointer if it is not being initialized to anything. These types of pointers are not
efficient because they may point to some unknown memory location which may cause problems in our
program and it may lead to crashing of the program. One should always be careful while working with wild
pointers.

Following program illustrates the use of wild pointer:

#include <stdio.h>

int main()

int *p; //wild pointer

printf("\n%d",*p);

return 0;

Output:

timeout: the monitored command dumped core

sh: line 1: 95298 Segmentation fault timeout 10s main

✅ 1. Pointer Example
A pointer stores the address of another variable.

cpp

CopyEdit

#include <iostream>

using namespace std;


int main() {

int a = 10;

int* ptr = &a; // ptr points to address of a

cout << "Value of a: " << a << endl;

cout << "Address of a: " << &a << endl;

cout << "Value of ptr (address): " << ptr << endl;

cout << "Value at address ptr points to (*ptr): " << *ptr << endl;

return 0;

✅ 2. Pass by Value Example


A copy of the variable is passed to the function. The original variable is not changed.

cpp

CopyEdit

#include <iostream>

using namespace std;

void modify(int x) {

x = x + 10;

int main() {
int a = 5;

modify(a);

cout << "After pass by value, a = " << a << endl; // Output: 5

return 0;

✅ 3. Pass by Address Example (using pointer)


The address of the variable is passed, so the original value is changed.

cpp

CopyEdit

#include <iostream>

using namespace std;

void modify(int* x) {

*x = *x + 10;

int main() {

int a = 5;

modify(&a);

cout << "After pass by address, a = " << a << endl; // Output: 15

return 0;

✅ 4. Pass by Reference Example


A reference (alias) to the original variable is passed, so the original value is changed.
cpp

CopyEdit

#include <iostream>

using namespace std;

void modify(int& x) {

x = x + 10;

int main() {

int a = 5;

modify(a);

cout << "After pass by reference, a = " << a << endl; // Output: 15

return 0;

You might also like