0% found this document useful (0 votes)
11 views

Reverse String in C++

This document provides multiple beginner-level C++ programs to reverse a string, including handling spaces and avoiding the use of STL functions. It covers various methods such as manual reversal using loops, recursion, and building a reversed string by appending characters. The document emphasizes simplicity and clarity for those preparing for coding interviews.

Uploaded by

Arfat shaikh
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 views

Reverse String in C++

This document provides multiple beginner-level C++ programs to reverse a string, including handling spaces and avoiding the use of STL functions. It covers various methods such as manual reversal using loops, recursion, and building a reversed string by appending characters. The document emphasizes simplicity and clarity for those preparing for coding interviews.

Uploaded by

Arfat shaikh
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/ 38

Reverse String in C++

give me beginner level reversing a string in c++ which conatins space

Here’s a simple C++ program to reverse a string that includes spaces. This example uses basic concepts,
making it beginner-friendly:

Code:

cpp

`#include <iostream>
#include <string>
#include <algorithm> // For std::reverse

int main() {
// Input the string
std::string inputString;
std::cout << "Enter a string: ";
std::getline(std::cin, inputString); // Use getline to handle spaces

// Reverse the string


std::reverse(inputString.begin(), inputString.end());

// Output the reversed string


std::cout << "Reversed string: " << inputString << std::endl;

return 0;
}
`

How it Works:

1. Input with spaces: The `std::getline` function is used to read a full line of text, including spaces.
2. Reversing the string: The `std::reverse` function from `<algorithm>` is applied to reverse the
string in place.
3. Output: The reversed string is printed.

Example Output:

csharp

`Enter a string: Hello World


Reversed string: dlroW olleH
`

dont use any stl

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 1/38
Here’s a beginner-friendly way to reverse a string in C++ without using any STL functions:

Code:

cpp

`#include <iostream>
using namespace std;

int main() {
// Input the string
char inputString[100];
cout << "Enter a string: ";
cin.getline(inputString, 100); // Use cin.getline to handle spaces

// Find the length of the string


int length = 0;
while (inputString[length] != '\0') {
length++;
}

// Reverse the string manually


for (int i = 0; i < length / 2; i++) {
char temp = inputString[i];
inputString[i] = inputString[length - i - 1];
inputString[length - i - 1] = temp;
}

// Output the reversed string


cout << "Reversed string: " << inputString << endl;

return 0;
}
`

How It Works:

1. Input Handling: The `cin.getline` function allows reading a string with spaces up to a maximum
length of 100 characters.
2. String Length Calculation: A `while` loop calculates the string length by iterating until the null
terminator (`\0`) is reached.
3. Manual Reversal: A `for` loop swaps characters from the start and end of the string until the
middle is reached.
4. Output: The reversed string is printed directly.

Example Output:

csharp

`Enter a string: Hello World


Reversed string: dlroW olleH
`

This method avoids using STL and demonstrates basic array and loop manipulation.

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 2/38
i dont want any inbuilt functin want to prepare for interview

Understood! Here's a pure implementation of reversing a string in C++ without using any inbuilt
functions:

Code:

cpp

`#include <iostream>
using namespace std;

int main() {
// Input the string
char inputString[100];
cout << "Enter a string: ";
cin.getline(inputString, 100); // Read input including spaces

// Find the length of the string (manually)


int length = 0;
while (inputString[length] != '\0') {
length++;
}

// Reverse the string manually


int start = 0, end = length - 1;
while (start < end) {
// Swap characters
char temp = inputString[start];
inputString[start] = inputString[end];
inputString[end] = temp;

// Move pointers
start++;
end--;
}

// Output the reversed string


cout << "Reversed string: " << inputString << endl;

return 0;
}
`

Explanation:

1. Input Handling:
`cin.getline(inputString, 100)` reads a string including spaces.
No other function is used for input manipulation.
2. Calculate Length Manually:
A `while` loop increments a counter (`length`) until the null terminator (`\0`) is reached.
3. Reverse Without STL:
Two pointers (`start` and `end`) are used to traverse the string.
Swap the characters at `start` and `end` using a temporary variable.
Move the pointers inward until they meet.
4. Output Result:

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 3/38
After the reversal, the modified array is printed as the reversed string.

Example Output:

kotlin

`Enter a string: Programming is fun


Reversed string: nuf si gnimmargorP
`

This implementation focuses entirely on manual logic and avoids all inbuilt functions, making it a great
practice for coding interviews.

some more code as a beginner level

Here are a few more beginner-level ways to reverse a string in C++ without using any inbuilt
functions. These examples highlight different approaches while keeping the logic simple.

1. Using a Temporary Array for Reversing:

cpp

`#include <iostream>
using namespace std;

int main() {
// Input the string
char inputString[100], reversedString[100];
cout << "Enter a string: ";
cin.getline(inputString, 100); // Read input including spaces

// Find the length of the string manually


int length = 0;
while (inputString[length] != '\0') {
length++;
}

// Fill the reversed array


for (int i = 0; i < length; i++) {
reversedString[i] = inputString[length - i - 1];
}

// Add null terminator to the reversed string


reversedString[length] = '\0';

// Output the reversed string


cout << "Reversed string: " << reversedString << endl;

return 0;
}
`

Explanation:

A temporary array (`reversedString`) is used to store the reversed characters.

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 4/38
The original string remains unchanged.

2. Using Recursion to Reverse a String:

cpp

`#include <iostream>
using namespace std;

// Function to reverse the string


void reverseString(char str[], int start, int end) {
if (start >= end) {
return;
}
// Swap the characters
char temp = str[start];
str[start] = str[end];
str[end] = temp;

// Recursive call
reverseString(str, start + 1, end - 1);
}

int main() {
// Input the string
char inputString[100];
cout << "Enter a string: ";
cin.getline(inputString, 100);

// Find the length manually


int length = 0;
while (inputString[length] != '\0') {
length++;
}

// Call the recursive function


reverseString(inputString, 0, length - 1);

// Output the reversed string


cout << "Reversed string: " << inputString << endl;

return 0;
}
`

Explanation:

