Lab Assignment #4 :: CPTR 105 :: 04/03/09
- Write a for statement to compute the sum 1 + 22 + 32 + 42 + ….. + n2. Ask the user for the value of
n
.
Solution
System.out.println("Please enter a number for the limit");
Scanner kb = new Scanner(System.in);
int n = kb.nextInt();
int sum = 0;
for (int count = 0; count <= n; count++) {
sum += count*count;
}
System.out.println("The derived sum is " + sum);
- Write a loop that will count the number of
blank
characters in a given string.
Solution
System.out.println("Please enter a string:");
Scanner kb = new Scanner(System.in);
String inputString = kb.nextLine();
int blanksCount = 0;
for (int count = 0; count < inputString.length() - 1; count++) {
if (inputString.charAt(count) == ' ')
blanksCount++;
}
System.out.println("The number of blank characters is " + blanksCount);