Home > Backend Development > C#.Net Tutorial > C# program: Count the number of 1's in the input number

C# program: Count the number of 1's in the input number

王林
Release: 2023-08-23 18:41:03
forward
1405 people have browsed it

C# program: Count the number of 1s in the input number

I have added the numbers using an array −

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

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++;
   }
}
Copy after login

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&#39;s: ");
      Console.WriteLine(cal);
      Console.ReadLine();
   }
}
Copy after login

Output

Numbers:
1
25
1
55
1
Number of 1&#39;s:  
3
Copy after login

The above is the detailed content of C# program: Count the number of 1's in the input number. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template