0
0
C++programming~15 mins

Why loops are needed in C++ - See It in Action

Choose your learning style9 modes available
Why loops are needed
📖 Scenario: Imagine you have a list of 5 friends and you want to say "Hello" to each one. Writing the same line again and again is tiring and takes a lot of space. Loops help us repeat actions easily without writing the same code many times.
🎯 Goal: You will create a simple program that stores 5 friend names and uses a loop to greet each friend by printing "Hello, <friend>!".
📋 What You'll Learn
Create an array of 5 friend names
Create a variable to count how many friends there are
Use a for loop to go through each friend in the array
Print a greeting message for each friend
💡 Why This Matters
🌍 Real World
Loops are used in many programs to handle repeated tasks like processing lists of data, automating repetitive actions, and managing user inputs.
💼 Career
Understanding loops is essential for any programming job because they make code efficient and easier to maintain when working with collections of data.
Progress0 / 4 steps
1
Create an array of friend names
Create a string array called friends with these exact names: "Alice", "Bob", "Charlie", "Diana", "Ethan".
C++
Need a hint?

Use std::string friends[5] = {"Alice", "Bob", "Charlie", "Diana", "Ethan"}; to create the array.

2
Create a variable for the number of friends
Create an int variable called count and set it to 5 to store the number of friends.
C++
Need a hint?

Use int count = 5; to store the number of friends.

3
Use a for loop to greet each friend
Use a for loop with int i = 0; loop while i < count; and increase i by 1 each time. Inside the loop, print "Hello, " followed by friends[i] and then "!".
C++
Need a hint?

Use a for loop with i from 0 to count - 1 and print the greeting inside.

4
Print the greetings
Run the program to print the greetings for all friends. The output should show each friend greeted on a new line.
C++
Need a hint?

Run the program and check the output matches the greetings for all friends.