Problem inserting a 32-digit number into an array - c

I am trying to write a C program to store a 32-bit number into an Array. For Example, the number: 11000001110010000000000000000000 In the array, arr[0] would be 1 as that is the first digit.
However I am unable to get the desired output. This is my code:
#include<stdio.h>
int main ()
{
int binarynumber;
int arr[32];
printf("Enter A binary Number:\n");
scanf("%d", &binarynumber);
for (int i = 32; i >= 0; i--)
{
arr[i] = binarynumber % 10;
binarynumber /= 10;
}
printf("The first digit is %d", arr[0]);
}

If I were you, I'd read it as a string and iterate through each character and added (and converted) them to the int array. As mentioned, typing the 32 digit long number is too big to store inside an int.

I guess bitwise operations should do the job
#include<stdio.h>
int main ()
{
int binarynumber;
int arr[32];
printf("Enter A binary Number:\n");
scanf("%d", &binarynumber);
int array_size = sizeof(arr)/sizeof(arr[0])
for (int i = 0, j = array_size - 1; i < array_size; i++, j--)
{
int binarynumber_copy = binarynumber;
// shifting number `j` bits right and cutting off one bit by bitwise AND
arr[i] = (binarynumber_copy >> j) & 1;
}
printf("The first digit is %d", arr[0]);
}

First of all if you want user to input 11000001110010000000000000000000, then you can't get that whole number in an integer. So, if the user enters 3251109888 (decimal of 11000001110010000000000000000000), then better to get the number as unsigned int. Also you need to convert it to binary in the loop using %2 and /2. The loop will run from 0 to 31, so that arr[0] contains the LSB. The code will look like this -
int main ()
{
unsigned int number;
int arr[32];
printf("Enter A binary Number:\n");
scanf("%u", &number);
for (int i = 0; i < 32; i++)
{
arr[i] = number % 2;
number /= 2;
}
for (int i = 31; i >= 0; i--) {
printf("%d", arr[i]);
}
printf("\n");
return 0;
}
If you want the user to input as 11000001110010000000000000000000, you need to get that input as string and then convert it into the digit using loop. To do that you can use -
int main ()
{
int arr[32];
char number[33] = {};
scanf("%32s", number); // This will scan max 32 characters
for (int i = 0; i < 32; i++)
{
arr[i] = number[i] - '0';
}
printf("arr[0]: %d\n", arr[0]);
for (int i = 0; i < 32; i++) {
printf("%d", arr[i]);
}
printf("\n");
return 0;
}
You may want to validate whether the input contains only digit or not using isdigit() inside the loop

Related

Counting and deleting repeated digits of array elements