This code uses a recursive function to reverse the string by swapping characters at the start and
end.
The function continues to swap until the pointers meet in the middle.

3. Using a Stack-Like Logic:

cpp

`#include <iostream>
using namespace std;

int main() {
// Input the string
char inputString[100], stack[100];
cout << "Enter a string: ";
cin.getline(inputString, 100);

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 5/38
// Push characters onto the stack
int length = 0, top = -1;
while (inputString[length] != '\0') {
stack[++top] = inputString[length];
length++;
}

// Pop characters from the stack for reversal


for (int i = 0; i < length; i++) {
inputString[i] = stack[top--];
}

// Output the reversed string


cout << "Reversed string: " << inputString << endl;

return 0;
}
`

Explanation:

A `stack` array is used to simulate stack behavior.


The characters are pushed onto the stack, and then popped in reverse order.

4. Swapping Using Only Loops (Without Extra Variables):

cpp

`#include <iostream>
using namespace std;

int main() {
// Input the string
char inputString[100];
cout << "Enter a string: ";
cin.getline(inputString, 100);

// Find the length manually


int length = 0;
while (inputString[length] != '\0') {
length++;
}

// Reverse by swapping
for (int i = 0; i < length / 2; i++) {
inputString[i] = inputString[i] + inputString[length - i - 1];
inputString[length - i - 1] = inputString[i] - inputString[length - i - 1];
inputString[i] = inputString[i] - inputString[length - i - 1];
}

// Output the reversed string


cout << "Reversed string: " << inputString << endl;

return 0;
}
`

Explanation:

This uses arithmetic operations (addition and subtraction) to swap characters without using an
extra variable.
It’s a fun way to explore swapping logic.

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 6/38
Practice Tip:

Experiment with these variations to get a deeper understanding of string manipulation. Each approach
demonstrates different thought processes, which is useful for interviews.

i want simple code without any prebuild functions as a beginner level

Here's a very simple C++ code to reverse a string, without any prebuilt functions, aimed at beginners:

cpp

`#include <iostream>
using namespace std;

int main() {
// Input the string
char inputString[100];
cout << "Enter a string: ";
cin.getline(inputString, 100); // Read string with spaces

// Calculate length manually


int length = 0;
while (inputString[length] != '\0') {
length++;
}

// Reverse the string using a loop


for (int i = 0; i < length / 2; i++) {
char temp = inputString[i];
inputString[i] = inputString[length - i - 1];
inputString[length - i - 1] = temp;
}

// Print the reversed string


cout << "Reversed string: " << inputString << endl;

return 0;
}
`

Explanation:

1. Input Handling:
The string is read using `cin.getline`, allowing spaces in the input.
No built-in function is used to manipulate the input.
2. Length Calculation:
A `while` loop calculates the string length by iterating until the null character (`\0`).
3. Reversal Logic:
A `for` loop swaps characters from the start and end of the string.
A temporary variable (`temp`) is used to hold a character during the swap.
4. Output:
The reversed string is printed after modification.

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 7/38
Example Run:

csharp

`Enter a string: Hello World


Reversed string: dlroW olleH
`

This is as minimal and straightforward as it gets for beginners!

#include <iostream>
using namespace std;

int main() {
// Input the string
char inputString[100], reversedString[100];
cout << "Enter a string: ";
cin.getline(inputString, 100); // Read input including spaces

// Find the length of the string manually


int length = 0;
while (inputString[length] != '\0') {
length++;
}

// Fill the reversed array


for (int i = 0; i < length; i++) {
reversedString[i] = inputString[length - i - 1];
}

// Add null terminator to the reversed string


reversedString[length] = '\0';

// Output the reversed string


cout << "Reversed string: " << reversedString << endl;

return 0;
} in this i want to use string instead of chr

To use `std::string` instead of character arrays, you can modify the code as follows:

Updated Code with `std::string`:

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 8/38
cpp

`#include <iostream>
#include <string> // Include the string library
using namespace std;

int main() {
// Input the string
string inputString, reversedString;
cout << "Enter a string: ";
getline(cin, inputString); // Use getline to read a string including spaces

// Find the length of the string manually


int length = 0;
while (inputString[length] != '\0') {
length++;
}

// Fill the reversed string


reversedString.resize(length); // Resize the string to match the input length
for (int i = 0; i < length; i++) {
reversedString[i] = inputString[length - i - 1];
}

// Output the reversed string


cout << "Reversed string: " << reversedString << endl;

return 0;
}
`

Key Changes:

1. Using `std::string`:
Replaced `char inputString[100]` with `std::string inputString`.
Replaced `char reversedString[100]` with `std::string reversedString`.
2. Resizing `reversedString`:
Before filling `reversedString`, it is resized using `reversedString.resize(length)` to ensure it
has enough capacity.
3. `getline` for Input:
`getline(cin, inputString)` is used to handle input with spaces.

Example Run:

csharp

`Enter a string: Hello World


Reversed string: dlroW olleH
`

This approach uses `std::string` while avoiding advanced functions, keeping it beginner-friendly.

// Fill the reversed string

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 9/38
reversedString.resize(length); // Resize the string to match the input length
for (int i = 0; i < length; i++) {
reversedString[i] = inputString[length - i - 1];
} use something else instead of this

If you want to avoid directly resizing and manually assigning characters to `reversedString`, you can
build the reversed string step-by-step by appending characters in reverse order. Here's how:

Modified Code:

cpp

`#include <iostream>
#include <string>
using namespace std;

int main() {
// Input the string
string inputString, reversedString;
cout << "Enter a string: ";
getline(cin, inputString); // Use getline to handle spaces

// Find the length of the string manually


int length = 0;
while (inputString[length] != '\0') {
length++;
}

// Build the reversed string by appending characters


for (int i = length - 1; i >= 0; i--) {
reversedString += inputString[i]; // Append characters in reverse order
}

// Output the reversed string


cout << "Reversed string: " << reversedString << endl;

return 0;
}
`

Changes Made:

1. Avoid `resize`:
Instead of pre-resizing `reversedString`, we build it character by character.
2. Appending Characters:
Used `reversedString += inputString[i];` to append characters in reverse order.

