C# Program to Count the Number of 1?s in the Entered Number
Posted by Superadmin on August 14 2022 14:29:45

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

 

 

This is a C# Program to count the number of 1’s in the entered number.

Problem Description

This C# Program Counts the Number of 1’s in the Entered Number.

Problem Solution

Here the array of numbers are obtained with its limit and number of 1’s in it is counted and displayed.

Program/Source Code

Here is source code of the C# Program to Count the Number of 1’s in the Entered Number. The C# program is successfully compiled and executed with Microsoft Visual Studio. The program output is also shown below.

/*
 * C# Program to Count the Number of 1's in the Entered Number
 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace ConsoleApplication16
{
    class Program
    {
        static void Main(string[] args)
        {
            int m, count = 0;
            Console.WriteLine("Enter the Limit : ");
            m = int.Parse(Console.ReadLine());
            int[] a = new int[m];
            Console.WriteLine("Enter the Numbers :");
            for (int i = 0; i < m; i++)
            {
                a[i] = Convert.ToInt32(Console.ReadLine());
            }
            foreach (int o in a)
            {
                if (o == 1)
                {
                    count++;
                }
            }
            Console.WriteLine("Number of 1's in the Entered Number : ");
            Console.WriteLine(count);
            Console.ReadLine();
        }
    }
}
Program Explanation

In this C# program, we are reading the limit of the ‘array’ size. Using for loop enter the coefficient element values of an array. If condition statement, is used to check that the value of ‘i’ variable is equal to 1. If the condition is true then execute the statement and increment the value of the ‘count’ variable. Print the counted number of 1’s in the entered number.

 
Runtime Test Cases
 
Enter the Limit : 5
Enter the Numbers : 
1
2
1
4
1
Number of 1's in the Entered Number : 3