C++ program to check if a number can be displayed using 7 segment LED

In this tutorial we are going to learn about the logic that will check if a number can be displayed using 7 segment LED in C++. We will also implement a C++ program that will demonstrate the above logic.

What is a 7-segment display?

The seven segment display consists of 7 LED lights arranged in rectangular manner as shown in the above figure. These 7 lights are called as segments, because when they are illuminated, they form the number as per the given input and number gets displayed.

A seven-segment display is a form of electronic display device that is used for displaying decimal numbers which is an alternative to the dot matrix displays.

Seven-segment displays have wide application in digital clocks, electronic meters, basic calculators, and other electronic devices that display numeric data.

Test Case 1:

number = 5

Led provided = 5

Output: Yes

Explanation: Because, the digit 5 on 7-segment display requires 5 illuminated segments to display the digit.

Test Case 2:

number = 7

Led provided = 2

Output: No

Explanation: Because, the digit 7 on 7-segment display requires 3 illuminated segments to display the digit.

C++ code to check if the number can be displayed within given LED segments

#include <bits/stdc++.h> 
using namespace std; 

// Pre-computed values of led segments used by digit 0 to 9. 
int led_seg[10] = { 6, 2, 5, 5, 4, 5, 6, 3, 7, 6 }; 

string seg_needed(string number, int led) 
{ 
  int count = 0; 

  for (int i = 0; i < number.length(); i++)
  { 
    count += led_seg[int(number[i]) - 48]; 
  } 

  if (count <= led) 
    return "YES"; 
  else
    return "NO"; 
} 

int main() 
{ 
  string number = "5"; 
  int led = 5; 

  cout << seg_needed(number, led) << endl; 
  return 0; 
} 

Output:

Yes

 

Explanation: In the above cpp code, I have initialized the number 5 and provided LED’s in the main function which are further passed as arguments to the seg_needed() functions that computes if that number can be displayed using the given LED’s or not.

Before beginning with the seg_needed() function, I have declared the number of LED segments required for number 0 to 9 in an array led_seg[]. In the seg_needed() function, the for loop is used to compute the LED segments for every individual number if there are multiple number in number variable.

‘int(number[i])’ this logic returns the ‘i’th position number and as it is of string type so, it does the type-casting into integer. And then if refers to led_seg[] array to get to know how much LED segments are required for the number. This value is stored in the count variable and then the count value is check with variable ‘led’. If values matches then ‘yes’ is returned else ‘no’.

Leave a Reply

Your email address will not be published. Required fields are marked *