Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

Can you explain why do I need nested for loops in my code? (C++)

+5 votes
asked Jun 2 by Eidnoxon (4,080 points)

Hello! I have been coding for a year, and I have learnt python so far. I know data structure and data analysis in python, but not on a high level. I decided to learn another programming language like 2 weeks ago. I'd like to question, why do I have to use nested for loops in my code? Here is my code:

#include <iostream>
using namespace std;

void sort(int list[], int size){
    int temp;
    for(int i = 0; i < size - 1; i++){
        for(int j=0; j<size-i-1; j++){
            if(list[j] > list[j+1]){
                temp = list[j];
                list[j] = list[j+1];
                list[j+1] = list[j];
int main(){
    int num[] = {2,1,3,5,4,6,8,9,7,10};
    int size = sizeof(num)/sizeof(num[0]);
    sort(num, size);
    for(int i : num){
        cout << i << ", ";
    return 0;

II would really appreciate your help!

1 Answer

+2 votes
answered Jun 2 by Peter Minarik (78,090 points)
selected Jun 3 by Eidnoxon
Best answer

You need a nested loop because this is how the bubble sort works.

What you do is take the first item and compare it to the next one. If the one on the left is larger, they swap places, so the larger element is on the right side. Then you compare the next two pair (index 0 to index 1, then index 1 to index 2, then index 2 to index 3, etc). This ensures that by the time you reach the end of the list the last element is the largest in the list.

But everything else on the left side of the largest element is still unsorted.

So rinse and repeat. Compare two, put the larger one to the right side, and keep comparing with the next ones.

You don't need to go all the way all the time as the right side is already sorted containing the largest then the 2nd largest then the 3rd largest, etc elements.

I hope this helps. For more details, read the linked site that explains bubble sorting in detail.

Good luck!

Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.