Example Run:

csharp

`Enter a string: Hello World


Reversed string: dlroW olleH
`

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 10/38
This approach is simple and uses basic string concatenation, which is easy to understand for beginners.

reversedstring += inputstring[i]; another way to wire this?

If you want to avoid using `reversedString += inputString[i];`, you can insert each character at the
front of the `reversedString` instead of appending it. Here's how:

Updated Code:

cpp

`#include <iostream>
#include <string>
using namespace std;

int main() {
// Input the string
string inputString, reversedString;
cout << "Enter a string: ";
getline(cin, inputString); // Use getline to handle spaces

// Find the length of the string manually


int length = 0;
while (inputString[length] != '\0') {
length++;
}

// Build the reversed string by inserting characters at the front


for (int i = 0; i < length; i++) {
reversedString = inputString[i] + reversedString; // Insert character at the front
}

// Output the reversed string


cout << "Reversed string: " << reversedString << endl;

return 0;
}
`

Explanation of Change:

1. Insert at the Front:


Instead of appending (`reversedString += inputString[i];`), this code uses `reversedString =
inputString[i] + reversedString;`.
This adds the current character to the beginning of `reversedString`.
2. Logic:
The reversed string is built step-by-step, with each new character placed at the start.

Example Run:

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 11/38
csharp

`Enter a string: Hello World


Reversed string: dlroW olleH
`

This method demonstrates another way of constructing a reversed string, suitable for practice and
understanding string operations better.

reversedstring += inputstring[i]; explain this this

The expression `reversedString += inputString[i];` is a shorthand for appending a character from


`inputString` to `reversedString`. Let's break it down:

Explanation:

1. `inputString[i]`:
This accesses the character at index `i` in the string `inputString`.
For example, if `inputString = "Hello"` and `i = 1`, then `inputString[i]` is `'e'`.
2. `reversedString += ...`:
This is shorthand for `reversedString = reversedString + ...;`.
The `+=` operator takes the current value of `reversedString`, adds the character
`inputString[i]` to it, and stores the result back in `reversedString`.
3. Step-by-Step Behavior:
When the loop executes, each character from `inputString` (in reverse order) is added to
`reversedString`.
Example:

cpp

`inputString = "Hello";
reversedString starts as ""; // Initially empty

// Loop iterates from i = 4 to i = 0 (reverse order)


i = 4: reversedString += 'o'; // reversedString = "o"
i = 3: reversedString += 'l'; // reversedString = "ol"
i = 2: reversedString += 'l'; // reversedString = "oll"
i = 1: reversedString += 'e'; // reversedString = "olle"
i = 0: reversedString += 'H'; // reversedString = "olleH"
`

Why is it Useful?

Ease of Use: The `+=` operator simplifies appending characters to the string without needing
explicit resizing or indexing.
Dynamic Growth: The `reversedString` dynamically grows as more characters are added.

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 12/38
Key Notes:

The `+=` operator works for both `char` and `std::string`. If `inputString[i]` is a `char`, it's
implicitly converted to a single-character string and appended.
Internally, `std::string` manages memory dynamically, so you don't need to worry about resizing
when using `+=`.

Example Behavior:

cpp

`string inputString = "World";


string reversedString = "";

// Appending step-by-step
reversedString += inputString[4]; // reversedString = "d"
reversedString += inputString[3]; // reversedString = "dl"
reversedString += inputString[2]; // reversedString = "dlr"
reversedString += inputString[1]; // reversedString = "dlro"
reversedString += inputString[0]; // reversedString = "dlroW"

cout << reversedString; // Outputs: dlroW


`

This method is concise and commonly used in string manipulation tasks.

next is how to find 2 LARGEST NUMBER

To find the two largest numbers in an array or a list of numbers, you can use a simple algorithm that
compares elements without sorting the array. Here's how you can do it:

Code for Finding Two Largest Numbers in an Array

cpp

`#include <iostream>
using namespace std;

int main() {
int arr[100], n;

// Input the size of the array


cout << "Enter the size of the array: ";
cin >> n;

// Input the elements of the array


cout << "Enter " << n << " elements: ";
for (int i = 0; i < n; i++) {
cin >> arr[i];
}

// Initialize two largest numbers


int largest = -1e9, secondLargest = -1e9; // Use a very small number as initial value

// Find the two largest numbers

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 13/38
for (int i = 0; i < n; i++) {
if (arr[i] > largest) {
secondLargest = largest; // Update second largest
largest = arr[i]; // Update largest
} else if (arr[i] > secondLargest && arr[i] != largest) {
secondLargest = arr[i]; // Update second largest if it's smaller than largest
}
}

// Output the results


if (secondLargest == -1e9) {
cout << "There is no second largest number (all numbers might be the same)." << endl;
} else {
cout << "The largest number is: " << largest << endl;
cout << "The second largest number is: " << secondLargest << endl;
}

return 0;
}
`

Explanation

1. Initialize Variables:
and `secondLargest` are initialized to a very small value (`-1e9` or another minimum
`largest`
value depending on the problem).
2. Traverse the Array:
If the current number is greater than `largest`, update `secondLargest` to `largest`, and
update `largest` to the current number.
If the current number is not equal to `largest` but greater than `secondLargest`, update
`secondLargest`.
3. Edge Case Handling:
If all numbers in the array are the same or there is only one number, output a message
indicating that a second largest number does not exist.

Example Run

Input:

yaml

`Enter the size of the array: 6


Enter 6 elements: 3 1 4 1 5 9
`

Output:

csharp

`The largest number is: 9


The second largest number is: 5
`

Key Notes

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 14/38
Time Complexity: The algorithm runs in O(n) time as it traverses the array once.
Space Complexity: It uses only a few variables, so the space complexity is O(1).
Handles Duplicates: The condition `arr[i] != largest` ensures that duplicates are ignored when
finding the second largest.

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


if (arr[i] > largest) {
secondLargest = largest; // Update second largest
largest = arr[i]; // Update largest
} else if (arr[i] > secondLargest && arr[i] != largest) {
secondLargest = arr[i]; // Update second largest if it's smaller than largest
}
} explain

