0% found this document useful (0 votes)
18 views3 pages

Automata Fix CPP

The document presents three C++ programming problems with incorrect code and their respective corrections. The first issue involves an infinite loop caused by using 'unsigned int' for countdown, the second addresses integer overflow in factorial calculation, and the third corrects an infinite loop in a nested loop pattern. Each section includes the original code, identified errors, and the corrected version.

Uploaded by

jashan100106
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)
18 views3 pages

Automata Fix CPP

The document presents three C++ programming problems with incorrect code and their respective corrections. The first issue involves an infinite loop caused by using 'unsigned int' for countdown, the second addresses integer overflow in factorial calculation, and the third corrects an infinite loop in a nested loop pattern. Each section includes the original code, identified errors, and the corrected version.

Uploaded by

jashan100106
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/ 3

Automata Fix Questions in C++

1) Countdown from n to 0

Incorrect Code:
#include <iostream>
using namespace std;

int main() {
unsigned int n;
cin >> n;
while (n >= 0) {
cout << n << endl;
n--;
}
return 0;
}

Errors:
- `unsigned int` causes an infinite loop when `n = 0` due to wrapping.
Corrected Code:
#include <iostream>
using namespace std;

int main() {
int n;
cin >> n;
while (n >= 0) {
cout << n << endl;
n--;
}
return 0;
}

2) Factorial Calculation

Incorrect Code:
#include <iostream>
using namespace std;

int main() {
int fact = 1, n;
cin >> n;
for (int i = 1; i <= n; i++) {
fact *= i;
}
cout << fact << endl;
return 0;
}

Errors:
- `int fact` overflows for large values of `n`.
Corrected Code:
#include <iostream>
using namespace std;

int main() {
long long fact = 1, n;
cin >> n;
for (long long i = 1; i <= n; i++) {
fact *= i;
}
cout << fact << endl;
return 0;
}

3) Print a pattern

Incorrect Code:
#include <iostream>
using namespace std;

int main() {
int n;
cin >> n;
for (int i = 1; i < n; i++) {
for (int j = 0; j < n; j--;) {
cout << i;
}
cout << endl;
}
return 0;
}

Errors:
- `j--` in the inner loop leads to an infinite loop.
Corrected Code:
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
for (int i = 1; i < n; i++) {
for (int j = i - 1; j < n; j++) {
cout << i;
}
cout << endl;
}
return 0;
}

You might also like