Reversal of Array in C Using Given Array - c

I am having trouble implementing a reversal of an array in C. I am using linux/nano and we have just started, so very minimal has been taught. The code below is what I have, and the array will print of the binary numbers of whatever integer is entered, but in this code, the binary is reversed from what it should be.
#include "stdio.h"
#define MAX_BITS 32
int main()
{
int num;
printf("Enter a valid positive integer: ");
scanf("%d", &num);
int array[MAX_BITS];
int bit, val;
int numDown = 1;
while (numDown <= num)
{
val = numDown;
while (val > 0)
{
bit = val % 2;
printf("%d",bit);
val = val / 2;
}
printf("\n");
numDown = numDown + 1;
}
return 0;
}
I know I need a while loop but I am unsure as to how to go about it.

#include <stdio.h>
#define MAX_BITS 32
int main()
{
int num;
printf("Enter a valid positive integer: ");
scanf("%d", &num);
char array[MAX_BITS];
int index = MAX_BITS - 1;
int temp = num;
do
{
array[index--] = temp % 2;
temp /= 2;
}while(temp != 0);
printf("Binary of %d is: ", num);
for (int i = index + 1; i < MAX_BITS; ++i )
{
printf("%d", array[i]);
}
printf("\n");
return 0;
}

Related

how to extract the even number from user input, and combine them as a new number in C program

test case:
input: 1234
output: 24
input: 2468
output: 2468
input: 6
output: 6
I have this code:
#include <stdio.h>
#include <math.h>
int main() {
int num;
printf("Enter a number: \n");
scanf("%d", &num);
int numberLength = floor(log10(abs(num))) + 1;
int inputNumberArray[numberLength];
int evenNumberCount = 0;
int even[10];//new even no. array
int i = 0;
do {
inputNumberArray[i] = num % 10;
num = num / 10;
i++;
} while (num != 0);
i = 0;
while (i < numberLength) {
if (inputNumberArray[i] % 2 == 0) {
evenNumberCount ++;
even[i] = inputNumberArray[i];
}
i++;
}
printf("array count %d\n", evenNumberCount);
i = 0;
for (i = 0; i < 8; i++) {
printf(" %d", even[i]);//print even array
}
i = 0;
int result = 0;
for (i = 0; i < 10; i++) {
if (evenNumberCount == 1) {
if (even[i] != 0) {
result = even[i];
} else {
break;
}
} else {
if (even[i] != 0) {
result = result + even[i] * pow(10, i);
} else
break;
}
}
printf("\nresult is %d", result);
/*
int a = 0;
a = pow(10, 2);
printf("\na is %d", a);
*/
}
when I enter number 1234, the result/outcome is 4, instead of 24.
but when I test the rest of test case, it is fine.
the wrong code I think is this: result = result + even[i] * pow(10, i);
Can you help on this?
Thanks in advance.
why do you have to read as number?
Simplest algorithm would be
Read as text
Validate
loop through and confirm if divisible by 2 and print live
next thing, have you try to debug?
debug would let you know what are doing wrong. Finally the issue is with indexing.
evenNumberCount ++; /// this is technically in the wrong place.
even[i]=inputNumberArray[i]; /// This is incorrect.
As the user Popeye suggested, an easier approach to accomplish this would be to just read in the entire input from the user as a string. With this approach, you can iterate through each letter in the char array and use the isdigit() method to see if the character is a digit or not. You can then easily check if that number is even or not.
Here is a quick source code I wrote up to show this approach in action:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main()
{
char input[100] = { '\0' };
char outputNum[100] = { '\0' };
// Get input from user
printf("Enter a number: ");
scanf_s("%s", input, sizeof(input));
// Find the prime numbers
int outputNumIndex = 0;
for (int i = 0; i < strlen(input); i++)
{
if (isdigit(input[i]))
{
if (input[i] % 2 == 0)
{
outputNum[outputNumIndex++] = input[i];
}
}
}
if (outputNum[0] == '\0')
{
outputNum[0] = '0';
}
// Print the result
printf("Result is %s", outputNum);
return 0;
}
I figured out the solution, which is easier to understand.
#include <stdio.h>
#include <math.h>
#define INIT_VALUE 999
int extEvenDigits1(int num);
void extEvenDigits2(int num, int *result);
int main()
{
int number, result = INIT_VALUE;
printf("Enter a number: \n");
scanf("%d", &number);
printf("extEvenDigits1(): %d\n", extEvenDigits1(number));
extEvenDigits2(number, &result);
printf("extEvenDigits2(): %d\n", result);
return 0;
}
int extEvenDigits1(int num)
{
int result = -1;
int count = 0;
while (num > 1) {
int digit = num % 10;
if (digit % 2 == 0) {
result = result == -1 ? digit : result + digit * pow(10, count);
count++;
}
num = num / 10;
}
return result;
}
}
You are overcomplicating things, I'm afraid.
You could read the number as a string and easily process every character producing another string to be printed.
If you are required to deal with a numeric type, there is a simpler solution:
#include <stdio.h>
int main(void)
{
// Keep asking for numbers until scanf fails.
for (;;)
{
printf("Enter a number:\n");
// Using a bigger type, we can store numbers with more digits.
long long int number;
// Always check the value returned by scanf.
int ret = scanf("%lld", &number);
if (ret != 1)
break;
long long int result = 0;
// Use a multiple of ten as the "position" of the resulting digit.
long long int power = 1;
// The number is "consumed" while the result is formed.
while (number)
{
// Check the last digit of what remains of the original number
if (number % 2 == 0)
{
// Put that digit in the correct position of the result
result += (number % 10) * power;
// No need to call pow()
power *= 10;
}
// Remove the last digit.
number /= 10;
}
printf("result is %lld\n\n", result);
}
}