This loop is the core of the algorithm to find the largest and second-largest numbers in an array. Let's
break it down step by step:

Key Variables

1. `largest`:
Holds the largest number found so far.
Starts with a very small value (e.g., `-1e9` or any minimum placeholder value).
2. `secondLargest`:
Holds the second largest number found so far.
Also starts with a very small value.

Logic of the Loop

cpp

`for (int i = 0; i < n; i++) {


if (arr[i] > largest) {
secondLargest = largest; // Update second largest
largest = arr[i]; // Update largest
} else if (arr[i] > secondLargest && arr[i] != largest) {
secondLargest = arr[i]; // Update second largest if it's smaller than largest
}
}
`

Step-by-Step Explanation

1. `if (arr[i] > largest)`


Checks if the current element `arr[i]` is larger than the current `largest`.
If true:

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 15/38
Update `secondLargest` to the value of `largest`. This ensures the previous largest value
becomes the second-largest value.
Update `largest` to the current element `arr[i]`.
2. `else if (arr[i] > secondLargest && arr[i] != largest)`
If the current element is not larger than `largest`, this condition is checked.
It ensures that the current element is:
Greater than the current `secondLargest`.
Not equal to the current `largest` (to avoid duplicate handling).
3. Ignore Smaller Values:
If `arr[i]` is neither greater than `largest` nor greater than `secondLargest`, the loop simply
moves to the next element without making any changes.

Example Walkthrough

Array: `{3, 5, 1, 4, 9, 2}`

Initial values: `largest = -1e9`, `secondLargest = -1e9`.

`i` `arr[i]` Condition `largest` `secondLargest` Explanation

0 3 `arr[i] > largest` 3 -1e9 `3` is the largest so far.


`5` becomes largest; `3`
1 5 `arr[i] > largest` 5 3
is second largest.
2 1 (none) 5 3 `1` is smaller than both.

`arr[i] > `4` becomes second


3 4 5 4
secondLargest` largest.
`9` becomes largest; `5`
4 9 `arr[i] > largest` 9 5
is second largest.

5 2 (none) 9 5 `2` is smaller than both.

Final Output:

Largest: `9`
Second Largest: `5`

Key Points

1. `if` vs. `else if`:


The `else if` ensures that the second condition is only checked if the first condition fails.
This avoids unnecessary checks and prevents overwriting `secondLargest` incorrectly.
2. Edge Cases:
If all elements are the same, the second-largest will not be updated, remaining as the initial
value.
If the array has fewer than two distinct elements, it gracefully handles the case by checking
the condition.
3. Efficiency:
Each element is processed exactly once, so the loop runs in O(n), making it very efficient.

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 16/38
i still didnt understood

No problem! Let me break it down further with a detailed explanation and analogy so it's easy to follow.

We want to find the largest and second-largest numbers in an array in one pass. Here's how the loop
works step-by-step:

Conceptual Explanation

Imagine you are given a list of numbers one by one, and you have two placeholders:

Largest: Keeps track of the biggest number you’ve seen so far.


Second Largest: Keeps track of the second biggest number.

Each time you see a new number:

1. You check if it’s bigger than the largest number.


If yes, the largest becomes the second largest (since it’s now the second biggest), and the new
number becomes the largest.
2. If it’s not bigger than the largest, check if it’s bigger than the second largest.
If yes, update the second largest.

Code Explanation

cpp

`for (int i = 0; i < n; i++) {


if (arr[i] > largest) {
secondLargest = largest; // The current largest becomes the second largest.
largest = arr[i]; // Update the largest to the new number.
} else if (arr[i] > secondLargest && arr[i] != largest) {
secondLargest = arr[i]; // Update second largest only if it's greater than the current seco
}
}
`

Step-by-Step with an Example

Input Array: `{3, 7, 2, 5, 9, 8}`


Initial values: `largest = -∞`, `secondLargest = -∞`.

Iteration 1:

`i = 0`, `arr[i] = 3`
Check: `arr[i] > largest` → `3 > -∞` (True)
Update `secondLargest = largest = -∞`
Update `largest = 3`

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 17/38
Now: `largest = 3`, `secondLargest = -∞`

Iteration 2:

`i = 1`, `arr[i] = 7`
Check: `arr[i] > largest` → `7 > 3` (True)
Update `secondLargest = largest = 3`
Update `largest = 7`
Now: `largest = 7`, `secondLargest = 3`

Iteration 3:

`i = 2`, `arr[i] = 2`
Check: `arr[i] > largest` → `2 > 7` (False)
Check: `arr[i] > secondLargest` → `2 > 3` (False)
No changes.
Now: `largest = 7`, `secondLargest = 3`

Iteration 4:

`i = 3`, `arr[i] = 5`
Check: `arr[i] > largest` → `5 > 7` (False)
Check: `arr[i] > secondLargest` → `5 > 3` (True)
Update `secondLargest = 5`
Now: `largest = 7`, `secondLargest = 5`

Iteration 5:

`i = 4`, `arr[i] = 9`
Check: `arr[i] > largest` → `9 > 7` (True)
Update `secondLargest = largest = 7`
Update `largest = 9`
Now: `largest = 9`, `secondLargest = 7`

Iteration 6:

`i = 5`, `arr[i] = 8`
Check: `arr[i] > largest` → `8 > 9` (False)
Check: `arr[i] > secondLargest` → `8 > 7` (True)
Update `secondLargest = 8`
Now: `largest = 9`, `secondLargest = 8`

Final Output

`largest = 9`
`secondLargest = 8`

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 18/38
Simpler Analogy

Imagine you’re hosting a contest:

1. Largest: Current champion.


2. Second Largest: Runner-up.

As new contestants (numbers) arrive:

1. If a contestant beats the champion, the current champion becomes the runner-up, and the new
contestant is the champion.
2. If the contestant doesn't beat the champion but beats the runner-up, they take the runner-up spot.

By the end of the contest, you’ll have the champion (largest) and the runner-up (second largest).

