settingsAccountsettings
Menusettings

Q: Finding numbers not divisible by 3 and 7 in C#

+5 votes

I need to write a program in C# that enters from the console a positive integer n and prints all the numbers from 1 to n not divisible by 3 and 7, on a single line, separated by a space.

Examples:

n

output

3

1 2

10

1 2 4 5 8 10

 

asked in C# category by user paulcabalit

2 Answers

+1 vote

Here is my solution with continue; which continues with the next step - excluding numbers divisible by 3 and 7:

using System;

class NumbersNotDivisibleByThreeAndSeven
{
    static void Main()
    {
        Console.WriteLine("Please enter your number: ");
        int n = int.Parse(Console.ReadLine());

        for (int i = 1; i <= n; i++)
        {
            if (i % 3 == 0)
            {
                continue;
            }
            else if (i % 7 ==0)
            {
                continue;
            }
            Console.Write("{0} ", i);
        }
        Console.WriteLine();
    }
}

 

answered by user sam
edited by user golearnweb
+1 vote

Another solution with some logical expressions:

using System;

class NumbersNotDivisibleBy3And7
{
    static void Main()
    {
        Console.WriteLine("Enter an integer:");
        int n = int.Parse(Console.ReadLine());
        for (int i = 1; i <= n; i++)
        {
            if (i % 3 != 0 && i % 7 != 0)
            {
                Console.Write("{0} ", i);
            }
        }
        Console.WriteLine();
    }
}

 

answered by user nikole
edited by user golearnweb
...