In: Computer Science
The Trabb Pardo-Knuth algorithm is often used to illustrate the basic syntax of programming languages.
ask for 11 numbers to be read into a sequence S for each item e in the reversed sequence of S compute the value sqrt(abs(e))+5*e if result is greater than 500 alert user else print result
Implement the algorithm in at least two programming languages.
Java:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int S[] = new int[11];
System.out.println("Enter 11 numbers: ");
for (int i=0; i<11; i++) {
S[i] = sc.nextInt();
}
for (int i=10; i>=0; i--) {
double result = Math.sqrt(Math.abs(S[i])) + 5*S[i];
if (result > 500) {
System.out.println(S[i] + " term is not eligible");
} else {
System.out.println(S[i] + " -> " + result);
}
}
}
}
C++:
#include <iostream>
#include <cmath>
using namespace std;
int main() {
int S[11];
cout << "Enter 11 numbers: ";
for (int i=0; i<11; i++) {
cin >> S[i];
}
for (int i=10; i>=0; i--) {
double result = sqrt(abs(S[i])) + 5*S[i];
if (result > 500) {
cout << S[i] << " term is not eligible" << endl;
} else {
cout << S[i] << " -> " << result << endl;
}
}
}