Decimal to Binary C - c

I have to write a C program that converts decimal to binary using numbers between 0 to 255. using 3 functions and no global variables. When I get it to run it just prints all zeros for some reason. This is what I have so far:
#include <stdio.h>
int getNumber();
int dectoBin(int, int binarray[], int);
void printBin(int binary[], int dec);
int main(){
int M = 7;
int binarray[M];
int dec = getNumber();
printf("The decimal number you entered was: %d", dec);
*binarray = decToBin(dec, binarray, M);
printBin(binarray, dec);
return 0;
}
int getNumber(){
int dec;
printf("Enter any a number between 0 and 255: ");
scanf("%d",&dec);
return 0;
}
int decToBin(int dec, int binarray[], int M){
int i, j;
if(dec>255)
printf("Please enter a number between 0 and 255");
else
for(i=7; i>=0;i--){
j = dec >>i;
if(j & 1){
binarray[i] = 1;
}
else {
binarray[i] = 0;
}
}
return *binarray;
}
void printBin(int binary[], int dec){
int i;
if(dec > 255){
printf("PLese use another number");
main();
}
else
{
for(i =7; i > 0;i--){
printf("%d", binary[i]);
printf("\n");
}
}
}

In your function:
int getNumber(){
int dec;
printf("Enter any a number between 0 and 255: ");
scanf("%d",&dec);
return 0;
}
You return 0, you should return dec:
int getNumber(){
int dec;
printf("Enter any a number between 0 and 255: ");
scanf("%d",&dec);
return dec;
}

