I have a function that takes an array a[] and its length n. I must calculate the sum of the numbers inside the array. I wrote this recursive function:
int somma(int a[], int n)
{
if (n == 0) { return 0; }
else {return a[n] + somma(a, n-1);}
}
And I call it in my main() in this way:
int main() {
int array[5], ris;
printf("Type the numbers of the array: \n");
for(int i=0; i<4; i++)
{
scanf("%d", &array[i]);
}
printf("\nThe sum is: %d.", somma(array,4));
getch();
return 0;
}
If the array contains array = [2; 4; 7; 5] the printf must show 18 (2+4+7+5). By the way the function returns me 88, can you help me?
I am using wxDevC++.
You are only reading the first four values in the array. array[4] contains garbage value
for(int i=0; i<5; i++) //change to 5
{
scanf("%d", &array[i]);
}
Your somma function is also wrong. It will always add 0 for arr[0].
if (n == -1) { return 0; } //change to this
You may try this:-
for(int i=0; i<=4; i++)
{
scanf("%d", &array[i]);
}
Also correct your somma
if (n == -1)
{
return 0;
}
If an array has n elements, then the last element has index n-1. Correct your somma function like this:
int somma(int a[], int n) {
if (n <= 0) {
return 0;
}
return a[n-1] + somma(a, n-1);
}
Additionally, there are two (minor) issues with your code:
Variable declaration inside for head in for(int i=0; i<4; i++) is not allowed by C89, only C99 and C++. Probably DevC++ compiles it because the file is treated as C++, but you should know that it won't compile on GCC, unless you use the -std=c99 switch.
getch is Windows-specific. On POSIX systems, use getchar instead.
Related
The question is to find twin prime numbers using pass by reference. I tried to code it out but it doesn't work the way normal pointers would? (Cannot use malloc function)
#include <stdio.h>
int twinp(int *n)
{
int i=2;
for (i=2; i<= *n/2; i++)
{
if (*n%i == 0)
return 0;
}
if (i > *n/2)
return 1;
}
int main ()
{
int i, c= 0;
printf("Twin prime numbers before 100 are: ");
for (i = 2; i <= 100; i++)
{
if (twinp(&i) && twinp(&i+2))
{
printf ("(%d, %d) ", i, i+2);
c++;
}
}
printf (" \nTotal number of twin prime pairs: %d", c); return 0;
}
If you want to pass the reference to a function in c, you have to use pointers.
Use the '&' keyword to reference the address of the value. Remember to have a memory location at moment to pass the reference, so you have to store the 'i+2' in local function and pass the reference to your function. Then use '*' to access the value.
#include <stdio.h>
int twinp(int * n)
{
int i=2;
for (i=2; i<= *n/2; i++)
{
if (*n%i == 0)
return 0;
}
if (i > *n / 2)
return 1;
}
int main ()
{
int i, c= 0;
printf("Twin prime numbers before 100 are: ");
for (i = 2; i <= 100; i++)
{
int i_plus_2 = i+2;
if (twinp(&i) && twinp(&i_plus_2))
{
printf ("(%d, %d) ", i, i+2);
c++;
}
}
printf (" \nTotal number of twin prime pairs: %d\n", c); return 0;
}
You are on the right track. When you pass by reference, you pass a memory location & of a variable in the calling function (twinp(..)) and in the actual function implementation, you'd catch that memory location via * pointer. When you actually try to use the value, you have to make sure you deference with the *.
Another approach you can take would be the below:
In the function itself, we do our checks for that current number AND the +2 number.
Your loop in your main function will take care of all the iterations up to 100.
If we find the number is prime, we print in the function. If not, we return and continue to the next iteration in our main loop.
#include <stdio.h>
void twinp(int *n)
{
for(int i= 2; i < *n; i++) {
if((*(n) % i) == 0 || (*(n) + 2) % i == 0)
return;
}
printf("(%d, %d),", *n,*n +2);
}
int main ()
{
int i, c = 0;
printf("Twin prime numbers before 100 are: ");
for (i = 3; i < 100; i++)
{
twinp(&i);
}
printf (" \nTotal number of twin prime pairs: %d", c);
return 0;
}
This is a piece of code to add the same number multiple times to an empty array but when I am printing the now non empty array, I am getting some other values:
#include<stdio.h>
#include<stdlib.h>
void sort_0(int arr[100], int i, int n){
int final_array[100], c=0;
// Count the number of '0' in the array
for(i=0;i<n;i++){
if(arr[i] == 0){
c++;
}
}
// Add the c number of '0' to the final_array
for(i=0;i<c;i++){
scanf("%d",final_array[i]);
}
for(i=0;i<c;i++){
printf("%d ", final_array[i]);
}
}
int main(){
int arr[100], i, n;
// Entering the size of the array
scanf("%d", &n);
// Entering n elements into the array
for(i=0;i<n;i++){
scanf("%d", &arr[i]);
}
sort_0(arr,i,n);
return 0;
}
In the above code, the number of times 0 appears in the array is counted. Then the count is taken as the range and 0 is adding to the empty array final_array count times.
If c = 5, the final_array = {0,0,0,0,0}
Expected Output:
arr = {0,1,4,3,0}
Output = 2
I am not getting any output
Since you don't know how much 0 you'll need to add to your array_final I figured out that a better solution could be to create that array after you have the number of 0 of the first array. Also, I see no reason why you were passsing i to the function since you can simply define it in the function itself.
void sort_0(int arr[10], int n, int* c){
int i;
for(i=0;i<n;i++){
if(arr[i] == 0){
(*c)+= 1;
}
}
}
int main (void) {
int size;
printf("Enter array size: ");
scanf("%d", &size);
int arr[size];
for (int i=0;i<size;i++) {
scanf("%d",&arr[i]);
}
int c = 0;
sort_0(arr, size, &c);
printf("C is: %d\n",c);
int* final_array;
if ((final_array=malloc(c * sizeof(int)))==NULL) // should always check malloc errors
{
perror("malloc");
return -1;
}
for (int i=0;i<c;i++) {
final_array[i]= 0;
}
printf("{");
for (int i=0;i<c-1;i++) {
printf("%d,", final_array[i]);
}
printf("%d}\n",final_array[c-1]);
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 have a function that takes array 1 and copies/manipulates it to array 2. Basically what it does is take the user input in array one, lets say (2, 3, 3) and array 2 is stored as (2, 0, 3, 0, 3). I know this works because it worked without implementing a function but sadly I have to have one. I cannot for the life of me figure out how to call the function, I believe I don't need a return since its a void and not returning a value. Below is my code any help would be appreciated.
#include <stdio.h>
void insert0(int n, int a1[], int a2[]);
int main() {
int i = 0;
int n = 0;
int a1[n];
int a2[2*n];
printf("Enter the length of the array: ");
scanf("%d",&n);
printf("Enter the elements of the array: ");
for(i = 0; i < n; i++){ //adds values to first array
scanf("%d",&a1[i]);
}
insert0(); //call function which is wrong and I cannot get anything to work
for( i = 0; i < n*2; i++){ //prints array 2
printf("%d", a2[i]);
}
void insert0 (int n, int a1[], int a2[]){ //inserts 0's between each number
for(i = 0; i < n; i++){
a2[i+i] = a1[i];
a2[i+i+1] = 0;
}
}
}
Modifying n after declaraing a1 and a2 won't magically increase their size. Declare a1 and a2 after reading the size into n to use variable-length arrays.
You must pass proper arguments to call insert0.
Defining functions inside functions is GCC extension and you shouldn't do that unless it is required.
a2 should have n*2 - 1 elements, not n*2 elements.
After moving it out of main(), i is not declared in insert0, so you have to declare it.
You should check if readings are successful.
Corrected code:
#include <stdio.h>
void insert0(int n, int a1[], int a2[]);
int main() {
int i = 0;
int n = 0;
printf("Enter the length of the array: ");
if(scanf("%d", &n) != 1){
puts("read error for n");
return 1;
}
if(n <= 0){
puts("invalid input");
return 1;
}
int a1[n];
int a2[2*n-1];
printf("Enter the elements of the array: ");
for(i = 0; i < n; i++){ //adds values to first array
if(scanf("%d", &a1[i]) != 1){
printf("read error for a1[%d]\n", i);
return 1;
}
}
insert0(n, a1, a2);
for( i = 0; i < n*2-1; i++){ //prints array 2
printf("%d", a2[i]);
}
}
void insert0 (int n, int a1[], int a2[]){ //inserts 0's between each number
int i;
for(i = 0; i < n; i++){
a2[i+i] = a1[i];
if (i+1 < n){ // don't put 0 after the last element
a2[i+i+1] = 0;
}
}
}
I'm trying to sort elements in an array from smallest to largest that a user inputs along with the size. This is my code so far:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define MAXVALUES 20
void sort(int *A[], int n) {
int i, tmp, j;
for (i = 0; i <= (n - 2); i++) {
for (j = (i + 1); j <= (n - 1); j++) {
if (*A[i] > *A[j]) {
tmp = *A[i];
*A[i] = *A[j];
*A[j] = tmp;
}
}
}
return;
}
int main(int argc, char *argv[]) {
int n, A[MAXVALUES], i;
printf("Enter an array and no. of elements in array: ");
scanf("%d%d", &A[MAXVALUES], &n);
sort(A[MAXVALUES], n);
printf("Ordered array is: \n");
for (i = 0; i <= (n - 1); i++) {
printf(" %d", A[i]);
}
return 0;
}
The compiler compiles it without any errors but it stops working after I put in the inputs. I've yet to quite grasp the theory behind arrays and pointers so could someone tell me where in my code I'm going wrong?
scanf("%d%d", &A[MAXVALUES], &n); is the problem
That's not how you read an array.
First you read the n, after that inside a loop you read every element like
scanf("%d", &A[i]); where i is the index from 0 to n
EDIT:
scanf("%d", &n);
int i = 0;
for(i = 0; i < n; i++)
{
scanf("%d", &A[i]);
}
This is what you want.
You can't use scanf() to read in a whole array at once.
This:
scanf("%d%d", &A[MAXVALUES], &n);
Makes no sense; it passes scanf() the address of the element after the last one in A, causing undefined behavior. The sort() call is equally broken.
To read in multiple numbers, use a loop. Also, of course you must read the desired length first, before reading in the numbers themselves.
Firstly I'll tell you a couple of things about your sorting function. What you want, is take an array (which in C is representable by a pointer to the type of elements that are in that array, in your case int) and the array's size(int) (optionally you can take a sorting method as an argument as well, but for simplicity's sake let's consider you want to sort things from lowest to highest). What your function takes is a pointer to an array of integers and an integer (the second argument is very much correct, or in other words it's what we wanted), but the first is a little more tricky. While the sorting function can be wrote to function properly with this argument list, it is awkward and unnecessary. You should only pass either int A[], either int *A. So your function header would be:
void sort1(int *A, int n);
void sort2(int A[], int n);
If you do this however, you have to give up some dereferencing in the function body. In particular I am referring to
if (*A[i] > *A[j]) {
tmp = *A[i];
*A[i] = *A[j];
*A[j] = tmp;
} which should become
if (A[i] > A[j]) {
tmp = A[i];
A[i] = A[j];
A[j] = tmp;
}
You should check out the operators [] and *(dereference) precedence http://en.cppreference.com/w/c/language/operator_precedence
Now, to adapt to these changes (and further correct some code) your main would look like so:
int main(int argc, char *argv[])
{
int A[MAXVALUES], n;
do{
printf("n="); scanf("%d", &n);
}while(n < 0 || n > 20);
int i;
for(i = 0; i < n; ++i)
scanf("%d", &A[i]); //this will read your array from standard input
sort(A, n); //proper sort call
for(i = 0; i < n; ++i)
printf(" %d", A[i]);
printf("\n"); //add a newline to the output
return 0;
}