how do I add up the sum of the digits of a number except for digits that repeat themselves in c?

I have an assignment and I need to add up the digits of it and ignore the once that repeat themselves
for example 234111 -> 2 + 3 + 4 + 1 -> 10
I tried doing this:
#include
int main(void)
{
int i = 0;
int num = 0;
int sum = 0;
printf("Please enter a number\n");
scanf("%d", &num);
while(num > 0){
sum += num%10;
num /= 10;
}
printf("%d", sum);
return 0;
}
what I did just adds up the digits, it doesn't ignore that ones that get repeated
What do i need to add to the code?
You can keep an array of 'flags' for which digits have been used already:
#include <stdio.h>
int main(void)
{
// int i = 0; // You don't actually use this in the code!
int num = 0;
int sum = 0;
int used[10] = { 0, }; // Set all "used" flags to zero
printf("Please enter a number\n");
scanf("%d", &num);
while (num > 0)
{
int digit = num % 10; // Get the digit
if (!used[digit]) sum += digit; // Only add if not used already
used[digit] = 1; // Now we have used it!
num /= 10;
}
printf("%d", sum);
return 0;
}
Feel free to ask for further clarification and/or explanation.
Just read each character and record if you've already seen it:
#include <stdio.h>
#include <ctype.h>
int
main(void)
{
int seen[10] = {0};
int sum = 0;
int c;
while( ( c = getchar()) != EOF ) {
int v = c - '0';
if( isspace(c)) {
continue;
}
if( v < 0 || v > 9 ) {
fprintf(stderr, "Invalid input\n");
return 1;
}
if( ! seen[v]++ )
sum += v;
}
printf("%d\n", sum);
return 0;
}

C program to find if a number is palindrome or not

