I am trying to learn how to convert ints into binary. it runs but this is the output: Enter a number: 33
New value: 16
Remainder: 1
Current VAlue: -17
Counter: 1
I appreciate any help. Thank you. Ok I am sorry my bad. The output should be: 00100001
#include <stdio.h>
int main()
{
int nv, r, num;
printf("Enter a number: ");
scanf("%d",&num);
int counter=0;
while(num>=0)
{
nv=num/2;
r=num%2;
num=-(nv+r);
counter++;
printf("New Value: %d\n",nv);
printf("Remainder: %d\n",r);
printf("Current Value: %d",num);
}
printf("Counter: %d\n",counter);
}
num=-(nv+r);
Is obviously negative, since both nv and r are positives.
I suspect you actually wanted
num = nv
or:
num -= (nv + r)
Also note that your stop condition is num >= 0 - if you do the first change, you will get an infinite loop, since when you reach num ==0, you will divide by 2, and get nv == num /2 == 0 / 2 == 0 and assign nv back to num
(*)Note that also the second change will proide infinite loop: 0 % 2 == 0 and 0 / 2 == 0, so num -= (nv + r) == 0 - (0 + 0) == 0
Is this what you were trying to accomplish?
#include <stdio.h>
int main()
{
int nv, r, num;
int counter=0;
printf("Enter a number: ");
scanf("%d",&num);
while(num>0)
{
nv=num/2;
r=num%2;
num-=(nv+r);
counter++;
printf("New Value: %d\n",nv);
printf("Remainder: %d\n",r);
printf("Current Value: %d\n",num);
}
printf("Counter: %d\n",counter);
return 0;
}
One easy way to do that is know that the machine store the number in binary. And what you need to do is only use this to print the number in binary.
int main()
{
int val=1;
int n=0;
int num;
printf("Enter a number: ");
scanf("%d",&num);
while(val <= num)
{
if(val & num) printf("bit %d is '1'\n", n);
else printf("bit %d is '0'\n", n);
n++;
val<<=1;
}
}
In this case the order is from the least significant to the most significant bit.
Related
i have a homework but i cant get the answer
I need to write a program in C...
Here is what is needed: You need to enter "n" natural number as input , and from all the natural numbers smaller than "n" , its needed to print the number which has the highest sum of devisors.
For exp: INPUT 10 , OUTPUT 8
Can anyone help me somehow?
I would really appreciate it !
i tried writing a program for finding the devisor of a number but i cant get far from here
#include <stdio.h>
int main() {
int x, i;
printf("\nInput an integer: ");
scanf("%d", &x);
printf("All the divisor of %d are: ", x);
for(i = 1; i < x; i++) {
if((x%i) == 0){
printf("\n%d", i);
}
}
}
I have implemented using function which will takes input number from user and then return the sum of divisor. hope this is one you looking for
/* function to return of sum of divisor
** input: x: integer number from user input
** return sum: sum of divisor of x
*/
int sum_of_divisor(int x)
{
int sum = 0;
for(int i = 1; i < x; i++)
{
if((x%i) == 0)
{
printf("%d\n", i);
sum = sum+i;
}
}
return sum;
}
int main() {
int x, i;
printf("\nInput an integer: ");
scanf("%d", &x);
printf("All the divisor of %d are: ", x);
printf("the sum of divisor is %d ", sum_of_divisor(x));
return 0;
}
Output:
Input an integer: 10
All the divisor of 10 are: 1
2
5
the sum of divisor is 8
After checking if i is a divisor of x, you should then store that value in another variable, for example m.
Repeat until a new divisor i is higher than that number. Add this new value to m.
#include <stdio.h>
main()
{
int i, num, sum=0; //declaration
printf("How many numbers do you want to calculate average of?\n");
scanf("%d", &num); //how many numbers are to be calculated
printf("Enter %d numbers\n", num);
int a[num]; //array to store data
for(i=1;i<=num;i++) //loop to take input
{
if(i==1) //for 1st
printf("1st value : ");
else if (i<=2) //2nd
printf("2nd value : ");
else if (i<=3) //3rd
printf("3rd value : ");
else //else print th ordinal
printf("%dth value : ", i);
scanf("%d", &a[i]);
}
for(i=1;i<=num;i++)
sum+=a[i];
float avg;
avg=sum/num;
printf("Average : %f", avg);
return 0;
}
A program to take out the average of n numbers.
Now, this code does what it should, but if the size of the array goes beyond 20, it prints 21th, 22th, 23th and so on, which is wrong. I can't think of how to fix this problem. Any help would be great. I am new to programming, so pardon my ignorance.
There isn't a standard function that does that. You can write one, or use mine:
ordinal.c
#include "ordinal.h"
#include <stdio.h>
static const char *const suffixes[4] = { "th", "st", "nd", "rd" };
enum { NUM_SUFFIXES = sizeof(suffixes) / sizeof(suffixes[0]) };
static unsigned suffix_index(unsigned n)
{
unsigned x;
x = n % 100;
if (x == 11 || x == 12 || x == 13)
x = 0;
else if ((x = x % 10) > 3)
x = 0;
return x;
}
char *fmt_ordinal(char *buffer, size_t buflen, unsigned n)
{
unsigned x = suffix_index(n);
int len = snprintf(buffer, buflen, "%u%s", n, suffixes[x]);
if (len <= 0 || (size_t)len >= buflen)
return 0;
return(buffer);
}
ordinal.h
/* returns buffer or 0 on failure (implausible unless buffer too small) */
extern char *fmt_ordinal(char *buffer, size_t buflen, unsigned n);
Some of that is overkill on its own, but the source file also contains scn_ordinal() which scans ordinal numbers with greater or lesser strictness, and the header declares it.
int main(void)
{
char buffer[15];
/* Test fmt_ordinal() */
for (unsigned i = 0; i < 35; i++)
printf("%2u => %4s\n", i, fmt_ordinal(buffer, sizeof(buffer), i));
return 0;
}
You can mod by 10 to get the last digit. Then based on that you can use "st", "nd", "rd", or "th". You'll also need special cases for 11, 12, and 13.
if ((i % 10 == 1) && (i % 100 != 11))
printf("%dst value : ", i);
else if ((i % 10 == 2) && (i % 100 != 12))
printf("%dnd value : ", i);
else if ((i % 10 == 3) && (i % 100 != 13))
printf("%drd value : ", i);
else
printf("%dth value : ", i);
I played with this a bit and this was my minimal 'lookup' except, sadly, for the expense of the modulo division. I wasn't fussed about values above 99.
if( i > 20 ) i %= 10; // Change 21-99 to 1-10.
if( i > 3 ) i = 0; // Every other one ends with "th"
// 0 1 2 3
suffix = &"th\0st\0nd\0rd"[ i * 3 ]; // Acknowledge 3byte regions.
You can use 'suffix' as a pointer to a normal null terminated string.
It is okay to be a beginner, no need to apologize. You can solve your problem using a combination of a SWITCH statement and the modulus operator (%). The modulus operator takes two numbers (n1 % n2) and returns the remainder when n1 is divided by n2.
You will want to construct an array of ordinals, like this:
char *ordinalList[] = { "st", "nd", "rd", "th" };
This will allow you to simply reference this array to append the correct ordinal to a number. The next step is to create an algorithm to determine which array index should be referenced. To do this, you can make a new function and call it in your "main".
char *determineOrdinal (char **ordinalList, int numValue)
{
if (3 < numValue && numValue < 21)
return ordinals[3];
switch (numValue % 10) {
case 1 : return ordinalList[0];
break;
case 2 : return ordinalList[1];
break;
case 3 : return ordinalList[2];
break;
default: return ordinalList[3];
break;
}
You can pass a number into this function as the numValue argument. Your "main" function might look something like this:
#include <stdio.h>
int main(void)
{
char *ordinalList[] = { "st", "nd", "rd", "th" };
char *currentdOrdinal;
int i, num, sum=0; //declaration
printf("How many numbers do you want to calculate average of?\n");
scanf("%d", &num); //how many numbers are to be calculated
printf("Enter %d numbers\n", num);
int a[num]; //array to store data
for(i=1;i<=num;i++) //loop to take input
{
currentdOrdinal = determineOrdinal (ordinalList, i)
printf("%d%s value : ", i, currentdOrdinal);
scanf("%d", &a[i]);
}
for(i=1;i<=num;i++)
sum+=a[i];
float avg;
avg=sum/num;
printf("Average : %f", avg);
return 0;
}
I think that code should work for you. I hope this helps.
First I have to input N, N becomes the first number to be checked.
Input: 79
Output should be: 537.70.
int sum=0;
while(1)
{
scanf("%d", &n);
if(n>=10 && n<80)
{
break;
}
printf("New output:\n");
}
for(i=n;i<=1000;i++)
{
if(i%2==0 && i%6!=0 && i%17!=0)
{
sum+=i;
}
I didnt put (float)sum/N to get average because I'm doing something wrong with sum.
More input output:
Input: 10 Output: 505.21
Input: 44 Output: 521.18
As well as keeping a 'running sum', you also need to keep a count of how many numbers were used, so you can properly calculate the average:
#include <stdio.h>
int main(void)
{
int n;
printf("Enter start number: ");
scanf("%d", &n);
int sum = 0, count = 0;
for (int i = n; i <= 1000; ++i) {
if (!(i % 2) && (i % 6) && (i % 17)) {
sum += i;
++count;
}
}
printf("Average is: %.2f\n", (double)sum / (double)count);
return 0;
}
Input: 79
Output should be: 537.70.
Are you sure about this value? I get 538.70 - but I get the given values for the other test cases you cite.
I have to write a program in C that will take a base b from the user (assuming b is between 2 and 10), a natural number n and then n numbers that represent the digits of some number m in base b. The program should print out what decimal number m was input. For example, if you put b=5 and n=4 and then the numbers 3 ,4, 2 and 1 the program should output 486 because m=3*5^3+4*5^2+2*5^1+1*5^0=486
Note: You can assume that the digits will be the numbers between 0 and b-1.
So here's what I've done:
#include<stdio.h>
#include<math.h>
int main(void) {
int x,n,b,k=0,num=0,i,j;
scanf("%d", &b);
scanf("%d", &n);
for(i=1; i<=n; i++) {
scanf("%d", &x);
for(j=1; j<b; j++){
if(j>k){
num=num+x*(pow(b,n-j));
k=j;
break;
}
}
}
printf("m=%d", num);
return 0;
}
Can you tell me why this doesn't work for the numbers given in the example above? It outputs 485 instead of 486, while if I take for example b=7, n=3 and then numbers 5, 6 and 1, I get the correct solution m=288.
I suggest checking the return value of scanf(), Something like this is the right idea:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int
main(int argc, char *argv[]) {
int base, n, i, x, sum = 0, power;
printf("Enter base: ");
if (scanf("%d", &base) != 1) {
printf("Invalid base.\n");
exit(EXIT_FAILURE);
}
printf("Enter n: ");
if (scanf("%d", &n) != 1) {
printf("Invalid n.\n");
exit(EXIT_FAILURE);
}
power = n-1;
printf("Enter numbers: ");
for (i = 0; i < n; i++) {
if (scanf("%d", &x) != 1) {
printf("Invalid value.\n");
exit(EXIT_FAILURE);
}
sum += x * pow(base, power);
power--;
}
printf("Sum = %d\n", sum);
return 0;
}
Input:
Enter base: 5
Enter n: 4
Enter numbers: 3 4 2 1
Output:
Sum = 486
You need some small change to your logic.
#include <stdio.h>
#include <math.h>
int main(void) {
int x, n, b, num = 0, i;
scanf("%d", &b);
scanf("%d", &n);
for (i = 1; i <= n; i++) {
scanf("%d", &x);
num += x * pow(b, n - i);
}
printf("m=%d", num);
return 0;
}
Test
gcc -Wall main.c -lm
$ ./a.out
5
4
3
4
2
1
m=486
Test 2
./a.out
7
3
5
6
1
m=288
OK, so given a binary number, we can output a decimal number very easily. Just printf("%d%\n", x);
Next job is to convert a number given digits and base into a binary (machine representation) number.
int basetointeger(const char *digits, int b)
{
assert(b >= 2 && b <= 10);
// code here
return answer;
}
Now hook it all up to main
int main(void)
{
int x;
int base;
char digits[64]; // give more digits than we need, we're not worrying about oveflow yet
/* enter base *?
code here
/* enter digits */
code here
x = basetointger(digits, base);
printf("Number in decimal is %d\n, x);
}
Is it 1 & 0 are prime numbers ? because when i Input 1 & 0 it says that it is a PRIME
#include <stdio.h>
int main(){
int num, i,y = 0;
printf("Enter a Number: ");
scanf("%d",&num);
for(i = 2; i <= num /2; ++i){
if(num % i == 0){
y=1;
}
}
printf("the number %d is a ",num);
if (y == 0){
printf("(PRIME)");
}
if(num % 2 == 0){
printf("(EVEN)");
}else
printf("(ODD)");
printf(" Number.");
}
can anybody help me with my code
No, neither 0 nor 1 are considered to be prime numbers, that is, the lowest prime number is 2. You need to change the code into, for instance:
if (y == 0 && n >= 2)
this covers both 0 and 1 along with negative integers (thanks to #MikeCAT)