In printBin you only prints 7 bits instead of 8 bits.
Change for(i =7; i > 0;i--){ to for(i = 7; i >= 0; i--){
And in main change: int M = 7; to int M = 8;. You need 8 bits for the range 0..255.
*binarray = decToBin(dec, binarray, M); is plain wrong and not necessary, write decToBin(dec, binarray, M) ;. The decToBin function takes already care of filling the binarray array.
Otherwise the architecture of your program is poor:
The test if the input is between 0 and 255 should be in getNumber or
in main, but not in printBin.
The call to main() inside the printBin function is completely
wrong, even if the program works correctly.
I leave this as an exercise to the reader to find out why.

Related

How to turn my function returns an array in C?(code to fix)

I am trying to make an array store each number I type in.
Some like:
Enter number:687544
And return as an array like:
6 8 7 5 4 4
I only figure out how to store the nums in order in the "store (num) " function below:
#include<stdio.h>
int store(int num);
int main()
{
    int num;
    printf("Enter number: ");
    scanf("%d",&num);    
    return store(num);
}
int store(int num)
{  
if(num!= 0)
    {
int mod = num % 10;  //split last digit from number
     store(num/10);  //recuring it back to the right order
     printf("%i\n",mod); //divide num by 10. num /= 10 also a valid one 
}
}
Following is I tried but not working code
#include<stdio.h>
int store(int num);
int main()
{
int num,d;
printf("Enter number: ");
scanf("%d",&num);
for(d=0; num<0;d++);
{
num /= 10;
}
int a[d];
int i;
for(i=0;i<d;i++){
a[d]=store(num);
}
printf("%d \n",a[d]);
}
int store(int num)
{
if(num!= 0)
{
int mod = num % 10;
store(num/10);
return mod;
}
}
Unexpected Result.......
Enter number: 123
115183680
Feel like I almost there but I have no idea which part goes wrong. May I ask how to fix this?
I only figure out how to store the nums in order in the "store (num) " function, however I tried the to expand my code that the result is not I expected.
Here is you code fixed, based on the same routing you have wrote, (using recursive calls) and reading int and parsing digits, etc
#include<stdio.h>
void store(int num, int* a, int* d);
int main()
{
int a[10]; // int is 32bit, (Depending on compiler, you can not store more than 10 digit) log10(2**32) ~ 9.xx
int num,d = 0;
printf("Enter number: ");
scanf("%d",&num);
// the recursive function, should need the pointer to array, and the index which is currently parsing
store(num, a, &d);
// print your array till valid index,
for(int i = 0; i< d; i++)
printf("%d ",a[i]);
printf("\n");
}
void store(int num, int* a, int* d)
{
if(num!= 0)
{
store(num/10, a, d);
int mod = num % 10;
a[(*d)++] = mod;
}
}
Here's a modifed version with comments on what I changed
int store(int num, int digit);
int a[20]; // Don't bother with dynamic allocation
int main()
{
int num,d;
printf("Enter number: ");
scanf("%d",&num);
int digit = 0;
int i;
digit = store(num, 0);
// Always print at least 1 digit
for(i=0; i< (digit ? digit : 1); i++){
printf(" %d", a[i]);
}
printf("\n");
}
// Pass in which digit you are on
int store(int num, int digit)
{
if(num!= 0)
{
int mod = num % 10;
int last = store(num/10, digit+1); // next digit
// Fill array right-to-left
a[last - digit - 1] = mod;
return last;
}
return digit; // return number of digits
}
Output
prog$ ./foo
Enter number: 0
0
prog$ ./foo
Enter number: 5
5
prog$ ./foo
Enter number: 123
1 2 3
Note that if you don't want a global array, you can add it as a third parameter to store. Don't forget to initialize a[0] in main in that case.

The following program "Counting consecutive 1's of a binary no" shows different ans when input goes more than 8-digit value?

I have tried different inputs and when it exceeds a 7 or 8 digit value it just shows some wrong answers as outputs but it worked fine with most of my cases.
#include <stdio.h>
#include <stdlib.h>
int bin(unsigned long long int n){//gave function for binary convertion
if(n==0)
return 0;
else
return (n%2+10*bin(n/2));
}
int main()
{
unsigned long long int n,x;/*I even gave high digit data type*/
int i, v, count=0, max=0;
scanf("%llu",&n); /*if input is >8-digit output is wrong*/
x = bin(n);
v = floor(log10(x))+1; /*Its length*/
int a[v];
for(i = v-1; i >= 0; i--){ /*string it in array*/
a[i] = x%10;
x = x/10;
}
for(i = 0; i < v; i++){
if(a[i] == 0){
count = 0;}
else{
count++;}
if(max < count){
max = count;}
}
printf("%d",max);/*I gave 99999999 output is 8 but its shows 9*/
}
Your program has a number of problems. Here is one example:
int bin(unsigned long long int n){
^^^
The function returns an int so the calculation will overflow for even small numbers:
printf("%d\n", bin(1023)); // will print 1111111111 (fine)
printf("%d\n", bin(1024)); // will/may print 1410065408 (ups - very bad)
Even if you change to
unsigned long long int bin(unsigned long long int n){
overflow will happen soon.
In I'll recommend that you look directly into the binary pattern of the number using the & operator.
I'll not solve the complete task for you but here is some code that may help you.
#include <stdio.h>
#include <stdlib.h>
int main()
{
size_t t = 1;
size_t limit;
size_t n;
if (scanf("%zu", &n) != 1)
{
printf("Illegal input\n");
exit(1);
}
limit = 8 * sizeof n; // Assume 8 bit chars
for (size_t i = 0; i < limit; ++i)
{
if (n & t)
{
printf("Bit %zu is 1\n", i);
}
else
{
printf("Bit %zu is 0\n", i);
}
t = t << 1;
}
return 0;
}

Program to print N first factorial numbers in c

Factorial number is a number that is multiplied by it's previous numbers. For example it's 5. 1*2*3*4*5 is it's factorial number.
I already made a program which prints factorial of any number, but i don't know how to make it to print N first factorial number in c.
For example i type 10. It must show first 10 numbers along with their factorials (Making a table)
Here is what i was made to print factorial of any number.Is there any possibility to do with while/ if else statements/ and for loop?
#include <stdio.h>
int main()
{
int i, n, fakt = 1;
printf("Enter a number:\n");
scanf("%d", &n);
for (i = 1; i <= n; i++)
fakt = fakt*i;
printf("Factorial of %d js %d\n", n, fakt);
getch();
}
You probably want this:
Program:
#include <stdio.h>
int main()
{
int i, n, fakt = 1;
printf("Enter a number:\n");
scanf("%d", &n);
for (i=1;i<= n;i++) //use braces to write more than one statement inside the loop
{
fakt=fakt*i;
printf("Factorial of %d is %d\n", i, fakt);
}
getch();
}
Output:
Enter a number:
5
Factorial of 1 is 1
Factorial of 2 is 2
Factorial of 3 is 6
Factorial of 4 is 24
Factorial of 5 is 120
#include <conio.h>
#include <stdio.h>
void main()
{
int f=1,i,v;
clrscr();
printf("Enter the number :");
scanf("%d",&v);
for(i=1;i<=v;i++)
{
f=f*i;
printf("num =%d and fac=%d\n",i,f);
}
getch();
}
this code will work
That code already uses the for loop. The while loop equivalent is:
i = 1;
while (i <= n) {
fakt = fakt*i;
i++;
}
#include <stdio.h>
int factorial(int n)
{
int i,fakt = 1;
printf("Enter a number:\n");
scanf("%d", &n);
for (i = 1; i <= n; i++)
fakt = fakt*i;
return fakt;
}
int main()
{
int n;
printf("Enter a number:\n");
scanf("%d", &n);
int i = 0;
for(i=1;i<=n;i++)
{
printf("Factorial for %d is %d\n",i,factorial(i));
}
return 0;
}
I think this will do the job just fine.
You can do a nested loop.
Run the parent loop from 1 to n,
and the nested loop will be your already working for loop.
You may want this:
#include <stdio.h>
int main()
{
int n, i, num, factorial;
printf("Enter the number of terms: ");
scanf("%d", &n);
for(i = 1; i <= n; i++)
{
num = i;
factorial = 1;
while(num)
factorial *= num--;
printf("%d \t %d\n", i, factorial);
}
return 0;
}
Output:
Enter the number of terms: 10
1 1
2 2
3 6
4 24
5 120
6 720
7 5040
8 40320
9 362880
10 3628800
Use this fastest version of factorial using recursion with if ..else statement
#include<stdio.h>
int fact(int n);
void main()
{
int n;
printf("\nEnter an integer:");
scanf("%d",&n);
fact(n);
}
int fact(int n)
{
int a;
if(n==0)
{
printf("The Factorial of 0 is 1\n");
return 1;
}
else
{
a=n*fact(n-1);
printf("The Factorial of %d is %d\n",n,a);
return a;
}
}
#include<stdio.h>
int main(int n){
int fact;
clrscr();
printf("Enter a number and type exit:\n");
scanf("%d",&n);
if(n!=0){
fact=n*main(n-1);
printf("Factorial of %d is %d\n",n,fact);
getch();
return fact;
}
else{
printf("Factorial of 0 is 1.\n");
getch();
return 1;
}
}

How to invent a code for square-root?

I want to write a code for making square-root not using pow().
here is what i have tried:
#include <stdio.h>
#include <stdlib.h>
int main(){
int a,I,sum=0,cnt=0;
printf("enter number");
scanf("%d",&a);
for(I=1;sum<a;I+=2){
sum+=I;
cnt++;
}
printf("answer is:%d",cnt);
return 0;
}
for numbers like 4,9,16,... it works but for numbers like 10,17,21,.. it does not work and the result is more than it shoud be.
what is the problem?
for(I=1;;I+=2){
sum+=I;
if(sum>a)
break;
cnt++;
}
#include <stdio.h>
#include <stdlib.h>
int main(){
int a,I,sum=0,cnt=0;
printf("enter number");
scanf("%d",&a);
for(I=1;sum<a;I+=2){
sum+=I;
cnt++;
}
if(sum==a)
printf("answer is:%d",cnt);
else
printf("answer is:%d",cnt-1);
return 0;
}
You can try this
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a,I,cnt=0;
int sum = 0;
printf("enter number");
scanf("%d",&a);
for(I=1;sum<a;I+=2){
sum+=I;
cnt++;
if(sum > a) //add this if statement to decrement cnt by 1 when sum exceeds a.
cnt--;
}
printf("answer is:%d",cnt);
}
Input:
21
Output:
4
Use the Babylonian method:
double babyl_sqrt(double x)
{
double i;
for (i = x / 2; fabs(i * i - x) > 0.000001f; i = (i + x / i) / 2)
;
return i;
}
To get a rounded to nearest int, adjust the limit a little bit.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int sqrt_round(int a) {
int I;
int sum = 0;
int cnt = 0;
// for(I=1;sum<a;I+=2){
for (I = 1; (sum + I / 2) < a; I += 2) {
sum += I;
cnt++;
}
return cnt;
}
int main() {
int a;
printf("enter number");
scanf("%d", &a);
printf("answer is:%d\n", sqrt_round(a));
printf("answer is:%g\n", sqrt(a));
return 0;
}
#include<stdio.h>
int main()
{
float i,x=10;
int lp;
scanf("%f",&i);
for(lp=0;lp<5;lp++)
x=(x-((((x*x)-i))/(2*x)));
printf("sqaure root of %f=%f\n",i,x);
return 0;
}
Compute and return the square root of x, where x is guaranteed to be a non-negative integer.
Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned.
Example 1:
Input: 4
Output: 2
Example 2:
Input: 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since
the decimal part is truncated, 2 is returned.
public int mySqrt(int x) {
long start = 1;
long end = x;
while(start + 1< end) {
long mid = start + (end - start) / 2 ;
if(mid * mid == x) {
return (int)mid;
}else if(mid * mid < x) {
start = mid ;
}else {
end = mid;
}
}
if(end * end == x) {
return (int)end;
}
return (int)start;
}

prime numbers in a given range

I have to find all the prime numbers between two numbers m and n. (1 <= m <= n <= 1000000000 and n-m <= 100000). I am using sieve of eratosthenes but getting wrong answer. Can anyone help me what is wrong with my code.
#include<stdio.h>
#include<math.h>
int S[100002];
void sieve(long long int m, long long int n)
{
long long int x=sqrt(n);
long long int i,j;
long long int a;
for(i=0;i<=n-m+2;i++)
S[i]=0;
if(m%2==0)
i=m;
else {
i=m+1;
}
for (;i<=n;i+=2){
S[i-m]=1;
}
for (i=3;i<=x;i+=2){
if(i>=m && S[i-m]) continue;
if(i*i>=m)j=i*i;
else {
a = (m-i*i)%(2*i);
if(a==0)j=m;
else
j=m+ (2*i -a);
}
for (;j<=n;j+=2*i){
S[j-m]=1;
}
}
if (m==1)i=1; else i=0;
for (;i<=n-m;i++)
if (!S[i]){
printf("%lld\n",i+m);
}
}
int main(){
int t;
long long int m,n;
scanf("%d\n",&t);
while(t--){
scanf("%lld %lld",&m,&n);
sieve(m,n);
printf("\n");
}
return(0);
}
if(m%2==0)
i=m;
else {
i=m+1;
}
for (;i<=n;i+=2){
S[i-m]=1;
}
Now, what happens if m <= 2? Will 2 be considered prime or not?
You should use loop in main and call prime function.
For performance, I recommend you to avoid using sqrt function because it requires a lot of CPU clocks.
bool isPrime(int number){
if(number < 2) return false;
if(number == 2) return true;
if(number % 2 == 0) return false;
for(int i=3; (i*i)<=number; i+=2){
if(number % i == 0 ) return false;
}
return true;
}
***Change datatype for the range of number (long, long long, etc).
It is the most efficient(Sieve method) way of finding prime number between a range.
Here 1 is not consider as a prime number as a conventionally way.
#include<stdio.h>
#include<string.h>
#define max 10000000
using namespace std;
int main()
{
unsigned long long int i, j, k, m, n;
unsigned long long int* a = new unsigned long long int[max];
scanf("%ul %ul",&m,&n);
for(i = 1;i<=n;i++)
a[i]=i;
a[1] = 0;
for(i=2;(i*i)<=n;i++)
if(a[i]!=0)
for(k=2*i;k<=n;k=k+i)
if(a[k]!=0)
a[k]=0;
for(i =m;i<=n;i++)
if(a[i]!=0)
printf("%ul ",a[i]);
memset(a, 0, sizeof(a));
return 0;
}
#include<stdio.h>
#include<stdlib.h>
void prime(int );
int main(){
int x, end;
printf("Enter end of the range:\n");
scanf("%d", &end);
for(x = 2;x <= end;x++){
prime(x);
}
return 0;
}
void prime(int x){
int j, count = 1;
for(j=2;j <= x;j++){
if(x % j == 0){
count += 1;
//printf("count = %d,x = %d", count, x);
}
}
if(count == 2){
printf("\n%d\n", x);
}
}

Resources