I made a C program to check if a number is palindrome or not. I used the following code, but it shows numbers like 12321 as non palindrome. Can you please explain me the mistake in the program below?
#include <stdio.h>
int main()
{
int i, x, n, c, j;
int d=0;
printf ("enter total digits in number: ");
scanf ("%d", &i);
printf ("\nenter number: ");
scanf ("%d", &n);
j=n;
for (x=1; x<=i; x++)
{
c= j%10;
d=c*(10^(i-x))+d;
j=(j-c)/10;
}
if (d==n)
{
printf ("\npalindrome");
}
else
{
printf ("\nnon palindrome");
}
return 0;
}
^ is the xor operator.
In order to raise power, you need to include math.h and call pow
d = (c * pow(10, i - x)) + d;
this algorithm is as simple as human thinking, and it works
#include <stdio.h>
int main() {
int i=0,n,ok=1;
char buff[20];
printf("Enter an integer: ");
scanf("%d", &n); // i am ommiting error checking
n=sprintf(buff,"%d",n); //convert it to string, and getting the len in result
if(n<2) return 0;
i=n/2;
n--;
while(i && ok) {
i--;
//printf("%c == %c %s\n", buff[i],buff[n-i],(buff[i]==buff[n-i])?"true":"false");
ok &= (buff[i]==buff[n-i]);
}
printf("%s is %spalindrome\n",buff, ok?"":"not ");
return 0;
}
// Yet another way to check for palindrome.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
int n, rn, tn;
printf("Enter an integer: ");
scanf("%d", &n);
// reverse the number by repeatedly extracting last digit, add to the
// previously computed partial reverse times 10, and keep dropping
// last digit by dividing by 10
for (rn = 0, tn = n; tn; tn /= 10) rn = rn * 10 + tn % 10;
if (rn == n) printf("%d is palindrome\n", n);
else printf("%d is not palindrome\n", n);
}
A loop like this might do:
int src; // user input
int n; // no of digits
int res = 0;
int tmp; // copy of src
// .... read the input: n and src ....
tmp = src;
for(int i = 0; i < n; i ++)
{
int digit = tmp % 10; // extract the rightmost digit
tmp /= 10; // and remove it from source
res = 10*res + digit; // apend it to the result
}
// ...and test if(res == src)...

converting decimal-number to binary-number

My program should convert a decimal number into a binary number.
The first for loop is for calculating the binary number.
The second loop puts the msb into the first element of the array.
It is an exercise and the msb has to be in the first element.
I do not understand where the mistake is, help is very much appreciated.
#include<stdio.h>
#include<stdlib.h>
int main(void){
int i;
int bits[16];
int bits_2[16];
int number;
int decimal;
int rest;
int msb;
int result=1;
printf( "Input number smaller than 65536: ");
scanf("%d", &decimal);
if(decimal >= 65536) {
printf( "\n\nincorrect input!");
return EXIT_FAILURE;
}
number=decimal;
for(i=0; result!=0; i++){
result = decimal / 2;
rest = result %2;
bits[i]=rest;
msb = i;
return msb;
}
printf("\n\n %d as binary number : ", number);
for(i=msb; bits[i]>=bits[0]; i--){
bits_2[msb-i] = bits[msb];
printf("%d", bits_2[msb-i]);
}
return 0;
}
result = number = decimal;
for(bits[0]=msb=i=0; result != 0; i++){
bits[i] = result % 2;
result = result / 2;
msb = i;
}
printf("\n\n %d as binary number : ", number);
for(i=msb; i >= 0; i--){
bits_2[msb-i] = bits[i];
printf("%d", bits_2[msb-i]);
}
This is your code with some changes to make it work (you can improve it)
#include<stdio.h>
#include<stdlib.h>
int main(void){
int i;
int bits[16];
int bits_2[16];
int number;
int decimal;
int rest;
int msb;
int result=1;
printf( "Input number smaller than 65536: ");
scanf("%d", &decimal);
if(decimal >= 65536) {
printf( "\n\nincorrect input!");
return EXIT_FAILURE;
}
number=decimal;
for(i=0; result!=0; i++){
result = number / 2; //change this line
rest = number %2; // change this line
number=result; // add this line
bits[i]=rest;
msb = i;
// return msb; //delete this line
}
printf("\n\n %d as binary number : ", decimal); // change this line
for(i=msb; i+1; i--){ // change the condition
// bits_2[msb-i+1] = bits[msb]; // delete this line
printf("%d", bits[i]); // change this line
}
return 0;
}
I noticed that you have a lot of useless variables so this is a compact version of your program:
#include <stdio.h>
#include <stdlib.h>
int main(void){
int i;
int bits[16];
unsigned int decimal;
int rest;
int result=1;
printf( "Input number smaller than 65536: ");
scanf("%d", &decimal);
if(decimal >= 65536) {
printf( "\n\nincorrect input!");
return EXIT_FAILURE;
}
else
printf("\n\n %d as binary number : ", decimal);
for(i=0; result!=0; i++){
result = decimal / 2;
rest = decimal %2;
decimal=result;
bits[i]=rest;
}
i--;
for(; i+1; i--){
printf("%d", bits[i]);
}
return 0;
}

Converting binary to number string to decimal number in C