Key Takeaways

First `if`: Updates both `largest` and `secondLargest` if a new largest number is found.
Second `else if`: Updates only `secondLargest` if a number is greater than the current second
largest but not the largest.

This ensures the two largest numbers are tracked efficiently!

now code for whether number is palidrome or not?

To check whether a number is a palindrome, you can reverse the number and compare it with the
original. If they are the same, the number is a palindrome.
Here's a beginner-friendly code:

C++ Code: Check if a Number is a Palindrome

cpp

`#include <iostream>
using namespace std;

int main() {
int number, originalNumber, reversedNumber = 0, remainder;

// Input the number


cout << "Enter a number: ";
cin >> number;

// Store the original number for comparison


originalNumber = number;

// Reverse the number


while (number != 0) {
remainder = number % 10; // Get the last digit
reversedNumber = reversedNumber * 10 + remainder; // Append digit to reversed number
number = number / 10; // Remove the last digit

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 19/38
}

// Check if the original number is equal to the reversed number


if (originalNumber == reversedNumber) {
cout << originalNumber << " is a palindrome." << endl;
} else {
cout << originalNumber << " is not a palindrome." << endl;
}

return 0;
}
`

How It Works:

1. Input the Number:


Read the number from the user.
2. Reverse the Number:
Use a loop to extract digits from the number one by one (`number % 10` gives the last digit).
Build the reversed number by appending the extracted digit.
3. Compare:
Compare the original number with the reversed number.
If they are equal, it's a palindrome.

Example Runs:

Example 1:

Input: `121`
Output: `121 is a palindrome.`

Example 2:

Input: `123`
Output: `123 is not a palindrome.`

Example 3:

Input: `12321`
Output: `12321 is a palindrome.`

Key Points:

This code works for both positive and negative numbers. If you want to exclude negatives, you can
add a check:

cpp

`if (number < 0) {


cout << "Negative numbers cannot be palindromes." << endl;
return 0;

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 20/38
}
`

The logic is efficient and runs in O(d), where d is the number of digits in the input.

while (number != 0) {
remainder = number % 10; // Get the last digit
reversedNumber = reversedNumber * 10 + remainder; // Append digit to reversed number
number = number / 10; // Remove the last digit
} explain this

This block of code is used to reverse the digits of a given number. Let me explain it step by step:

Variables

1. `number`:
Holds the current value of the number being reversed. It is reduced step-by-step in the loop.
2. `remainder`:
Stores the last digit of the number during each iteration.
3. `reversedNumber`:
Builds the reversed version of the number by appending digits one by one.

How It Works (Step-by-Step)

Step 1: Check Condition

cpp

`while (number != 0)
`

The loop runs as long as the `number` is not zero.


Once `number` becomes zero, the loop stops because all digits have been processed.

Step 2: Extract the Last Digit

cpp

`remainder = number % 10;


`

The `%` (modulus) operator gives the remainder when `number` is divided by 10.
This extracts the last digit of the number.

Example:

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 21/38
If `number = 123`, then `remainder = 123 % 10 = 3`.
If `number = 45`, then `remainder = 45 % 10 = 5`.

Step 3: Build the Reversed Number

cpp

`reversedNumber = reversedNumber * 10 + remainder;


`

Multiply `reversedNumber` by 10 to shift its digits to the left.


Add the `remainder` (last digit) to append it to the right of `reversedNumber`.

Example:

Initially, `reversedNumber = 0`.


First iteration: `reversedNumber = 0 * 10 + 3 = 3`.
Second iteration: If `remainder = 2`, `reversedNumber = 3 * 10 + 2 = 32`.

Step 4: Remove the Last Digit

cpp

`number = number / 10;


`

Divide `number` by 10 (integer division) to remove the last digit.

Example:

If `number = 123`, then `number = 123 / 10 = 12`.


If `number = 12`, then `number = 12 / 10 = 1`.

Example Walkthrough

Input: `number = 123`

Iteration `number` `remainder` `reversedNumber` Explanation


1 123 3 0 * 10 + 3 = 3 Extract last digit, append to reversed.
2 12 2 3 * 10 + 2 = 32 Shift left, append next digit.
3 1 1 32 * 10 + 1 = 321 Shift left, append next digit.

4 0 - - Loop ends, number fully reversed.

Output: `reversedNumber = 321`

Summary of Each Line

1. `remainder = number % 10`: Get the last digit of the number.

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 22/38
2. `reversedNumber = reversedNumber * 10 + remainder`: Shift `reversedNumber` left and append the
last digit.
3. `number = number / 10`: Remove the last digit from `number` to prepare for the next iteration.

By the end of the loop, the original number is reversed!

now code for


armsrtong number in c++

To check whether a number is an Armstrong number, you need to calculate the sum of the cubes (or
powers corresponding to the number of digits) of its digits and compare it to the original number. If
they are equal, the number is an Armstrong number.

C++ Code for Armstrong Number

cpp

`#include <iostream>
#include <cmath> // For pow() function
using namespace std;

int main() {
int number, originalNumber, remainder, result = 0, digits = 0;

// Input the number


cout << "Enter a number: ";
cin >> number;

// Store the original number


originalNumber = number;

// Count the number of digits


while (originalNumber != 0) {
originalNumber = originalNumber / 10;
digits++;
}

// Reset originalNumber to the input number


originalNumber = number;

// Calculate the sum of powers of its digits


while (originalNumber != 0) {
remainder = originalNumber % 10; // Get the last digit
result += pow(remainder, digits); // Add digit^digits to the result
originalNumber = originalNumber / 10; // Remove the last digit
}

// Check if the result equals the original number


if (result == number) {
cout << number << " is an Armstrong number." << endl;
} else {
cout << number << " is not an Armstrong number." << endl;
}

return 0;
}
`

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 23/38
Explanation

1. Count the Number of Digits:


Use a loop to divide the number by 10 repeatedly until it becomes 0.
Each division removes one digit, and the loop counts how many digits the number has.
2. Sum of Powers:
Extract each digit using the modulus operator (`%`).
Raise the digit to the power of the total number of digits using `pow(remainder, digits)` and
add it to the `result`.
3. Compare:
Compare the calculated `result` to the original number. If they are equal, the number is an
Armstrong number.