I need to write a program that allows user to enter an array of integers, finds the digit that appears most often in all entered numbers, and removes it from the elements of the array. If several digits appear the same number of times, the smallest of them should be deleted. If all digits of the element of the array are deleted, that element should become zero. In the end, such a modified array is printed.
Example of input and output:
Enter number of elements of the array: 5
Enter the array: 3833 8818 23 33 1288
After deleting, the array is: 8 8818 2 0 1288
Explanation: The numbers 3 and 8 appear the same number of times (6 times each), but 3 is less, so it was removed it from all members of the array. Element 33 consists exclusively of the digits 3, so that it becomes 0.
#include <stdio.h>
int main() {
int i,n,arr[100]; n;
printf("Enter number of elements of the array: ");
scanf("%d", &n);
printf("Enter the array: ");
for(i=0;i<n;i++) {
scanf("%d", &arr[i]);
}
return 0;
}
EDIT: I'm beginner to programming, and this task should be done using only knowledge learned so far in my course which is conditionals, loops, and arrays. This shouldn't be done with strings.
Divide the problem into separate tasks.
Write the code
In the code below I do not treat 0 as having digit 0. It is because it is not possible to remove 0 from 0. You can easily change this behaviour by changing while(){} loop to do{}while()
int removeDigit(int val, int digit)
{
int result = 0;
unsigned mul = 1;
int sign = val < 0 ? -1 : 1;
digit %= 10;
while(val)
{
int dg = abs(val % 10);
if(dg != digit)
{
result += dg * mul;
mul *= 10;
}
val /= 10;
}
return sign * result;
}
void countDigits(int val, size_t *freq)
{
while(val)
{
freq[abs(val % 10)]++;
val /= 10;
}
}
int findMostFrequent(const size_t *freq)
{
size_t max = 0;
for(size_t i = 1; i < 10; i++)
{
if(freq[i] > freq[max]) max = i;
}
return (int)max;
}
int main(void)
{
int table[20];
size_t freq[10] = {0,};
int mostfreq = 0;
srand(time(NULL));
for(size_t i = 0; i < 20; i++)
{
table[i] = rand();
printf("Table[%zu] = %d\n", i, table[i]);
countDigits(table[i], freq);
}
mostfreq = findMostFrequent(freq);
printf("Most frequent digit: %d\n", mostfreq);
for(size_t i = 0; i < 20; i++)
{
table[i] = removeDigit(table[i], mostfreq);
printf("Table[%zu] = %d\n", i, table[i]);
}
}
https://godbolt.org/z/PPj9s341b

Program for binary to decimal conversion in C isn't working like it's supposed to and instead gives some random outputs

The program is supposed to ask for length and number of binary arrays and then stores them and converts them all into decimal and prints the decimal part. The logic seems fine to me but it isn't working for some reason and gives weird outputs. Here's the code:
#include <stdio.h>
int main() {
int n, decimal_num = 0, base = 1, rem;
printf ("Enter the length and number of binary strings: ");
scanf(" %i", &n);
int str[n], deci[n];
for (int i = 0; i<n; i++) {
printf("Enter string %i: ", i + 1);
scanf(" %i", &str[i]);
}
for (int i = 0; i < n; i++) {
while (str[i] > 0) {
rem = str[i] % 10;
decimal_num = decimal_num + rem * base;
str[i] = str[i] / 10;
base = base * 2;
}
deci[i]= decimal_num;
decimal_num= 0;
}
for (int i = 0; i < n; i++) {
printf("%i\n", deci[i]);
}
}
There are a few issues I see with this program. First off creating arrays the way you did will give errors with most compilers. This is fixed by dynamically allocating the arrays by including stdlib.h and using malloc
int *str, *deci;
str = malloc(n * sizeof(int));
deci = malloc(n * sizeof(int));
This also means you would need to free this memory at the end at the end of your program.
free(str);
free(deci);
The second issue is in the second loop calculating the base 10 values. This is most likely what is causing the incorrect output. The issue is caused by not resetting the base variable after each iteration of the loop. This is causing the program to interpret the binary numbers at much larger than they actually are. This can be fixed by setting the base variable back to one in the same place you are setting decimal_num to zero
Another issue which doesn't affect functionality is the naming of your variables. More specifically the variable str which doesn't store a string. You should rename this to something more descriptive e.g. binary_nums. I would also recommend renaming deci for the same reason.
Additionally I was also getting issues with the scanf call using %i in the first loop so I changed it to %d which fixed the issue for me.
The fixed program looks like this
#include <stdio.h>
#include <stdlib.h>
int main() {
int n, decimal_num = 0, base = 1, rem;
int *binary_nums, *base10_nums;
printf("Enter the length and number of binary strings: ");
scanf(" %d", &n);
binary_nums = malloc(n * sizeof(int));
base10_nums = malloc(n * sizeof(int));
for (int i = 0; i < n; i++) {
printf("Enter string %i: ", i + 1);
scanf(" %d", &binary_nums[i]);
}
for (int i = 0; i < n; i++) {
while (binary_nums[i] > 0) {
rem = binary_nums[i] % 10;
decimal_num = decimal_num + rem * base;
binary_nums[i] = binary_nums[i] / 10;
base = base * 2;
}
base10_nums[i] = decimal_num;
decimal_num = 0;
base = 1;
}
for (int i = 0; i < n; i++) {
printf("%i\n", base10_nums[i]);
}
free(binary_nums);
free(base10_nums);
}
unsigned conv(const char *binaryString)
{
unsigned result = 0;
while(binaryString && *binaryString)
{
if(*binaryString == '\n') break;
result *= 2;
result += *binaryString++ == '1';
}
return result;
}
int main(void)
{
int size, number;
scanf("%u", &size);
scanf("%u", &number);
/* check return value of scanf */
char strings[number][size+1];
for(int n = 0; n < number; )
{
fgets(strings[n], size, stdin);
/* add error checks */
if(strings[n++][0] == '\n') n--;
}
for(int n = 0; n < number; n++)
{
printf("%u (0x%x) == %s", conv(strings[n]), conv(strings[n]), strings[n]);
}
}

