How to find the missing number without using arrays? - c

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;
}

Related

change an integer to base 2 with arrays as output in C

#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.)

Printing pascal's triangle in C

I have to print the pascal's triangle given a certain number of levels desired. The max levels that will be asked for is 28. I am able to print the some of the rows correctly but then it starts printing negative numbers in the rest of my rows. I can't figure out why, help would be much appreciated!
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void printTriangle() {
int numLevels;
printf("Please enter how many levels of Pascal's Triangle you would like to see: ");
scanf("%d", &numLevels);
char pascalTriangle[28][28];
for (int k = 1; k <= numLevels; ++k) {
for (int i = 0; i < k; ++i) {
int val = (i == 0) || (i == k - 1) ? 1 : (pascalTriangle[k-1][i-1] + pascalTriangle[k-1][i]);
pascalTriangle[k][i] = val;
printf(" %d", val);
}
printf("\n");
}
}
int main() {
printTriangle();
}
Change char pascalTriangle[28][28]; to int pascalTriangle[28][28];. You're going over the max char value so it goes to negative.
There is no "array" type, only a collection of pointers. You can also change char to short, long, etc.
Also, change k <= numLevels to k < numLevels. This prevents the segmentation fault. To fix the logic, you have to change for(int i = 0; to for(int i = -1;
The fixed code is:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void printTriangle() {
int numLevels;
printf("Please enter how many levels of Pascal's Triangle you would like to see: ");
scanf("%d", &numLevels);
long long pascalTriangle[28][28];
for (int k = 0; k < numLevels; ++k) {
for (int i = -1; i < k; ++i) {
long long val = (i == 0) || (i == k - 1) ? 1 : (pascalTriangle[k-1][i-1] + pascalTriangle[k-1][i]);
pascalTriangle[k][i] = val;
printf(" %lld", val);
}
printf("\n");
}
}
int main() {
printTriangle();
}

Rand() not generating random variables in C

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

I have an exercise of c

My exercise is input list integer numbers from keyboard and the end of program by 0. Then print sum of array. This is my code:
#include <stdio.h>
#include <stdlib.h>
const int MAX_ITEMS = 50;
void inputIntegerNumber(int* a, int* count);
int sumOfInteger(int* n, int* count);
int main(int argc, char** argv) {
int x[MAX_ITEMS], count;
inputIntegerNumber(&x, &count);
printf("Sum of array is %d", sumOfInteger(&x, &count));
return (EXIT_SUCCESS);
}
void inputIntegerNumber(int* a, int* count ){
do{
printf("Please! input numbers: ");
scanf("%d", a);
*count++;
}while((*a != 0) && (*count != MAX_ITEMS));
}
int sumOfInteger(int* n, int* count){
int sum = 0;
for (int i = 0; i < *count; i++)
sum += *n;
return sum;
}
I don't know what's wrong with it? It doesn't give me a result same my thinks...
There are some problems like -
inputIntegerNumber(&x, &count);
printf("Sum of array is %d", sumOfInteger(&x, &count));
in both calls you pass &x but x is an array of int and your function expects int * not int (*)[]. This must have given an error atleast.
For both functions you can just pass the array x directly.
And in your function inputIntegerNumber this -
*count++;
You need to increment value of count, so it should be (*count)++. Dereference first and then increment the value.
You are doing some mistakes in your code like passing pointer to a pointer &x value(since array is basically a pointer to some memory location) and overwriting the same location again and again. In scanf("%d", a); you are overwriting the first location again and again without changing a in you input loop.You need to learn about arrays and their usage. In sumOfInteger function also you're not changing the value of n. I changed you code a bit and i was able to see desired output.
#include <stdio.h>
#include <stdlib.h>
const int MAX_ITEMS = 50;
void inputIntegerNumber(int* a, int* count);
int sumOfInteger(int* n, int* count);
int main(int argc, char** argv) {
int x[MAX_ITEMS], count = 0; // zero elements in array
inputIntegerNumber(x, &count);
printf("Sum of array is %d", sumOfInteger(x, &count));
return (EXIT_SUCCESS);
}
void inputIntegerNumber(int* a, int* count ){
int aIndex = 0;
do{
printf("Please! input numbers: ");
scanf("%d", &a[aIndex]);
aIndex++;
}while((a[aIndex-1] != 0) && (aIndex != MAX_ITEMS));
*count = aIndex;
}
int sumOfInteger(int* n, int* count){
int sum = 0;
for (int i = 0; i < *count; i++)
sum += n[i];
return sum;
}
when i run it i can see :
~/Documents/src : $ ./a.out
Please! input numbers: 1
Please! input numbers: 2
Please! input numbers: 3
Please! input numbers: 0
Sum of array is 6
You're overcomplicating things. Before you sit down to write a program, always write the general steps that must be done
Read the numbers from the command line
Convert them to ints and save them in memory
Calculate the sum
Print it
Here is the revised program
#include <stdio.h>
#include <stdlib.h> /* for strtol */
#define DIE(msg) fprintf(stderr, "%s", msg); exit(EXIT_FAILURE)
int main(int argc, char *argv[])
{
int *nums;
if (argc <= 1)
DIE("Usage: [int-list]\n");
/* skip program name */
--argc;
++argv;
nums = malloc(argc * sizeof(int));
if (!nums)
DIE("Out of mem\n");
for (int i = 0; i < argc; ++i) {
char *end;
double val = strtol(argv[i], &end, 0);
if (end == argv[i]) /* no digits detected */
DIE("Usage: [int-list]\n");
nums[i] = val;
}
printf("%d\n", add(nums, argc));
free(nums);
}
int add(int arr[], size_t n)
{
int sum = 0;
for (int i = 0; i < n; ++i)
sum += arr[i];
return sum;
}
To complete the strtol error handling is an exercise for the OP.

Check the random number by modulo and user's input

im trying to determine how many times the user has guess right the number and place of a random number.
for example, if the number is 1234 and the user's input is 7214
so he guess right only the number 2 and 4.
because of this: 1[2]3[4] == 7[2]1[4].
problem: the program throws me out after i take the user's input. im getting an error which says: "Expression: result_pointer != nullptr"
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
int hit(int num);
int strike(int num);
int rndNum(int num);
void main()
{
int num = 0;
int chosenNum;
int saveHits;
srand(time(NULL));
printf("The Random number: %d", chosenNum = rndNum(num));
printf("\nPlease enter a 4 digit number: ");
scanf("%d", num);
saveHits = hit(num, chosenNum);
printf("\nThe number of hits: %d", saveHits);
getch();
}
int rndNum(int num)
{
int rndNum = rand() % 9000 + 1000;
return rndNum;
}
int hit(int num1, int chosenNum1)
{
int i, hit1 = 0;
for (i = 0; i < 4; i++)
{
if (num1 % 10 == chosenNum1 % 10)
hit1++;
num1 /= 10;
chosenNum1 /= 10;
}
return hit1;
}
You're missing a &
scanf("%d", &num);
^

Resources