- Write a function that initializes each element $$tab[i]$$ of a tab array to the value $$2^i$$.
- Using the first question, write a program that reads characters equal to 0 or 1 from the keyboard and calculates the number that these digits represent in binary. We can display in base 10 the result.
Example:
Enter 0 or 1 : 1
Current value : 1
Enter 0 or 1 : 0
Current value : 1
Enter 0 or 1 : 1
Current value : 5
Enter 0 or 1 : 1
Current value : 13
Enter 0 or 1 : 0
Current value : 13
Enter 0 or 1 : 1
Current value : 45
Enter 0 or 1 : 0
Current value : 45
Enter 0 or 1 : 0
Current value : 45
Enter 0 or 1 : 1
Current value : 301
Difficulty level
This exercise is mostly suitable for students
#include<stdio.h>
#include<conio.h>
#define NB_MAX 20
void fill(unsigned int t[NB_MAX])
{
int i = 1;
t[0] = 1;
while (i < NB_MAX)
{
t[i] = t[i - 1] * 2;
i++;
}
}
void main()
{
char c;
int choice, i = 0;
unsigned int n=0;
unsigned int t[NB_MAX];
fill(t);
while (1) // infinite loop
{
choice = 0;
printf("Enter 0 or 1 : ");
while (!choice)
{
c = getchar();
choice = ((c == '0') || (c == '1'));
}
if (c == '1')
n += t[i];
i++;
printf("Current value : %d\n", n);
}
getch();
}
Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Checking whether elements of 2 BSTs are the same using an iterative function