Start learning free

LESSON 124 OF 347 · LOOPS & CONDITIONALS

Print Positive Numbers From an Array in C#: foreach and if

Practice Read the full explanation

Given an array of integers, print to the console the positive numbers, one on each line.

A number n is positive if it is strictly greater than 0.

Example:

Input: nums = [3, -2, 0, 4, -4]
Output (console):
3
4

Note:

You have to print the numbers to the console, your function shouldn't return anything.


STEP 1 OF 3
    Ctrl + Enter to check

    C# · LOOPS & CONDITIONALS

    Print Positive Numbers From Array in C#, explained

    Problem overview

    The method PrintPositiveNumbers(int[] nums) takes an array of integers and prints the positive ones to the console, one per line, in their original order. It returns nothing. A number is positive when it is strictly greater than 0, so zero is not printed.

    For nums = [3, -2, 0, 4, -4], the output is 3 and then 4. The -2 and -4 are negative, and 0 is neither positive nor negative.

    Approach

    The task has two parts: look at every element, and act on only some of them. In C# these map directly onto a foreach loop, which visits each element, and an if statement, which decides whether to print it.

    The loop does not need to know positions. The task does not ask where a number sits in the array, only what its value is, so foreach is simpler than a for loop with an index. It also removes the chance of an off-by-one error in the bounds.

    Step by step

    1. Write a foreach loop over nums. Declare the loop variable as int val. On each pass, val holds the next element, starting with the first.
    2. Test the value with if (val > 0). Use > and not >=, because zero must be left out.
    3. Print inside the if. Console.WriteLine(val) writes the number and ends the line, so each positive number is on its own line.

    The solution in C#

    class Solution {
        public void PrintPositiveNumbers(int[] nums) {
            foreach (int val in nums) {
                if (val > 0) {
                    Console.WriteLine(val);
                }
            }
        }
    }
    

    Some details worth knowing:

    • The loop variable in a foreach is read-only. You can use val but you cannot assign to it, which is fine here because the method only reads.
    • int[] is a C# array type. Its elements are visited in order from index 0 to the end.
    • The method returns void. The output goes to the console, so the method has no return value to produce.
    • Because foreach reads the array, nothing in nums changes.

    If you later need the positions as well, switch to a for loop over i < nums.Length and read nums[i]. For this task, that extra bookkeeping is not needed.

    Complexity

    The loop visits each of the n elements once and does a constant amount of work for each, so the time is O(n). The method stores nothing besides the loop variable, so the space is O(1).

    Edge cases and common mistakes

    • Zero in the array. With >= the 0 in the example would be printed too, and the output would be wrong.
    • No positive numbers. If every element is zero or negative, nothing is printed. That is correct, and no special handling is needed.
    • An empty array. The loop body never runs, so nothing is printed.
    • Returning instead of printing. The task is to print. A method that builds a list and returns it will not produce the expected console output.
    • Printing the wrong thing. Console.WriteLine("val") prints the word val for every positive number. Leave out the quotes to print the variable.
    • Using return inside the loop. It would end the method after the first positive number and skip the rest.

    Testing

    • [3, -2, 0, 4, -4] prints 3 and 4.
    • [-1, -2, -3] prints nothing.
    • [5, 5, 1] prints 5, 5 and 1, one per line. Duplicates are printed each time they appear.
    • [] prints nothing.
    Keep going with C#About 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free