Example Runs

Example 1:

Input: `153`

13 + 53 + 33 = 1 + 125 + 27 = 153
Output: `153 is an Armstrong number.`

Example 2:

Input: `9474`

94 + 44 + 74 + 44 = 6561 + 256 + 2401 + 256 = 9474


Output: `9474 is an Armstrong number.`

Example 3:

Input: `123`

13 + 23 + 33 = 1 + 8 + 27 = 36
Output: `123 is not an Armstrong number.`

Key Notes

1. Armstrong Numbers:
For 3-digit numbers, they are numbers like 153, 370, 371, 407.
For 4-digit numbers, examples include 9474.
2. Edge Cases:
Single-digit numbers are always Armstrong numbers because n1 = n.
3. Efficiency:
This code works efficiently for small numbers. For very large numbers, performance can be
slower due to the `pow` function.

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 24/38
explain everything also why orginal number and numner n all

Sure! Let’s go through every part of the Armstrong number code step-by-step, explaining the logic, why
variables like `originalNumber` and `number` are used, and how everything works.

What is an Armstrong Number?

An Armstrong number is a number that is equal to the sum of its digits each raised to the power of the
number of digits.
For example:

1. 153 = 13 + 53 + 33 = 153 (Armstrong number)


2. 123 = 13 + 23 + 33 = 36 =
 123 (Not an Armstrong number)

Code Overview

Here is the code again for reference:

cpp

`#include <iostream>
#include <cmath> // For pow() function
using namespace std;

int main() {
int number, originalNumber, remainder, result = 0, digits = 0;

// Input the number


cout << "Enter a number: ";
cin >> number;

// Store the original number


originalNumber = number;

// Count the number of digits


while (originalNumber != 0) {
originalNumber = originalNumber / 10;
digits++;
}

// Reset originalNumber to the input number


originalNumber = number;

// Calculate the sum of powers of its digits


while (originalNumber != 0) {
remainder = originalNumber % 10; // Get the last digit
result += pow(remainder, digits); // Add digit^digits to the result
originalNumber = originalNumber / 10; // Remove the last digit
}

// Check if the result equals the original number


if (result == number) {
cout << number << " is an Armstrong number." << endl;
} else {
cout << number << " is not an Armstrong number." << endl;
}

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 25/38
return 0;
}
`

Variable Explanations

1. `number`:
This is the user input number.
We keep this variable unchanged because we need it at the end to compare the computed
result to the original number.
2. `originalNumber`:
Used as a temporary copy of `number`.
This variable is modified during the process of counting digits and calculating the sum of
powers.
Why use `originalNumber`?
If we directly modify `number`, we lose the original value for the final comparison.
By working with `originalNumber`, the input `number` remains intact for the final check.
3. `digits`:
Stores the count of digits in the number. For example:
`153` has 3 digits.
`9474` has 4 digits.
This count is important because each digit must be raised to this power to calculate the
Armstrong number.
4. `remainder`:
Stores the last digit of the number at each step of the loop.
Extracted using the modulus operator (`%`).
5. `result`:
Accumulates the sum of each digit raised to the power of `digits`.
At the end of the program, this is compared to the original `number`.

Detailed Explanation of Each Step

1. Input the Number

cpp

`cout << "Enter a number: ";


cin >> number;
`

The user enters the number, which is stored in `number`.

2. Count the Number of Digits

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 26/38
cpp

`while (originalNumber != 0) {
originalNumber = originalNumber / 10;
digits++;
}
`

Divide `originalNumber` by 10 repeatedly until it becomes `0`. Each division removes one digit from
the number.
Increment `digits` with each step to count how many digits were removed.

Example: For `number = 9474`:

Iteration 1: `originalNumber = 9474 / 10 = 947`, `digits = 1`


Iteration 2: `originalNumber = 947 / 10 = 94`, `digits = 2`
Iteration 3: `originalNumber = 94 / 10 = 9`, `digits = 3`
Iteration 4: `originalNumber = 9 / 10 = 0`, `digits = 4`

At the end, `digits = 4`.

3. Reset `originalNumber`

cpp

`originalNumber = number;
`

Restore `originalNumber` to the input `number`, so it can be used for further calculations.

4. Calculate the Sum of Powers

cpp

`while (originalNumber != 0) {
remainder = originalNumber % 10; // Get the last digit
result += pow(remainder, digits); // Add digit^digits to the result
originalNumber = originalNumber / 10; // Remove the last digit
}
`

Extract the last digit using `originalNumber % 10`.


Raise the digit to the power of `digits` using `pow(remainder, digits)`.
Add the result to `result`.
Remove the last digit using integer division (`originalNumber / 10`).

Example: For `number = 9474`:

Iteration 1:
`remainder = 9474 % 10 = 4`
`result = 0 + pow(4, 4) = 256`
`originalNumber = 9474 / 10 = 947`
Iteration 2:

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 27/38
`remainder = 947 % 10 = 7`
`result = 256 + pow(7, 4) = 2401 + 256 = 2657`
`originalNumber = 947 / 10 = 94`
Iteration 3:
`remainder = 94 % 10 = 4`
`result = 2657 + pow(4, 4) = 256 + 2657 = 2913`
`originalNumber = 94 / 10 = 9`
Iteration 4:
`remainder = 9 % 10 = 9`
`result = 2913 + pow(9, 4) = 6561 + 2913 = 9474`
`originalNumber = 9 / 10 = 0`

At the end, `result = 9474`.

5. Compare the Result

cpp

`if (result == number) {


cout << number << " is an Armstrong number." << endl;
} else {
cout << number << " is not an Armstrong number." << endl;
}
`

Compare the `result` (sum of powers) to the original `number`.


If they are equal, the number is an Armstrong number. Otherwise, it's not.

Key Points

1. Why Use `originalNumber`?