Why does this ISBN checking code turn '0' into 45?

Can you help me find out why the second 0 in the array turns into 45 please.
Everything is okay but except this number makes the result goes wrong. I cannot find out what's the matter with this.
Here is my code:
#include <stdio.h>
int getuserchoice() {
int n;
printf("---ISBN Validate---");
printf("\n1-ISBN Checking");
printf("\n2-Quit");
printf("\nSelect: ");
scanf("%d", &n);
return n;
}
int main() {
long a[10];
long sum = 0;
int i = 0, n = 1;
long x;
if (getuserchoice() == 1) {
printf("\nEnter the values for ISBN number : ");
scanf("%ld", &x);
if (x > 0) {
while (x > 0) {
a[i] = x % 10;
x = x / 10;
i++;
}
}
for (i = 0; i < 10; i++)
printf("%ld\t", a[i]);
for (i = 0; i < 10; i++) {
sum += a[i] * n;
n++;
}
if (sum % 11 == 0)
printf("\nISBN Status: Valid!");
else
printf("\nISBN Status: Invalid!");
} else
printf("\nSee you later!");
getchar();
return 0;
}
By default uninitialized arrays contain garbage (literally anything). It so happens that that particular element contains 45 (amazing, isn't it?).
It stays 45 because leading 0s are discarded when reading a number (you should read it as a string (C++) or char[]), so you are never accessing that particular array element to give it a meaningful value.
Here's SO post on how to initialize an array with 0s in C.

Scramble numbers from array with numbers - C

I have been figuring out how to scramble numbers from array after user enters 10 different numbers by using rand(). It crushes when it arrives to adjust() function so feel free to point out my stupid mistake. Cheers. The top part is function, the bottom part is in main().
void adjust(int z[], int size)
{
int i, n, t;
for(i = 0; i < size; i++)
{
size = rand();
t = z[size];
z[size] = z[i];
z[i] = t;
}
printf("\nYour numbers have been scrambled and here they are: \n", t);
}
.....................
int z[10];
int i;
int num = 0;
printf("Please enter 10 different numbers: \n");
for(i = 0; i < 10; i++)
{
z[i] = num;
scanf("%d", &num);
}
printf("\nThe numbers you entered were: ");
for (i = num; i <= 10; i++)
{
printf("%d ", z[i]);
}
printf("\n");
addNum(z, 10);
adjust(z, 10);
return 0;
The rand() function returns a number between 0 and RAND_MAX.
Hence, the array index can go well beyond its range.
To get a random index within a range from 0 to N -1 , use rand() % N.
Another issue is that in your for loop, in adjust function, you are destroying the original value of 'size'. That contains the length of your array and is used to check the terminating condition of your for loop. Hence, do not modify 'size'. Use another variable to store your random index.
for(i = 0; i < size; i++)
{
n = rand() % size; // n is between 0 and size-1
t = z[n];
z[n] = z[i];
z[i] = t;
}
// For a better design move the following lines to a separate function
// that way adjust function just does the scrambling while another
// printing function prints out the array. Each function does only one thing.
printf("\nYour numbers have been scrambled and here they are: \n");
for( i = 0; i < size; i++)
{
printf("%d ", z[i]);
}

Most frequent element in a sequence using arrays in C

I'm doing an online course on "Programming, Data Structure & Algorithm". I've been given an assignment to "find the most frequent element in a sequence using arrays in C (with some constraints)". They've also provided some test-cases to verify the correctness of the program. But I think I'm wrong somewhere.
Here's the complete question from my online course.
INPUT
Input contains two lines. First line in the input indicates N,
the number of integers in the sequence. Second line contains N
integers, separated by white space.
OUTPUT
Element with the maximum frequency. If two numbers have the
same highest frequency, print the number that appears first in the
sequence.
CONSTRAINTS
1 <= N <= 10000
The integers will be in the range
[-100,100].
And here's the test cases.
Test Case 1
Input:
5
1 2 1 3 1
Output:
1
Input:
6
7 7 -2 3 1 1
Output:
7
And here's the code that I've written.
#include<stdio.h>
int main()
{
int counter[201] = {0}, n, i, input, maximum = 0;
scanf("%d", &n);
for(i = 1; i <= n; i++) {
scanf("%d", &input);
if(input < -100 && input < 100)
++counter[input];
}
maximum = counter[0];
for (i = 1; i < 201; i++) {
if (counter[i] > maximum) {
maximum = counter[i];
}
}
printf("%d", maximum);
return 0;
}
Please tell me where I'm wrong. Thank you.
EDIT:
I've modified the code, as suggested by #zoska. Here's the working code.
#include<stdio.h>
int main()
{
int counter[201] = {0}, n, i, input, maximum = 0;
scanf("%d", &n);
for(i = 1; i <= n; i++) {
scanf("%d", &input);
if(input < 100 && input > 0)
++counter[input + 100];
else
++counter[input];
}
maximum = counter[0];
for (i = 0; i < 201; i++) {
if (counter[i] > maximum) {
maximum = i - 100;
}
}
printf("%d", maximum);
return 0;
}
Additionally to problem pointed out by Paul R is:
You are printing maximum occurrences of number, not the number itself.
You're going to need another variable, which will store the number with maximum occurences. Like :
maximum = count[0];
int number = -100;
for (i = 0; i < 201; i++) {
if (counter[i] > maximum) {
maximum = counter[i];
number = i - 100;
}
}
printf("number %d has maximum occurences: %d", number, maximum);
Also you should iterate through an array from 0 to size-1:
So in all cases of your loops it should be :
for(i = 0; i < 201; i++)
Otherwise you won't be using count[0] and you will only have a range of -99...100.
Try below code
#include<stdio.h>
int main()
{
int counter[201] = {0}, n, i, input, maximum = 0;
scanf("%d", &n);
for(i = 1; i <= n; i++) {
scanf("%d", &input);
if(input >= -100 && input <= 100)
++counter[input + 100];
}
maximum = counter[0];
int index = 0;
for (i = 0; i < 201; i++) {
if (counter[i] >= maximum) {
index = i;
maximum = counter[i];
}
}
printf("number %d occured %d times\n", index-100, maximum);
return 0;
}
I would prefer checking in one loop itself for the maximum value just so that the first number is returned if i have more than one element with maximum number of occurances.
FInd the code as:
#include<stdio.h>
int main()
{
int n,input;
scanf("%d",&n);
int count[201] ={0};
int max=0,found=-1;
for(int i=0;i<n;i++)
{
scanf("%d",&input);
count[input+100]++;
if(max<count[input+100])
{
max= count[input+100];
found=input;
}
}
printf("%d",found);
return 0;
}
But, there is also one condition that if the number of occurance are same for two numbers then the number which appers first in sequence should appear.

Resources