turbo c++ easy programs
Sure! I can provide explanations for each step of some easy C++ programs. Here's an example program that calculates the factorial of a number:
#include <iostream>
using namespace std;
int main() {
int num, factorial = 1;
cout << "Enter a positive integer: ";
cin >> num;
for (int i = 1; i <= num; ++i) {
factorial *= i;
}
cout << "The factorial of " << num << " is " << factorial << endl;
return 0;
}
Explanation:
- The program begins by including the
iostream
header file, which allows us to use input and output operations in C++. - We then use the
using namespace std;
statement to avoid having to writestd::
before standard C++ library functions and objects. - The
main()
function is the entry point of the program. - Inside the
main()
function, we declare two variables:num
to store the input number andfactorial
to store the factorial value. - We then prompt the user to enter a positive integer by using the
cout
object to display the message "Enter a positive integer: ", and thecin
object to read the user's input into thenum
variable. - Next, we use a
for
loop to calculate the factorial of the input number. The loop iterates fromi = 1
toi <= num
, incrementingi
by 1 in each iteration. - Within the loop, we update the
factorial
variable by multiplying it with the current value ofi
. - Once the loop completes, we use the
cout
object to display the calculated factorial value by concatenating the message "The factorial of ", the value ofnum
, the message " is ", and the value offactorial
. - Finally, we return 0 to indicate successful program execution.
This program calculates the factorial of a positive integer using a for
loop and displays the result.