zero_field
zero_field

Reputation: 345

Grouping numbers using if condition

It's pretty simple to group a list of integers by even or odd. This is what we can do.

#include <iostream>
#include <cmath>

int main(){
   for(int i=1; i<=1000; i++){
   if (fmod(i,2) == 0)
   std::cout<<"even:"<<i<<std::endl;
   else
     std::cout<<"odd:"<<i<<std::endl;
   }
   return 0;
}

But what I intend to do is to group them by the 10 entries. We can first group A has entries from 1 to 10 and the next group B has entries 11 to 20. Similar way, entries from 21 to 30 will be in A, and 31 to 40 will be in B.

The reason I'm thinking this way is to, I want to learn how we can group them? Is there any stl libray function I can use?

**I have an extension of this question. For example in the "for"loop, the number of entries is 1005, instead of 1000, in that case, I would like to ignore the last 5 entries. How to do this?

Another question, I may not have the integers always (it could be double), which could be coming from an array, so my intention was to group the entries as I want. I have used for loop, just as an example for integer entries, but what I'm looking for is grouping the numbers using an if condition.**

Upvotes: 0

Views: 337

Answers (2)

Sid S
Sid S

Reputation: 6125

Don't use fmod() for integers. Use the modulo operator, %

for (int i = 0; i < 1000; i++)
{
    if (i % 20 < 10)
        std::cout << "group A: ";
    else
        std::cout << "group B: ";
    std::cout << i + 1 << std::endl;
}`

Upvotes: 1

abhiarora
abhiarora

Reputation: 10430

You can use vector container class in C++. It's a (template) container to save and retrieve your numbers. To declare one,

std::vector<int> groupA;

Your logic to filter the numbers into groups is also not correct. Don't use fmod for integers. You can use modulus operator % in C and C++.

You should give it a try one more time. If it still doesn't work, see my example below to understand the logic:

#include <iostream>

#include <cmath>
#include <vector>

int main()
{
        std::vector<int> groupA;
        std::vector<int> groupB;
        for (int i = 0; i < 1000; i++) {
                if (!((i / 10) % 2)) {
                        std::cout << "Group A: " << (i+1) << std::endl;
                        groupA.push_back(i+1);
                } else {
                        std::cout << "Group B: " << (i+1) << std::endl;
                        groupB.push_back(i+1);
                }
        }
        return 0;
}

Upvotes: 2

Related Questions