Home > front end >  Reversing for loop
Reversing for loop

Time:11-27

How can I reverse this for loop for the else statement? I am very open to criticism.

int a = 1;
int ans;

ans=a;

int inp;
cout<<"type 1 for ascending and 2 for descending\n \n"<<endl;
cin>>inp;

if (inp==ans) {
    const char* books[6]
        = { "1 Literature", "2 Grammar", "3 Spelling", "4 Short Stories", "5 Alphabet", "6 Punctuations" };

    for (int i = 0; i < 6; i  )
        cout << books[i] << "\n";

    return 0;
}
else{?}

I tried this and I believe I am very wrong LOL:

else{
    const char* books[6]
        = { "1 Literature", "2 Grammar", "3 Spelling", "4 Short Stories", "5 Alphabet", "6 Punctuations" };

    for (int i = 6; i > 0; i--)
        cout << books[i] << "\n";

    return 0;
}

CodePudding user response:

#include<iostream>
#include<string>

int main()
{
    int ans = 1;

    int inp{};
    std::cout << "type 1 for ascending and 2 for descending\n\n\n";
    std::cin >> inp;

    std::string books[6] = { "1 Literature", "2 Grammar", "3 Spelling", "4 Short Stories", "5 Alphabet", "6 Punctuations" };
    
    if (inp == ans)
    {
        for (auto& book : books) // another way to do a range based for loop 
        {
            std::cout << book << "\n";
        }
    }
    else
    {
        for (int i{5}; i >= 0; i--) // your answer :)
        {
            std::cout << books[i] << '\n';
        }
    }

    std::cin.ignore();
    std::cin.clear();
    std::cin >> ans; // so my terminal stays open
}

This is how you do it. Some tips: declare books outside the for loop no need to redeclare it everytime. Also the index of the last item in an array of size 6 is index 5 so we start there and go until we hit the 0th index and break. also please look into syntax, you must have brackets on a for loop, even if it still compiles no one will like you if they are working with you and it will confuse you. Hope you stick with it C is a beautiful language imho.

  •  Tags:  
  • c
  • Related