To preserve the original `number` for comparison at the end.
2. Efficiency:
The program efficiently calculates the digits and sum of powers in two passes through the
number.
3. Edge Cases:
Single-digit numbers are always Armstrong numbers (e.g., `5 = 5^1`).
Very large numbers may take longer to process due to the power function.

Let me know if you have further doubts!

min and max value form array

Here’s how to find the minimum and maximum values in an array in C++. I'll also provide a detailed
explanation of the logic.

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 28/38
C++ Code: Finding Min and Max in an Array

cpp

`#include <iostream>
using namespace std;

int main() {
int n;

// Input the size of the array


cout << "Enter the number of elements in the array: ";
cin >> n;

// Declare the array


int arr[n];

// Input the array elements


cout << "Enter " << n << " elements:" << endl;
for (int i = 0; i < n; i++) {
cin >> arr[i];
}

// Initialize min and max with the first element


int min = arr[0];
int max = arr[0];

// Traverse the array to find min and max


for (int i = 1; i < n; i++) {
if (arr[i] < min) {
min = arr[i]; // Update min if the current element is smaller
}
if (arr[i] > max) {
max = arr[i]; // Update max if the current element is larger
}
}

// Output the results


cout << "Minimum value: " << min << endl;
cout << "Maximum value: " << max << endl;

return 0;
}
`

Explanation

1. Input the Size of the Array (`n`)


The user specifies how many elements they want in the array.
2. Input the Array Elements
The elements of the array are entered one by one.
3. Initialize `min` and `max`
Both are initially set to the first element of the array (`arr[0]`). This ensures a valid starting
point for comparison.
4. Loop Through the Array
Start the loop from the second element (`i = 1`) since the first element is already considered
in initialization.
For each element:
If the current element is smaller than `min`, update `min`.
If the current element is larger than `max`, update `max`.

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 29/38
5. Output the Results
Once the loop ends, `min` contains the smallest value, and `max` contains the largest value in
the array.

Example Run

Input:

yaml

`Enter the number of elements in the array: 5


Enter 5 elements:
3 7 2 9 4
`

Execution:

Initialization: `min = 3`, `max = 3`


Iteration 1 (arr[1] = 7):
`7 > max` → Update `max = 7`
Iteration 2 (arr[2] = 2):
`2 < min` → Update `min = 2`
Iteration 3 (arr[3] = 9):
`9 > max` → Update `max = 9`
Iteration 4 (arr[4] = 4):
No updates (`4 > min` and `4 < max`)

Output:

yaml

`Minimum value: 2
Maximum value: 9
`

Key Points

1. Why Initialize `min` and `max` with `arr[0]`?


Ensures the logic works for all input sizes, including arrays with one element.
2. Efficiency:
The code runs in O(n) time since it traverses the array once.
3. Edge Cases:
Single Element Array: Both `min` and `max` will be the same value (e.g., `arr = [5] → min =
max = 5`).
All Elements Same: `min` and `max` will still be the same (e.g., `arr = [7, 7, 7] → min = max
= 7`).

Let me know if you need further clarification!

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 30/38
how to find number of vowels and consonant in string ?

To find the number of vowels and consonants in a string, you can loop through each character of the
string, check whether it is a vowel, consonant, or something else (like a space or special character), and
keep a count.

C++ Code to Count Vowels and Consonants

cpp

`#include <iostream>
#include <string>
using namespace std;

int main() {
string input;
int vowels = 0, consonants = 0;

// Input the string


cout << "Enter a string: ";
getline(cin, input);

// Loop through each character in the string


for (char ch : input) {
// Convert character to lowercase for easier comparison
ch = tolower(ch);

// Check if it is a vowel
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
vowels++;
}
// Check if it is a consonant (alphabet but not a vowel)
else if (ch >= 'a' && ch <= 'z') {
consonants++;
}
}

// Output the results


cout << "Number of vowels: " << vowels << endl;
cout << "Number of consonants: " << consonants << endl;

return 0;
}
`

Explanation

1. Input a String:
Use `getline(cin, input)` to read the whole string, including spaces.
2. Loop Through Each Character:
Use a range-based for loop (`for (char ch : input)`) to iterate through each character in the
string.
3. Convert to Lowercase:

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 31/38
Convert the character to lowercase using `tolower(ch)` to handle case insensitivity.
4. Check Vowels:
Compare the character to `a`, `e`, `i`, `o`, and `u`. If it matches, increment the `vowels`
counter.
5. Check Consonants:
Check if the character is a letter (`ch >= 'a' && ch <= 'z'`) and not a vowel. If so, increment
the `consonants` counter.
6. Ignore Non-Alphabetic Characters:
Any character that is not a letter (e.g., numbers, spaces, punctuation) is ignored.
7. Output Results:
Print the total counts of vowels and consonants.

Example Run

Input:

csharp

`Enter a string: Hello World!


`

Execution:

1. Processing each character:


`H`: Consonant → `consonants = 1`
`e`: Vowel → `vowels = 1`
`l`: Consonant → `consonants = 2`
`l`: Consonant → `consonants = 3`
`o`: Vowel → `vowels = 2`
``: Space → Ign

