Totalling & Counting

Totalling

  • Totalling involves adding up values, often in a loop
  • A total variable can be initialised to 0 and then updated within a loop, such as:

Pseudocode example:

total ← 0

for i ← 1 to 10

input num

total ← total + num

next i

output total

Python example:

total = 0

for i in range(1, 11):

num = int(input("Enter a number: "))

total += num

print("Total:", total)

Java example:

int total = 0;

Scanner scanner = new Scanner(System.in);

for (int i = 1; i <= 10; i++) {

System.out.print("Enter a number: ");

int num = scanner.nextInt();

total += num;

}

System.out.println("Total: " + total);

Visual Basic example:

Dim total As Integer = 0

For i As Integer = 1 To 10

Console.Write("Enter a number: ")

Dim num As Integer = Integer.Parse(Console.ReadLine())

total += num

Next i

Console.WriteLine("Total: " & total)

Counting

  • Counting involves keeping track of the number of times a particular event occurs
  • A count variable can be initialised to 0 and then updated within a loop, such as:

Pseudocode example:

count ← 0

for i ← 1 to 10

input num

if num > 5 then

ount ← count + 1

end if

next i

output count

Python example:

count = 0

for i in range(1, 11):

num = int(input("Enter a number: "))

if num > 5:

count += 1

print("Count:", count)

Java example:

int count = 0;

Scanner scanner = new Scanner(System.in);

for (int i = 1; i <= 10; i++) {

System.out.print("Enter a number: ");

int num = scanner.nextInt();

if (num > 5) {

count++;

}

}

System.out.println("Count: " + count);

Visual Basic example:

Dim count As Integer = 0

For i As Integer = 1 To 10

Console.Write("Enter a number: ")

Dim num As Integer = Integer.Parse(Console.ReadLine())

If num > 5 Then

count += 1

End If

Next i

Console.WriteLine("Count: " & count)

Loading

error: Content is protected !!