I've written a program that asks the user to input a number using strings, the program then will convert that number to decimal, however Im having a problem with it, when I compile (using -lm) and run the a.out, I get a Segmentation fault (core dumped), not really sure where to look or how to fix it, also one more question what do i need so that it prints the result of the conversion (printf("something..")) ?
#include <stdio.h>
#include <string.h>
#include <math.h>
int main()
{
char string[100];
int s;
char a;
char j;
int sum;
printf("B = B to D\n");
printf("D = D to B\n");
printf("choose which one to convert to:");
scanf("%c%c", &a, &j);
if (a == 'B')
{
printf("enter binary number to convert to decimal: ");
scanf("%s", string);
for(s = strlen-1; s >= 0; s--)
{
if(string[s] == '1')
{
sum = sum + pow(2,s);
}
}
}
return 0;
You probably meant to have strlen(string) - 1, not strlen - 1. My best guess is that your program is interpreting strlen as a function pointer, and it's pretty much a given that crazy things happen after that.
As it is, you might be interested in the strtol function, which appears to do exactly what you're looking for.
You use strlen as an integer. I think you mean strlen(string)
for(sum=0, j=0, s=strlen(string)-1; s >= 0; s--, ++j){
if(string[s] == '1'){
sum = sum + pow(2,j);
}
}
printf("%d\n",sum);
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <ctype.h>
#include <stdlib.h>
void reverse_string(char *string)
{
int string_length = strlen(string);
char temp;
int i;
for (i = 0; i < string_length/2; i++)
{
temp = string[i];
string[i] = string[string_length - (i + 1)];
string[string_length - (i + 1)] = temp;
}
}
int main()
{
char string[100];
int s;
char a;
char j;
int sum = 0;
int string_length = 0;
int number, original_number;
int remainder;
char binary_string[200];
int i = 0;
printf("B = B to D\n");
printf("D = D to B\n");
printf("choose which one to convert to:");
scanf("%c%c", &a, &j);
a = toupper(a);
if (a == 'B')
{
printf("enter binary number to convert to decimal: ");
scanf("%s", string);
string_length = strlen(string);
for(s = strlen(string)-1; s >= 0; s--)
{
if(string[s] == '1')
{
sum = sum + pow(2,string_length - (s + 1));
}
}
printf("%s in binary is %d\n",string,sum);
}
else if (a == 'D')
{
printf("enter positive decimal number to convert to binary: ");
scanf("%s",string);
number = atoi(string);
original_number = number;
if ( number < 0 )
{
printf("ERROR: only positive numbers please\n");
return 1;
}
do
{
remainder = number % 2;
if ( remainder == 0 )
binary_string[i] = '0';
else
binary_string[i] = '1';
number = number / 2;
i += 1;
}
while (number > 0);
binary_string[i] = '\0';
reverse_string(binary_string);
printf("decimal %d is %s in binary\n",original_number,binary_string);
}
return 0;
}
strlen isn't used properly. I think you want to do something like strlen(string)-1. BTW your logic wont work to convert the fractional part. Check this code:
#include <stdio.h>
#define MAX 1000
int main()
{
double fraDecimal=0.0,dFractional=0.0 ,fraFactor=0.5;
long dIntegral = 0,bIntegral=0,bFractional[MAX];
long intFactor=1,remainder,i=0,k=0,flag=0;
char fraBinary[MAX];
printf("Enter any fractional binary number: ");
scanf("%s",&fraBinary);
while(fraBinary[i]) //Separating the integral and fractional parts
{
if(fraBinary[i] == '.')
flag = 1; //If dot is found start taking the fractional part.
else if(flag==0)
bIntegral = bIntegral * 10 + (fraBinary[i] -48);
/* char - 48 to get the numerical value.*/
else
bFractional[k++] = fraBinary[i] -48;
i++;
}
while(bIntegral!=0){
remainder=bIntegral%10;
dIntegral= dIntegral+remainder*intFactor;
intFactor=intFactor*2;
bIntegral=bIntegral/10;
}
for(i=0;i<k;i++){
dFractional = dFractional + bFractional[i] * fraFactor;
fraFactor = fraFactor / 2;
}
fraDecimal = dIntegral + dFractional ;
printf("Equivalent decimal value: %Lf",fraDecimal);
return 0;
}
Source:
C Program to Convert Binary into Decimal Number

Resources