for (char ch : input) {


// Convert character to lowercase for easier comparison
ch = tolower(ch); use basic loop

If you want to use a basic loop instead of a range-based for loop, here’s how you can rewrite the code:

C++ Code with a Basic Loop

cpp

`#include <iostream>
#include <string>
using namespace std;

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 32/38
int main() {
string input;
int vowels = 0, consonants = 0;

// Input the string


cout << "Enter a string: ";
getline(cin, input);

// Loop through each character in the string using a basic loop


for (int i = 0; i < input.length(); i++) {
char ch = input[i]; // Access character at position i

// Convert character to lowercase for easier comparison


if (ch >= 'A' && ch <= 'Z') {
ch = ch + 32; // Convert uppercase to lowercase manually
}

// Check if it is a vowel
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
vowels++;
}
// Check if it is a consonant (alphabet but not a vowel)
else if (ch >= 'a' && ch <= 'z') {
consonants++;
}
}

// Output the results


cout << "Number of vowels: " << vowels << endl;
cout << "Number of consonants: " << consonants << endl;

return 0;
}
`

Explanation of Changes

1. Use a Basic Loop:


The loop is written in the form `for (int i = 0; i < input.length(); i++)`, where `i` iterates
over the indices of the string.
Access each character using `input[i]`.
2. Manual Conversion to Lowercase:
Instead of `tolower()`, uppercase letters (`A` to `Z`) are converted to lowercase by adding
`32` to their ASCII values:
ASCII value of `'A'` is 65, `'a'` is 97 → Difference is 32.
3. Logic Remains the Same:
Check if the character is a vowel or consonant and update the respective counters.

Example Run

Input:

csharp

`Enter a string: Hello World!


`

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 33/38
Execution:

1. Processing each character:


`H` → Convert to `h` → Consonant → `consonants = 1`
`e` → Vowel → `vowels = 1`
`l` → Consonant → `consonants = 2`
`l` → Consonant → `consonants = 3`
`o` → Vowel → `vowels = 2`
Space (` `) → Ignored
`W` → Convert to `w` → Consonant → `consonants = 4`
`o` → Vowel → `vowels = 3`
`r` → Consonant → `consonants = 5`
`l` → Consonant → `consonants = 6`
`d` → Consonant → `consonants = 7`
`!` → Ignored

Output:

javascript

`Number of vowels: 3
Number of consonants: 7
`

check if both string are same or not

To check if two strings are the same, you can compare their characters one by one. Here’s a simple code
example using a basic loop:

C++ Code: Check if Two Strings are the Same

cpp

`#include <iostream>
#include <string>
using namespace std;

int main() {
string str1, str2;
bool areSame = true;

// Input two strings


cout << "Enter the first string: ";
getline(cin, str1);
cout << "Enter the second string: ";
getline(cin, str2);

// Check if lengths are the same


if (str1.length() != str2.length()) {
areSame = false; // Strings of different lengths cannot be the same
} else {
// Compare each character

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 34/38
for (int i = 0; i < str1.length(); i++) {
if (str1[i] != str2[i]) {
areSame = false; // If any character is different, set areSame to false
break; // Exit loop early since we know the strings are not the same
}
}
}

// Output result
if (areSame) {
cout << "The strings are the same." << endl;
} else {
cout << "The strings are not the same." << endl;
}

return 0;
}
`

Explanation

1. Input Strings:
Use `getline` to allow strings with spaces.
2. Check Lengths First:
If the lengths of the two strings are not equal, they cannot be the same.
In this case, we skip the character comparison.
3. Compare Character by Character:
Use a `for` loop to iterate through each character in the strings.
If any character in `str1` does not match the corresponding character in `str2`, set `areSame`
to `false` and break out of the loop.
4. Output the Result:
If `areSame` is `true`, the strings are identical.
Otherwise, they are different.

Example Run

Input:

csharp

`Enter the first string: Hello World


Enter the second string: Hello World
`

Output:

sql

`The strings are the same.


`

Input:

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 35/38
csharp

`Enter the first string: Hello


Enter the second string: hello
`

Output:

sql

`The strings are not the same.


`

Key Notes

1. Case Sensitivity:
The comparison is case-sensitive. For example, `"Hello"` and `"hello"` are considered
different.
To make it case-insensitive, convert both strings to lowercase before comparison.
2. Edge Cases:
If both strings are empty, they are considered the same.
Strings with different lengths are immediately flagged as different.

Would you like a version with case-insensitive comparison? Let me know!

what if i dont ant to use ibuilt functions

If you don't want to use any inbuilt functions like `.length()` or direct character comparison methods,
you can manually calculate the lengths of the strings and compare their characters. Here's how to
achieve this:

C++ Code Without Using Inbuilt Functions

cpp

`#include <iostream>
using namespace std;

int main() {
char str1[100], str2[100];
bool areSame = true;

// Input two strings


cout << "Enter the first string: ";
cin.getline(str1, 100); // Input the first string
cout << "Enter the second string: ";
cin.getline(str2, 100); // Input the second string

// Manually calculate the lengths of the strings

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 36/38
int len1 = 0, len2 = 0;
while (str1[len1] != '\0') {
len1++;
}
while (str2[len2] != '\0') {
len2++;
}

// Check if lengths are the same


if (len1 != len2) {
areSame = false; // Strings with different lengths cannot be the same
} else {
// Compare each character manually
for (int i = 0; i < len1; i++) {
if (str1[i] != str2[i]) {
areSame = false; // If any character is different
break; // Stop further checks
}
}
}

// Output the result


if (areSame) {
cout << "The strings are the same." << endl;
} else {
cout << "The strings are not the same." << endl;
}

return 0;
}
`

Explanation

1. Input Strings Using `cin.getline`:


The strings are stored as character arrays, which avoids using the C++ `string` class.
`cin.getline(str, 100)` ensures spaces are captured within the string.
2. Manually Calculate Lengths:
A `while` loop is used to count the number of characters in each string until the null
character (`'\0'`) is reached.
`len1` holds the length of `str1`, and `len2` holds the length of `str2`.
3. Compare Lengths:
If the lengths differ, the strings are immediately deemed unequal.
4. Character-by-Character Comparison:
A `for` loop is used to compare each character of `str1` with the corresponding character in
`str2`.
If any character does not match, `areSame` is set to `false`, and the loop exits early.
5. Output Result:
If `areSame` remains `true`, the strings are identical.
Otherwise, they are different.

Example Run

Input:

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 37/38
csharp

`Enter the first string: Hello World


Enter the second string: Hello World
`

Output:

sql

`The strings are the same.


`

Input:

csharp

`Enter the first string: Hello


Enter the second string: HellO
`

Output:

sql

`The strings are not the same.


`

Key Points

No Inbuilt Functions: We avoided using `.length()` and direct comparison methods.


Case-Sensitivity: This solution is case-sensitive. For example, `"Hello"` and `"hello"` are
considered different.
Edge Cases:
If both strings are empty (`""`), they are the same.
If one string is empty and the other is not, they are different.

Let me know if you'd like to extend this further, such as making it case-insensitive or optimizing the
code!

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 38/38

You might also like