Basic examples of c++
Reverse of a number
using namespace
std;
int main() {
int number, reverse = 0, remainder;
// Input from the user
cout << "Enter an integer:
";
cin >> number;
// Process to reverse the number
while (number != 0) {
remainder = number % 10; // Extract the last digit
reverse = reverse * 10 + remainder; //
Add it to the reversed number
number /= 10; // Remove the last digit
}
// Output the reversed number
cout << "Reversed number: "
<< reverse << endl;
return 0;
}
Explanation
- Input:
- The
program starts by asking the user to input an integer (number). This is
stored in the variable number.
- Initialization:
- Two
variables are initialized:
- reverse
to store the reversed number (initially set to 0).
- remainder
to temporarily store the last digit of the number.
- Reversing
Process (while loop):
- The
loop runs as long as number is not 0.
- Inside
the loop:
1.
Extract Last Digit: remainder = number %
10;
- The
modulo operator (%) is used to get the last digit of the number.
2.
Update Reversed Number: reverse = reverse
* 10 + remainder;
- The
current remainder is added to the reverse, which is multiplied by 10 to
shift its digits left.
3.
Remove Last Digit: number /= 10;
- The
number is divided by 10 (integer division) to remove the last digit.
- Output:
- After
the loop completes, the reverse variable contains the reversed number.
- This
is then printed to the console.
Example
Input:
Enter an integer: 1234
Execution:
- Initial:
number = 1234, reverse = 0
- 1st
Iteration: remainder = 4, reverse = 0 * 10 + 4 = 4, number = 123
- 2nd
Iteration: remainder = 3, reverse = 4 * 10 + 3 = 43, number = 12
- 3rd
Iteration: remainder = 2, reverse = 43 * 10 + 2 = 432, number = 1
- 4th
Iteration: remainder = 1, reverse = 432 * 10 + 1 = 4321, number = 0
Output:
Reversed number: 4321
This program handles positive numbers, but can also be
extended to handle negative numbers by capturing the sign of the input
separately. Let me know if you'd like an enhanced version!
#include <iostream>
using namespace std;
int main() {
int number;
cout <<
"Enter an integer: ";
cin >>
number;
if (number % 2 ==
0) {
cout <<
number << " is even." << endl;
} else {
cout <<
number << " is odd." << endl;
}
return 0;
}
Multiplication of a number
#include <iostream>
using namespace std;
int main() {
int number;
cout <<
"Enter a number: ";
cin >>
number;
cout <<
"Multiplication Table of " << number << ":\n";
for (int i = 1; i
<= 10; ++i) {
cout <<
number << " x " << i << " = " <<
number * i << endl;
}
return 0;
}
Fibonacci Series program
Here is a program to generate the Fibonacci series in
C++ with a detailed explanation:
Fibonacci Series:
The Fibonacci series is a sequence of numbers where each
number is the sum of the two preceding ones, starting with 0 and 1.
For example:
0, 1, 1, 2, 3, 5, 8, 13, ...
The formula to generate Fibonacci numbers:
F(n)=F(n−1)+F(n−2)F(n) = F(n-1) + F(n-2)
Where:
- F(0)=0F(0)
= 0 (base case)
- F(1)=1F(1)
= 1 (base case)
C++ Code: Fibonacci Series
This program generates the Fibonacci series up to n terms
using an iterative approach.
#include <iostream>
using namespace std;
int main() {
int n, t1 = 0, t2
= 1, nextTerm = 0;
// Input: Number
of terms in Fibonacci series
cout <<
"Enter the number of terms: ";
cin >> n;
cout <<
"Fibonacci Series: ";
for (int i = 1; i
<= n; i++) {
// Print the
first two terms separately
if (i == 1) {
cout
<< t1 << ", ";
continue;
}
if (i == 2) {
cout
<< t2 << ", ";
continue;
}
// Calculate
the next term
nextTerm = t1
+ t2;
t1 = t2; //
Update previous two terms
t2 = nextTerm;
cout <<
nextTerm << ", ";
}
return 0;
}
Explanation of Code:
- Header
file:
- #include <iostream>
- This
includes the standard input-output library to use cin and cout.
- Variables:
- int n, t1 = 0, t2 = 1,
nextTerm = 0;
- n:
Number of terms in the Fibonacci series (input from user).
- t1:
The first term (0).
- t2:
The second term (1).
- nextTerm:
Holds the value of the next Fibonacci number.
- Input:
- cin >> n;
- The
program asks the user to input the number of terms.
- For
Loop:
- for (int i = 1; i <= n;
i++) {
- if (i == 1) { cout << t1
<< ", "; continue; }
- if (i == 2) { cout << t2
<< ", "; continue; }
- nextTerm = t1 + t2;
- t1 = t2;
- t2 = nextTerm;
- cout << nextTerm <<
", ";
- }
- Iterates
n times to calculate and print the Fibonacci series.
- Conditionals:
- The
first two terms (t1 and t2) are printed directly.
- Formula:
- The
next term is the sum of the previous two terms:
nextTerm=t1+t2\text{nextTerm} = t1 + t2
- Update:
- Move
t2 to t1, and nextTerm to t2.
- Output:
- Prints
the Fibonacci series, separated by commas.
Sample Output:
Input:
Enter the number of terms: 7
Output:
Fibonacci Series: 0, 1, 1, 2, 3, 5, 8,
Key Points:
- The
Fibonacci series starts with 0 and 1.
- Each
subsequent term is the sum of the previous two terms.
- This
program uses an iterative approach which is efficient compared to
recursion for larger values of n.
If you want to implement it recursively, let me know,
and I'll explain that as well! 😊
Here’s a C++ program to calculate the factorial of a number,
along with a detailed explanation:
Factorial of a number
using namespace
std;
int main() {
int number;
long long factorial = 1; // To handle large
factorials
// Input from the user
cout << "Enter a positive
integer: ";
cin >> number;
// Check if the input is valid
if (number < 0) {
cout << "Factorial is not
defined for negative numbers." << endl;
} else {
// Calculate factorial
for (int i = 1; i <= number; ++i) {
factorial *= i; // Multiply
factorial by i
}
// Output the result
cout << "Factorial of "
<< number << " is " << factorial << endl;
}
return 0;
}
Explanation:
- Input:
- The
program prompts the user to enter a positive integer and stores it in the
variable number.
- Validation:
- A
check ensures that the input is non-negative since factorials are only
defined for non-negative integers. If number < 0, an error message is
displayed.
- Initialization:
- A
variable factorial is initialized to 1. This variable will hold the
result of the factorial calculation. The long long type is used to handle
large numbers (factorials grow very quickly).
- Factorial
Calculation (for loop):
- A
for loop runs from 1 to number (inclusive).
- During
each iteration:
- The
current value of i is multiplied by factorial, and the result is stored
back in factorial.
- For
example, if number = 5, the steps are:
- Step
1: factorial = 1 * 1 = 1
- Step
2: factorial = 1 * 2 = 2
- Step
3: factorial = 2 * 3 = 6
- Step
4: factorial = 6 * 4 = 24
- Step
5: factorial = 24 * 5 = 120
- Output:
- Once
the loop completes, factorial contains the factorial of the input number.
- The
program outputs the result.
Example Execution:
Input:
Enter a positive integer: 5
Execution:
- Initial:
factorial = 1
- 1st
Iteration: i = 1, factorial = 1 * 1 = 1
- 2nd
Iteration: i = 2, factorial = 1 * 2 = 2
- 3rd
Iteration: i = 3, factorial = 2 * 3 = 6
- 4th
Iteration: i = 4, factorial = 6 * 4 = 24
- 5th
Iteration: i = 5, factorial = 24 * 5 = 120
Output:
Factorial of 5 is 120
Special Cases:
- Factorial
of 0:
- By
definition, the factorial of 0 is 1. The program will handle this
correctly since the loop doesn’t execute for number = 0, and factorial
remains 1.
- Negative
Numbers:
- The
program ensures that negative inputs are not processed and displays an
error message.
Alternate Versions:
- If
you want a recursive solution for factorial, let me know!
Sum of Digits of a Number
Program Code
#include <iostream>
using namespace std;
int main() {
int number, sum =
0, remainder;
cout <<
"Enter an integer: ";
cin >>
number;
while (number !=
0) {
remainder =
number % 10; // Extract the last digit
sum +=
remainder; // Add the last digit
to the sum
number /= 10; // Remove the last digit
}
cout <<
"Sum of digits: " << sum << endl;
return 0;
}
Explanation
This program calculates the sum of digits of a given
integer. Let’s go step by step:
- Variables
Used:
- number:
Stores the input integer.
- sum:
Stores the cumulative sum of the digits. Initialized to 0.
- remainder:
Temporarily stores the last digit of the number.
- User
Input:
- The
program asks the user to input an integer using:
- cin >> number;
- Logic
to Extract Digits:
- The
idea is to repeatedly extract the last digit of the number, add it to the
sum, and then remove the last digit. This is done using:
- Modulus
operator % to get the last digit.
- Division
operator / to remove the last digit.
For example, if the input is 123:
- 123
% 10 = 3 → Extract the last digit 3.
- 123
/ 10 = 12 → Remove the last digit, now number = 12.
- Loop
(while loop):
- The
loop continues as long as number is not equal to 0.
- In
each iteration:
1.
Extract the last digit using remainder = number
% 10.
2.
Add the digit to sum using sum += remainder.
3.
Remove the last digit by dividing the number by
10 using number /= 10.
- Output:
- Once
the loop ends, sum contains the total sum of all digits.
- The
result is displayed using:
- cout << "Sum
of digits: " << sum << endl;
Example Execution
Input:
Enter an integer: 123
Execution:
|
Iteration |
number |
remainder (number % 10) |
sum (previous + remainder) |
number /= 10 |
|
1 |
123 |
3 |
0 + 3 = 3 |
12 |
|
2 |
12 |
2 |
3 + 2 = 5 |
1 |
|
3 |
1 |
1 |
5 + 1 = 6 |
0 |
- When
number becomes 0, the loop stops.
Output:
Sum of digits: 6
Edge Cases to Consider
- Input:
0
- Since
number is 0, the loop doesn't execute.
- The
sum remains 0, and the output is correct:
- Sum of digits: 0
- Negative
Numbers:
- If
the input is negative, the logic still works because the % operator in
C++ correctly extracts the last digit of a negative number.
- Example:
- Enter an integer: -456
- Sum of digits: 15
Key Concepts in the Program
- Modulus
Operator %: Used to extract the last digit of a number.
- Division
Operator /: Used to remove the last digit.
- Loops
(while): Repeats the process until the number becomes 0.
- Basic
Input/Output: cin for input and cout for output.
This program is an excellent example of using loops
and mathematical operators to solve a problem. Let me know if you need
further clarifications or additional examples! 😊
#include <iostream>
using namespace std;
int main() {
int n;
// Ask user for
the size of the matrix
cout <<
"Enter the size of the square matrix (N): ";
cin >> n;
if (n <= 0) {
cout <<
"Size must be greater than 0." << endl;
return 1;
}
int matrix[n][n];
// Declare a 2D array to store the matrix values
int value =
1; // Initial value to fill in the
matrix
// Fill the matrix
with sequential numbers
for (int i = 0; i
< n; ++i) {
for (int j =
0; j < n; ++j) {
matrix[i][j] = value;
value++;
}
}
// Print the
matrix
cout <<
"The square matrix is:" << endl;
for (int i = 0; i
< n; ++i) {
for (int j =
0; j < n; ++j) {
cout
<< matrix[i][j] << "\t";
}
cout <<
endl;
}
return 0;
}
Comments
Post a Comment