C# Program to Count the Number of 1's in the Entered Numbers


I have added the numbers using an array −

int[] num = new int[] {1, 25, 1, 55, 1};

Now loop through and find for 1, if 1 is there, 6 then increment the variable that counts the occurrence −

foreach(int j in num) {
   if (j == 1) {
      cal++;
   }
}

Example

The following is the code to count the number of 1’s in the entered number.

Live Demo

using System;
public class Demo {
   public static void Main() {
      int cal = 0;
      int[] num = new int[] {1, 25, 1, 55, 1};
      Console.WriteLine("Numbers:");
      for (int i = 0; i < 5; i++) {
         Console.WriteLine(num[i]);
      }
      foreach (int j in num) {
         if (j == 1) {
            cal++;
         }
      }
      Console.WriteLine("Number of 1's: ");
      Console.WriteLine(cal);
      Console.ReadLine();
   }
}

Output

Numbers:
1
25
1
55
1
Number of 1's:  
3

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 19-Jun-2020

379 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements