I would like to write a program which can find all prime numbers between two numbers in t test cases. But my program had crashed when I run it.
Please, could anyone help me?
My code:
#include <stdio.h>
#include <malloc.h>
#include <math.h>
void print(int a,int b)
{
int *p,i;
int x;
p = (int *) malloc (sizeof(int)*(b-a));
for(i=0;i<(b-a);i++) p[i]=a+i;
for(i=0;i<(b-a)/2;i++)
{
if(p[i]!=0)
{
if(p[i]%i==0) p[i]=0;
}
}
for(i=0;i<=(b-a);i++) if(p[i]!=0) printf("%d ",p[i]);
free(p);
}
int main(void)
{
int t,i,m,n;
scanf("%d",&t);
for(i=0;i<t;i++)
{
scanf("%d %d",&m,&n);
print(m,n);
}
return 0;
}
The problem is stumbling on allocating memory in a range, allocating one element too few (should have been malloc (sizeof(int)*(b-a+1));) and then not sticking to indexing the memory allocated. This could be so much simpler: no arrays needed - if a number has a divisor, there is no need to check any other divisors.
Sometimes it is easier to side-step the problems than struggle with them.
#include <stdio.h>
#include <math.h>
int prime(int n)
{
int s, i;
if (n == 1 || n == 2)
return 1;
if (n % 2 == 0) // no even numbers
return 0;
s = (int)sqrt(n); // limit the loop
for (i=3; i<=s; i+=2) // odd numbers only
if (n % i == 0)
return 0;
return 1;
}
void print(int a, int b)
{
int n;
for (n=a; n<=b; n++)
if (prime (n))
printf("%d ", n);
printf("\n");
}
int main(void)
{
int t, i, m, n;
printf("Input number of ranges to test: ");
scanf("%d", &t);
for(i=0; i<t; i++)
{
printf("Input bottom and top of range: ");
scanf("%d %d", &m, &n);
print(m, n);
}
return 0;
}
You messed up the termination of the for-loops. You allocated b-a bytes but you are iterating over b-a+1 items...
for(i=0;i<=(b-a);i++) p[i]=a+i;
needs to be a i<(b-a) or else you have a segfault (in both loops).
Also as BLUEPIX pointed out:
for(i=0;i<b/2;i++)
needs to be i<(b-a)/2 for iterating over half the intervall.
p[i]%i
Division by zero in the first iteration i==0.
After this the programm should terminate without an error.
Related
#include<stdio.h>
#include<math.h>
int perfectSquare(int arr[], int n);
int main()
{
int n , arr[n];
printf("number of elements to store in array");
scanf("%d", &n);
for (int i = 0; i < n; i++)
{
printf("enter %d number", i+1);
scanf("%d", &arr[i]);
}
perfectSquare(arr, n);
return 0;
}
int perfectSquare(int arr[], int n)
{
int i;
int a;
for (i = 0; i <= n; i++) //i=4 arr[4]==9 //arr[1]=2 i=1
{
a=sqrt((double)arr[i]); //a=3 //a=1.454=1
if ( a*a==arr[i] ) //a==3*3==9==arr[4] //a*a=1!=arr[2]
printf("%d", arr[i]);
}
}
I am new to coding and I am currently learning c. I came up with this code but it doesn't work can someone tell me what is the problem with this code?
There are a couple of issues with this exercise, but generally you're on the right track. Here, a version of your example with some possible corrections:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void perfect_square(int arr[], int n);
int main(void)
{
int i, n, *arr;
printf("number of elements to store in array: ");
scanf("%d", &n);
if (n <= 0)
return -1;
arr = malloc(n*sizeof(int));
if (arr == NULL)
return -2;
for (i = 0; i < n; i++) {
printf("enter number %d: ", i+1);
scanf("%d", &arr[i]);
}
perfect_square(arr, n);
free(arr);
arr = NULL;
return 0;
}
void perfect_square(int arr[], int n)
{
int i, a;
for (i = 0; i < n; i++) {
a = (int)sqrt((double)arr[i]);
if (a*a == arr[i])
printf("%d ", arr[i]);
}
}
Some hints:
Arrays, that have an unknown size at compile time are usually allocated with malloc(), and must be deallocated again with free() (see also: alloca(), calloc(), realloc()). (In "more recent versions of C" there is also the possibility to use variable length arrays, but those can limit the portability of the code).
Always make sure to check the start value and end condition of for-loops, to prevent out of bound errors.
And try to consistently format the code, use good names and nice indentation to improve read-, maintain-, reusablilty.
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;
}
How to read space-separated integers representing the array's elements and sum them up in C?
I used the below code but it reads all the elements in a new line:
#include <math.h>
#include <stdio.h>
int main() {
int i = 0, N, sum = 0, ar[i];
scanf("%d" , &N);
for (i = 0; i < N; i++) {
scanf("%d", &ar[i]);
}
for (i = 0; i < N; i++) {
sum = sum + ar[i];
}
printf("%d\n", sum);
return 0;
}
Your array ar is defined with a size of 0: the code invokes undefined behavior if the user enters a non zero number for the number of items.
Furthermore, you should check the return value of scanf(): if the user enters something not recognized as a number, your program will invoke undefined behavior instead of failing gracefully.
Here is a corrected version:
#include <stdio.h>
int main(void) {
int i, N, sum;
if (scanf("%d", &N) != 1 || N <= 0) {
fprintf(stderr, "invalid number\n");
return 1;
}
int ar[N];
for (i = 0; i < N; i++) {
if (scanf("%d", &ar[i]) != 1) {
fprintf(stderr, "invalid or missing number for entry %d\n", i);
return 1;
}
}
sum = 0;
for (i = 0; i < N; i++) {
sum += ar[i];
}
printf("%d\n", sum);
return 0;
}
Note that the program will still fail for a sufficiently large value of N as there is no standard way to check if you are allocating too much data with automatic storage. It will invoke undefined behavior (aka stack overflow).
You should allocate the array with malloc() to avoid this:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int i, N, sum;
int *ar;
if (scanf("%d", &N) != 1 || N <= 0) {
fprintf(stderr, "invalid number\n");
return 1;
}
ar = malloc(sizeof(*ar) * N);
if (ar == NULL) {
fprintf(stderr, "cannot allocate array for %d items\n", N);
return 1;
}
for (i = 0; i < N; i++) {
if (scanf("%d", &ar[i]) != 1) {
fprintf(stderr, "invalid or missing number for entry %d\n", i);
return 1;
}
}
sum = 0;
for (i = 0; i < N; i++) {
sum += ar[i];
}
printf("%d\n", sum);
free(ar);
return 0;
}
Finally, there is still a possibility for undefined behavior if the sum of the numbers exceeds the range of type int. Very few programmers care to detect such errors, but it can be done this way:
#include <limits.h>
...
sum = 0;
for (i = 0; i < N; i++) {
if ((sum >= 0 && arr[i] > INT_MAX - sum)
|| (sum < 0 && arr[i] < INT_MIN - sum)) {
fprintf(stderr, "integer overflow for entry %d\n", i);
return 1;
}
sum += ar[i];
}
#include <math.h>
#include <stdio.h>
int main()
{
int i=0,N,sum=0;
scanf("%d" ,&N);
int ar[N];
for(i=0; i<N; i++)
scanf("%d",&ar[i]);
for(i=0; i<N; i++)
sum=sum+ar[i];
printf("%d\n", sum);
return 0;
}
This should be the code.
You have initially declared the array of size 0 (because i=0).
Even though you declared the array of size 0, when I ran it on my machine, it actually executed successfully with the correct output.
This is generally due to undefined behavior which means that we can only guess the output when the code is correct. If the code has undefined behavior, then it can do whatever it wants (and in the worst case the code will execute successfully giving the impression that it's actually correct).
Declaring a Variable Size Array (VLA) is optional in C11 standard. Thus, it depends on the implementation of the compiler whether it will support VLA or not. As pointed out by #DavidBowling in comments, if the compiler does support, then declaring a VLA of size 0 can invoke undefined behavior (which you should avoid in all cases). If it doesn't support, then this will simply give a compilation error and you'll have to declare the array size as some integer constant (example, int arr[100];).
#include <math.h>
#include <stdio.h>
int main()
{
int i=0,N,sum=0;
scanf("%d" ,&N);
int ar[N];
for(i=0; i<N; i++)
{
scanf("%d",&ar[i]);
}
for(i=0; i<N; i++)
{
sum=sum+ar[i];
}
printf("%d\n", sum);
return 0;
}
You should declare the array after accepting the value of N.
#include <math.h>
#include <stdio.h>
int main()
{
int i=0,N,sum=0;
scanf("%d" ,&N);
int ar[N];
for(i=0; i<N; i++)
{
scanf("%d",&ar[i]);
sum=sum+ar[i];
}
printf("%d\n", sum);
return 0;
}
As this is a very simple question I'll expand it a bit to include some good programming practices.
1. Analyze the problem
We have to complete two tasks here:
Read and store the numbers to array.
Sum the array elements.
Of course you can both read and calculate the same time, but we ❤ the SoC design principle. This will help you later with bigger programs.
2. Create the program structure
In this state we have to consider what function to use, as we already solved the data structure problem (we use array).
Of course, we always can put the whole procedure in main function but this would break the SoC principle.
The main principle here is:
I create a function for a separate procedure.
So we'll have to build two functions. Let's consider the following example:
ReadArrayData will be used to read the data from the standard input (your keyboard in other words) to array. But what will declare as parameters? We surely have to pass the array and the array size. The return type of this function will be void (we don't have to return something).
Keep in mind that if you pass array to function you can manipulate it as you please and keep these changes in your main program. This is because the arrays are passed always by reference to a function.
In the end this will be your function prototype:
void ReadArrayData(int arraySize, int array[]);
CalculateArraySum will be used to calculate the sum of the array elements. The function prototype will be the same as for ReadArrayData with the difference that the returning type will be int (we return the sum).
int CalculateArraySum(int arraySize, int array[]);
3. Write your program
#include <stdio.h>
void ReadArrayData(int arraySize, int array[]);
int CalculateArraySum(int arraySize, int array[]);
int main(void) {
int N;
printf("Give the array size: ");
scanf("%d", &N);
int array[N];
ReadArrayData(N, array);
int sumOfArrayElements = CalculateArraySum(N, array);
printf("The sum of array elements is %d.\n", sumOfArrayElements);
return 0;
}
void ReadArrayData(int arraySize, int array[]) {
printf("Give %d elements: ", arraySize);
for (int i = 0; i < arraySize; ++i) {
scanf("%d", &array[i]);
}
}
int CalculateArraySum(int arraySize, int array[]) {
int sum = 0;
for (int i = 0; i < arraySize; ++i) {
sum += array[i];
}
return sum;
}
I know this was a large scaled answer, but I saw you are new to computer programing. I just wanted to present you the main functionality to solve all kinds of problems. This was just a small introduction. In the end, you have to remember what steps we take to solve a problem. With time and as you solve many problems you will learn many many other things.
I ask the user to input two integers, n and x. After that, I need to ask them for a value for the a variable n times. I need to create a new a variable for each value. How do I do it? I have absolutely no idea.
Also, I need to do it in one line, so the input will be, for example, 50 30 21, not
50
30
21
Thanks.
#include <stdio.h>
int main (void) {
int a, n, x;
int i = 0;
scanf ("%d%d", &n, &x);
scanf ("%d", &a); /* what should I do here? */
}
Try this:
int arr[100]; // static allocation but you can also allocate the dynamically memory
printf("Enter the number for how many time repeat scanf()\n");
scanf("%d",&n);
for (int i = 0; i < n; i++)
{
scanf("%d",&arr[i]);
}
Try the below code:
#include <stdio.h>
int main (void) {
int a[100];
int n, x;
int i = 0;
scanf ("%d%d", &n, &x);//n cannot be greater than 100 in this case.
for(i = 0; i < n; i++)
{
scanf ("%d", &a[i]);
}
return 0;
}
Using dynamic memory:
#include <stdio.h>
#include <stdlib.h>
int main (void) {
int *a = NULL;
int n, x, i;
scanf("%d%d", &n, &x);
if (n <= 0) {
fprintf(stderr, "n must be > 0\n");
return 1;
}
a = malloc(n * sizeof(int));
if (a == NULL) {
fprintf(stderr, "failed to allocate memory for "
"%d integers\n", n);
return 1;
}
/* reading the user input */
for (i = 0; i < n; i++) {
scanf ("%d", &a[i]);
}
/* usage */
for (i = 0; i < n; i++) {
printf("a[%d] = %d\n", i, a[i]);
}
printf("x = %d\n", x);
free(a);
return 0;
}
After that, I need to ask them for a value for the a variable n times.
High Level Programming Languages and even Assembly Language (Conditional/Unconditional Jump) provide Loop constructs to a programmer. In computer programming, a loop is a sequence of instructions that is continually repeated until a certain condition is reached. In C/C++, we have for, while, do while loop constructs.
So, i order to ask a user for a value for n times, you can use for loop in your program. I have given an example below:
#include <stdio.h>
#define MAX_ARR_LEN 100
int main (void)
{
int a[MAX_ARR_LEN];
int n, x;
int i = 0;
scanf ("%d%d", &n, &x);
if (n > MAX_ARR_LEN) {
printf("You can't enter more than - %d\n", MAX_ARR_LEN);
return -1;
}
for(i = 0; i < n; i++) {
scanf ("%d", &a[i]);
}
return 0;
}
When you do scanf, it takes the input until the space character, which is a delimiter. You do not need to specify anything extra for that.
If you do not need to use the value of n again, you could use this code.
#include <stdio.h>
#include <stdlib.h>
int main (void) {
int n, x, i;
scanf ("%d%d", &n, &x);
int *a = (int *) malloc (n * sizeof(int)); //This will allocate 'n' integer sized memory for 'a'
for(i = 0; i < n; i++) {
scanf ("%d", &a[i]);
}
}
I've been stuck on this problem for ages now and don't seem to know how to complete this program. I am a beginner in programming so I only know C. I will admit this is for an assignment and I am not looking for the answer but I would really appreciate a little help with the problem. This is what I have:
#include <stdio.h>
#include <math.h>
void main()
{
int low, high, n, count,i;
scanf ("%d %d",&low, &high);
count=0;
n=0;
if (low<=3)
count=count+1;
while (n<low)
{
n=n+6;
}
while (n<high)
{
i=1;
while (i<sqrt(n+1))
{
i=i+2;
if ((n-1)%i==0 || (n+1)%i==0)
continue;
else
count=count+1;
}
n=n+6;
}
printf("the number of twin primes between %d and %d are %d",low, high, count);
}
Am I using while loops wrong and/or the if statements? I haven't been taught to use for loops so I can't use those. I also have to use the fact that every twin prime besides {3,5} follow the formula 6+/-1.
Thank you for helping me.
The following program work correctly.
#include <stdio.h>
#include <math.h>
int main(int argc, char *argv[])
{
int low, high, n, count, i;
scanf ("%d %d", &low, &high);
count = 0;
n = 0;
if (low <= 3)
count++;
while (n<low)
n += 6;
while (n < high) {
i = 1;
int flag = 0;
while (i * i < n + 1) {
i++;
if ((n - 1) % i == 0 || (n + 1) % i == 0)
flag = 1;
}
if (!flag)
count++;
n += 6;
}
printf("the number of twin primes between %d and %d are %d", low, high, count);
}
as you can see you need just something like flag for your prime detection phase.