#include <stdio.h>
#include<math.h>
int main(void){
int Num;
int i;
int N;
int x = 0;
int a[x];
scanf("%d", &Num);
N = Num;
for(i = 0; i < Num; i++)
{if (Num%2 == 0)
{a[i] = 0;}
else
{a[i] = 1;}
Num = Num/2;
}printf("%d in base 2 is %d", N, a[x]);
return 0;
}
program should convert an integer Num to base 2 eg 17 to 10001.
ideally using an array as the output
the remainder of the division of Num by 2 should be the last number in the output
then number is divided by 2 and the process repeats with the second output becoming the 2nd last output of the array
Sorry if this question is worded badly
Any help is appreciated
Thanks
#include <stdio.h>
#include <math.h>
int main(void){
int Num;
int N;
scanf("%d", &Num);
int x = floor(log2(Num)) +1;
int a[x];
N = Num;
for(size_t i=0;i<x;i++){
if(Num%2 == 0){
a[i]=0;
}else{
a[i]=1;
}
Num /= 2;
}
printf("%d in base 2 is ",N);
for(int i=x-1; i>=0;i--){
printf("%d",a[i]);
}
return 0;
}
I think the above code works fine for what you need (although it's not the best way to code this program).
In line 7 of your code, you defined x as 0; so, in line 8, the length of your array is 0 – and that's not what we need.
At the end, when you want to output the result, you only output the xth element of your array. Instead, we want to output every element that we stored. (I used i-- because, if I did not, the binary of Num would be reversed.)
Related
I have to find a missing number in a sequence of numbers.
The input consists of a positive integer n, between 0 and 35000, and n unique numbers with range [0..n]. (So this range contains n+1 numbers).
I already tried some things with sum={n*(n+1)}/2 and then misNum=sum-SumOfNum;, but I couldn't find a way to make this work.
I wrote some code, but not with the examples I mentioned before. Obviously, this code is not complete, but I don't know how to make it complete.
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char *v[]) {
int length;
int num;
scanf("%d", &length);
/*scanf(???)*/
int goal=length;
int i;
for(i=0; i!=length; i++){
goal=goal+i-num[i];
};
return goal;
}
Input and outcome should be:
Input: 2 "enter" 0 2. Output: 1
Input: 3 "enter" 0 3 1. Output: 2
Sum of all numbers from 0 to n is
n(a1+an)/2 = (in your case a1 = 0 and an = n+1) n*(n+1)/2
so the missing number is n*(n+1)/2 - (sum of input numbers after the length)
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char* v[]) {
int length;
int i = 0;
int sum = 0;
scanf_s("%d", &length);
// calculate arithmetic series sum
auto series_sum = ((length + 1) * (length)) / 2;
while (i < length)
{
int next;
scanf_s("%d", &next);
sum += next;
++i;
}
printf("missing num is %d ", series_sum - sum);
}
You have n number of integers to be scanned. Use mathematical equation to calculate the sum of first n+1 natural numbers. Then run a loop for n times and then run a loop to add all the n numbers scanned. Then subtract this sum with the sum of n+1 natural number. Result will be the missing number.
The calculation from the question is also correct and can be made to work with a few modifications.
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char *v[]) {
int length;
int num;
// printf("enter maximum number: ");
scanf("%d", &length);
int goal=length;
int i;
for(i=0; i!=length; i++){
// printf("number[%d]: ", i);
if(scanf("%d", &num) != 1) {
fprintf(stderr, "invalid input\n");
return 1;
}
if((num < 0) || (num > length)) {
fprintf(stderr, "invalid number %d\n", num);
return 2;
}
goal=goal+i-num;
};
// printf("missing number: ");
printf("%d\n", goal);
return 0;
}
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;
}
I've been trying to apply all advices found in this site but none seems to be working.
For the first part of the code I need to fill an array with random numbers (0 or 1) to simulate an epidemic spreading, but the array obtained is not the desired one at all... this is the code I wrote:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(int argc, char **argv)
{
int N, BC, t, T, i, v[N];
float b, g, p, r;
/*Variable values initialization*/
printf("Enter infection probability:\n");
scanf("%f", &b);
printf("Enter the number of individuals:\n");
scanf("%d", &N);
printf("Enter the number of time steps:\n");
scanf("%d", &T);
printf("Periodic boundary contitions? (Y:1 / N:0)\n");
scanf("%d", &BC);
/*First set of individuals*/
srand(time(NULL));
for(i = 0; i < N; i++){
v[i] = (rand()/RAND_MAX);
}
/*Check if array properly initialized*/
printf("Initial array:\n" );
for(i = 0; i < N; i++){
printf("%d-", v[i]);
}
The outcome I expected for the array was something like: 1-0-1-1-0-0-0-..., but I always get the following one:
Initial array:
0-0-2-15-0-0-0-0-0-0-
What am I doing wrong?
Thanks a million!
You should declare v[N] after
printf("Enter the number of individuals:\n");
scanf("%d", &N);
otherwise its size will be random since N isn't initialized when the memory allocated for v[] based on N is set.
If you want just 0 or 1 you should use a modulo:
srand(time(NULL));
for(i = 0; i < N; i++){
v[i] = (rand() % 2);
}
all the even values generated by rand will become 0 and all the odd values will become 1
Just learning C and I'm trying to understand how I get the sum of numbers using 2 functions but the results is incorrect.
I'm trying to ask the user for 10 numbers which are stored in an array in function main. The sum is then calculated in a separate function and then displayed in main.
Here is my original code without multiple functions that works:
int main()
{
int n[10];
int index;
int sum_n = 0;
int largest_n;
int smallest_n;
int *p;
p = &n[10];
int a;
printf("Enter 10 Integers\n");
for (index = 0; index < 10; index ++){
scanf("%d", &n[index] );
sum_n += n[index];
}
printf("The Sum of numbers is %d\n", sum_n);
}
Here is me trying to convert it to functions but the sum isn't working out:
int calculations (int);
int main()
{
int n[10];
int index;
int largest_n;
int smallest_n;
int *p;
p = &n[10];
int a;
printf("Enter 10 Integers\n");
for (index = 0; index < 10; index ++){
scanf("%d", &n[index] );
}
if (n[index] = 10){
//sum_n += n[index];
printf("The Sum of numbers is %d\n",calculations(n[index]));
}
&
int calculations (int num){
int sum_n = 0;
sum_n += num;
return sum_n;
}
When I run the second program using functions for numbers 1 to 10 I'm getting:
I'm either doing something blatantly wrong or not understanding what I'm doing at all.
every time you call a function the variables declared within a function are reset.
in case you want a variable that won't be reset every time you call a function you can simply make it static.
moreover you are passing and argument n[10] but your array stores number from n[0] to n[9] . And if you want sum of all ten numbers then you have to call calculation function for every number or you could just pass whole array. here is modified code.
#include<stdio.h>
int calculations (int);
int main()
{
int n[10];
int index;
int largest_n;
int smallest_n;
int *p;
p = &n[10];
int a;
int ans=0;
printf("Enter 10 Integers\n");
for (index = 0; index < 10; index ++){
scanf("%d",&n[index]);
ans = calculations(n[index]);
}
printf("The Sum of numbers is %d\n",ans);
}
int calculations (int num){
static int sum_n;
sum_n += num;
return sum_n;
}
First you don't need array for sum in this code, Second always remember to check what returned by scanf.The code is very simple.
first part with main
int main()
{
int n;
int sum=0;
printf("Enter 10 Integers\n");
for (int index = 0; index < 10; index ++){
if(scanf("%d", &n))
sum+=n;
}
printf("The Sum of numbers is %d\n",sum);//calculations(n));
}
Second using function calculation
int sum=0;
void calculation(int num){
sum+= num;
}
int main()
{
int n;
printf("Enter 10 Integers\n");
for (int index = 0; index < 10; index ++){
if(scanf("%d", &n))
calculation(n);
}
printf("The Sum of numbers is %d\n",sum);//calculations(n));
}
Your function calculations() simply returns its parameter (0 + num is simply num).
The statement
int sum_n = 0;
in it resets sum_n to 0 every time of calling it.
Move this statement out of it - directly into main() function (and before calling calculations()).
Corrections mentioned in comments below.
int calculations (int *num){ //Should be a pointer or array eg. int num[] as you want to pass an array to this function
int sum_n = 0;
int i;
//Create loop here to iterate over array and sum elements
for(i=0; i<sizeof(num)/sizeof(int); i++)
sum_n+=num[i];
return sum_n;
}
And
if (n[index] = 10){ //This is logically incorrect. This should be if(index==10).
// n[index]=10 will assign 10 to a[10] and if will still pass as if(10) is true but make a note of it. Don't use assignment operator inside if, you need comparison operator `==`
printf("The Sum of numbers is %d\n",calculations(n[index])); //You should call calculations like this -> calculations(n). You should pass whole array not just an element.
}
My code is below, this is my first programming course so expect a possibly stupid mistake.
Basically I am trying to get the min/max and the position number of them. However, my max works correctly up until 6 numbers are generated and I can't seem to understand why.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int n, r, x, i;
int max, min;
int num[0];
printf("Enter an integer");
scanf("%d", &n);
x = n;
printf("\n Pos | Val");
for(n=0; n<x; n++)
{
r = ( rand()%1000 ) + 1;
printf("\n %3d | %3d", n+1, r);
}
max=num[0];
i=0;
while(i<x) // while loop determing the biggest number
{
if(num[i]>max)
{
max=num[i];
}
i++;
}
printf("\nMax : %d",max); // biggest number
return 0;
}
There are actually several places that needs improvement in your code.
Firstly, it is invalid to declare an array of size 0 in your code int num[0];, so I'm not sure why your code work with a n up to 6.
Secondly, as you may learn very soon, indentation is very important while programming so that the code is better to understand and maintain in the future. Furthermore, while C is not a language that requires indentation (and that is considered one of its strengths) many common languages such as Python that rely on whitespace to differentiate functions do need careful management of indentation.
Third, RAND_MAX is not a multiple of 1000 so you would not obtain equal probability in your program. A srand function call is also recommended.
A possible implementation of your intended program (still ugly):
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAXN 1000
int main(void) {
int n, r, i;
int pos = 0;
int max;
int num[MAXN];
printf("Enter an integer");
scanf("%d", &n);
srand(time(0));
printf("\n Pos | Val");
for (i = 0; i<n; i++)
{
r = (int)(((double)rand() / (RAND_MAX + 1)) * 1000) + 1;
printf("\n %3d | %3d", i + 1, r);
num[i] = r;
}
max = num[0];
i = 0;
for (i = 1; i < n; i++)
{
if (num[i] > max)
{
max = num[i];
pos = i;
}
}
printf("\nMax : %d | Pos : %d", max, pos); // biggest number
//while (1);
return 0;
}
As far as my tests, this piece works well
As already identified by numerous answers and comments, your primary problem is your array. Standard C doesn't allow array sizes of zero. GCC does unless you tell it to complain.
However, all the other answers continue to blithely use the array. For the problem stated, there's no need for an array at all. Also, the question text mentions 'minimum' as well as 'maximum', and 'position' as well as 'value' — though the code shown reports neither minimum nor position. Clearly, if this is just a preliminary phase before using the data for some other work, then you probably do need to save the data in an array. You can then decide whether to use a C99 (or later) VLA — variable length array — or whether to use dynamic memory allocation with malloc() et al, remembering to free the allocated space with free().
Here's a simple revised program that doesn't use an array and does manage minimum and maximum as well as reporting positions. It deliberately changes the range of values to 0..999 so that there are never 4-digit numbers to throw the presentation off. You can decide what to do if you absolutely must used 1-based counting and values in the range 1..1000. (Using + 1 in selected locations is one part of the answer; deciding to replace %3d with either %d or %4d is probably the rest of the answer).
This code uses the time as a seed value for the random numbers, and it reports that seed value. If the program was going to be used seriously, I'd make it accept optional arguments, one of which would be the seed, so that previous runs can be recreated. I'd probably make it accept an argument for the number of random values to be generated too.
The code validates that a number was entered and validates that the number falls in the range 1..999, bailing out with an error message written to standard error if the value is not acceptable. Note that the error message diagnoses what is valid — there is nothing more frustrating than to be told that something is invalid but not why and what you need to do to fix it (and often, it helps to show what the program read — it might not be what the user thought the program would read).
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
int n;
printf("Enter number of random values to test: ");
if (scanf("%d", &n) != 1 || n <= 0 || n >= 1000)
{
fprintf(stderr, "Didn't read a valid number in the range 1..999\n");
return 1;
}
unsigned seed = time(0);
srand(seed);
printf("Seed: %u\n", seed);
int minval = 0;
int maxval = 0;
int minidx = 0;
int maxidx = 0;
printf("\n Pos | Val\n");
for (int i = 0; i < n; i++)
{
int r = (rand() % 1000);
printf(" %3d | %3d\n", i, r);
if (i == 0)
{
minval = r;
maxval = r;
minidx = i;
maxidx = i;
}
else if (r > maxval)
{
maxval = r;
maxidx = i;
}
else if (r < minval)
{
minval = r;
minidx = i;
}
}
printf("Minimum value was %3d at index %3d\n", minval, minidx);
printf("Maximum value was %3d at index %3d\n", maxval, maxidx);
return 0;
}
Example run (program mnmx67 compiled from mnmx67.c):
$ mnmx67
Enter number of random values to test: 10
Seed: 1503763592
Pos | Val
0 | 201
1 | 216
2 | 85
3 | 793
4 | 382
5 | 780
6 | 341
7 | 661
8 | 75
9 | 266
Minimum value was 75 at index 8
Maximum value was 793 at index 3
$
You did not store your random numbers in num, also You need to have some space to store these numbers. Try this for size, i commented my changes
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int n, r, x, i;
int max, min;
int * num; // ++++++++ pointer to array
printf("Enter an integer");
scanf("%d", &n);
x = n;
num = malloc(x * sizeof(int)); // ++++++++++ allocate memory
printf("\n Pos | Val");
for(n=0; n<x; n++)
{
r = ( rand()%1000 ) + 1;
printf("\n %3d | %3d", n+1, r);
num[n] = r; // +++++++++ store your number
}
max=num[0];
i=0;
while(i<x) // while loop determing the biggest number
{
if(num[i]>max)
{
max=num[i];
}
i++;
}
printf("\nMax : %d",max); // biggest number
free(num); // +++++++++ free memory
return 0;
}
Your first mistake is that the array's dimension is zero. You need to set a size for the array.
I would do this by splitting the code into three additional functions: one to generate the numbers, and two others to find the min and max.
int *gennums(size_t n)
{
int *nums;
size_t i;
if ((nums = malloc(n * sizeof (int))) != NULL) {
for (i = 0; i < n; ++i)
nums[i] = rand() % 1000;
return nums; // caller must free
}
return NULL;
}
int min(const int *arr, size_t n)
{
assert(n > 0);
int m = arr[0];
size_t i;
for (i = 0; i < n; ++i)
if (arr[i] < m)
m = arr[i];
return m;
}
int max(const int *arr, size_t n)
{
assert(n > 0);
int m = arr[0];
size_t i;
for (i = 0; i < n; ++i)
if (arr[i] > m)
m = arr[i];
return m;
}
Here int num[0];
You are not storing your random numbers in this array.Searching in that is meaning less.
Also size of your array should be at-least equal to n