i'm new to programming and i'm learning about recursion, i am doing exercise 4 from this page
https://www.w3resource.com/c-programming-exercises/recursion/index.php, i am trying to print the elements of the array once the value of "i" in the recursive function gets to the value of "n", however once i run the program it prints garbage values i think.my question is why does it do that? why doesn't it print the values of the array?
#include <stdio.h>
#include <stdlib.h>
void printr(int n,int i);
int main (void)
{
printf("NUMBER OF ELEMENTS:\n");
int n;
scanf("%i",&n);
printr(n,0);
}
void printr(int n,int i)
{
int arr[n];
if (i == n)
{
for (int j = 0; j < n; j++)
{
printf("%d",arr[j]);
return;
}
}
printf("element %d :\n",i+1);
int e;
//scan for input
scanf("%d",&e);
//populate array
arr[i]=e;
//do it again
printr(n,i + 1);
}
Then i solved it by passing the array defined in the mein function asan argument in the printr function
it worked but i don't understand why my first attemp didn't?
#include <stdio.h>
#include <stdlib.h>
void printr(int arr[],int n,int i);
int main (void)
{
printf("NUMBER OF ELEMENTS:\n");
int n;
scanf("%i",&n);
int arr[n];
printr(arr,n,0);
}
void printr(int arr[],int n,int i)
{
if (i == n)
{
for (int j = 0; j < n;j++)
{
printf("%d ",arr[j]);
}
printf("\n");
return;
}
printf("element %d :\n",i+1);
int e;
//scan for input
scanf("%d",&e);
//populate array
arr[i] = e;
//do it again
printr(arr,n,i + 1);
}
Thank you!
Because basic C: each invocation of printr has its own arr on the stack, initially uninitialized. And you print it without initializing it first.
When you print out the value, it isn't initialized first. When you create the variable to be printed, its pointing to a place in memory. This memory was probably freed by another program (so its up for grabs). As such, it contains "garbage" data. The way to deal with this is to initialize your values.
In order to avoid stuff like this in the future, get in the habit of setting your pointers to NULL when you don't initialize them so that your programs segfaults when your trying to read an uninitialized value.
Related
in a program to accept an array and display it on the console using functions getArray() and displayArray() how this program works as it Accepts values of array in function getArray() and uses it in the function displayArray() without returning any values from the first function?
I tried this program and failed to get result, then found this one in youTube comment section and I tried it and got results! I want to know how this program works ?
Q:Write a program to accept an array and display it on the console using function?
a.Program should contain 3 functions including main() function,
main() - {
Declare an array.
Call function getArray().
Call function displayArray() }.
getArray() -
Get values to the array.
displayArray() -
Display the array values
#include <stdio.h>
#include <stdlib.h>
void getArray(int);
void displayArray(int);
int main(void) {
int limit;
printf("Enter The Size of the Array :");
scanf("%d",&limit);
getArray(limit);
displayArray(limit);
return EXIT_SUCCESS;
}
void getArray(int limit){
int i,a[100];
printf("Enter The Values of Array :\n");
for(i=0;i<limit;i++){
scanf("%d",&a[i]);
}
}
void displayArray(int limit){
int i,b[100];
printf("Your Array is :\n");
for(i=0;i<limit;i++){
printf(" %d\t",b[i]);
}
printf("\n");
}
Array a in getArray is a local variable that gets destroyed when it goes out of scope. Array b in displayArray is also a local variable (local to displayArray) and has no relationship with a in getArray. You need to pass the same array to both functions.
One way could be to allocate the needed memory for the array in main and pass that, along with the number of elements in the array, to the two functions.
Example:
#include <stdio.h>
#include <stdlib.h>
// a is now a pointer to the first element in the array:
void getArray(int *a, int limit) {
printf("Enter The Values of Array :\n");
for(int i = 0; i < limit; i++) {
scanf("%d", &a[i]);
}
}
// b is now a pointer to the first element in the array:
void displayArray(int *b, int limit) {
printf("Your Array is :\n");
for(int i = 0; i < limit; i++) {
printf(" %d\t", b[i]);
}
putchar('\n');
}
int main(void) {
int limit;
printf("Enter The Size of the Array :");
if(scanf("%d", &limit) != 1 || limit < 1) return EXIT_FAILURE;
// allocate memory for `limit` number of `int`s:
int *arr = malloc(limit * sizeof *arr);
if(arr == NULL) return EXIT_FAILURE;
getArray(arr, limit); // pass arr + limit
displayArray(arr, limit); // pass arr + limit
free(arr); // and free the memory when done
return EXIT_SUCCESS;
}
#include<stdio.h>
void getArray(int);
void displayArray(int);
int array[100];
void main()
{
int limit;
printf("enter the array size you want\n");
scanf("%d",&limit);
getArray(limit);
displayArray(limit);
}
void getArray(int limit)
{
printf("enter the array element you want\n");
for(int i=0;i<limit;i++)
{
scanf("%d",&array[i]);
}
}
void displayArray(int limit)
{
for(int i=0;i<n;i++)
{
printf("%d",array[i]);
printf("\t");
}
}
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.
Sorry for that title. I really didn't know how to define this problem.
I was needed to declare integer array of N numbers and to fill it with random nums in void function. Then that array needs to be printed in main. The thing is that i am not allowed to use printf in void function so only way to print in main is to use pointers I guess. My knowledge is limited as I am beginner at pointers. Thx in advance and sorry for bad english.
Here is my code so far. When I compile it marks segmentation error.
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
void form();
int main()
{
int N, a[100];
printf("Input index: \n");
scanf("%d", &N);
form(N, &a);
printf("Array: \n");
for (int i = 0; i < N; i++) {
printf("a[%d] = %d", i, a[i]);
}
}
void form(int N, int *ptr[100])
{
srand(time(NULL));
for (int i = 0; i < N; i++) {
*ptr[i] = rand() % 46;
}
There are several issues in your code.
1) Your array decalaration form() is obsolete. Use proper prototype.
2) For declaring a VLA, declare it after reading N instead of using a fixed size array.
3) An array gets converted into a pointer to its first element when passed to a function. See: What is array decaying?
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
void form(int, int*); /* see (1) */
int main(void) /* Standard complaint prototype for main.
If you need to pass arguments you can use argc, and argv */
{
int N;
printf("Input size: \n");
scanf("%d", &N);
int a[N]; /* see (2) */
form(N, a); /* see (3) */
printf("Array: \n");
for (int i = 0; i < N; i++) {
printf("a[%d] = %d", i, a[i]);
}
}
void form(int N, int *ptr) { /* Modified to match the prototype
srand(time(NULL));
for (int i = 0; i < N; i++) {
ptr[i] = rand() % 46;
}
}
So a couple things:
void form();
As Olaf was alluding to, this declaration is incorrect - you are missing the applicable parameters. Instead, it should be
void form(int N, int ptr[100]);
The main reason your program is crashing is because of the following line:
*ptr[i] = rand() % 46;
You are dereferencing the pointer at i, which is actaully giving you a number - what you want is to assign the value of the pointer at i the new random value:
ptr[i] = rand() % 46;
As related reading, see this question about passing an array in as a function parameter (basically, int ptr[] is the same thing as int * ptr)
Small modifications on your code:
1) Correction and simplification of parameter handling at function call. Just hand over "a", it's an array, so it is an address, you can use int *ptr, or int ptr[], or int ptr[100] in the formal parameter list for it. So you can use simply ptr[i] in your function.
2) Make a prototype for function from old-style declaration providing parameter list.
3) int i; declaration before the for loop - not mandatory, depends on your compiler standard
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
void form(int N, int *ptr);
int main()
{
int N, a[100];
printf("Input index: \n");
scanf("%d", &N);
form(N, a);
printf("Array: \n");
int i;
for (i = 0; i < N; i++) {
printf("a[%d] = %d", i, a[i]);
}
}
void form(int N, int *ptr)
{
srand(time(NULL));
int i;
for (i = 0; i < N; i++) {
ptr[i] = rand() % 46;
}
}
I'm trying to make function that prints array but the output of it is wrong.
Can someone help me please?
This is the code:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
void printArr(int arr[],int size);
int main()
{
int arr1[3] = { 1,2,3 };
int arr2[5] = { 1,2,3,4,5 };
printf("arr1: \n");
printArr(arr1, 3);
printf("\n\narr2: \n");
printArr(arr2, 5);
printf("\n\n");
return(0);
}
void printArr(int arr[], int size)
{
int i;
for (i = 0; i < size; i++);
{
printf("%d", arr[i]);
}
}
What I get is:
Remove the semi-colon at the of for:
for (i = 0; i < size; i++);
^^^
That makes the for loop run size times and executes the block after that. But by that time, i value is equal to size. This leads to out of bound access, which is undefined behaviour. Clearly, this is not what you intention was.
I am coding a c project, that needs that the user enters a N*N square of integers : that's to say an input of N lines of N integers. The algo works fine.
Now I want the user to input N lines of N integers each of consecutive integers are separated by a space. Here, I don't have the right usage of scanf, because I tried to declare integers array but I was not able to deal with the spacing.
I tried something like this, very unnatural and failing :
int i=0;
int j=0;
int N;
scanf("%d",&N);
char c[N][2*N-1];
while(i < N){
scanf("%s",&c[i]);
i++;
}
i=0;
j=0;
while (i<N){
while (j<N){
c[i][j]=c[i][2*j]-48;
j++;
}
j=0;
i++;
}
Can someone help ?
Best,
Newben
If I understood what your original code was supposed to do then this code should actually do it (and print it out again just to prove it worked).
You need to dynamically allocate the array since it's variable size ( In C99 you could use variable sized arrays on the stack but that's really a different discussion ).
scanf will automatically ignore white-space between the integers (including spaces and new-lines) so you don't need to parse that out manually.
#include <stdlib.h>
#include <stdio.h>
int main()
{
int i=0, j=0, N;
int **c;
scanf("%d",&N);
c = malloc(N*sizeof(int*));
for (i=0;i<N;i++)
{
c[i] = malloc(N*sizeof(int));
for (j=0;j<N;j++)
{
scanf("%d",&c[i][j]);
}
}
for (i=0;i<N;i++)
{
for (j=0;j<N;j++)
{
printf("%d ",c[i][j]);
}
printf("\n");
free(c[i]);
}
free(c);
return 0;
}
C99 alternative without malloc/free for completeness (I'v never liked this C99 feature since there's no way to check that the was/is enough space on the stack):
#include <stdlib.h>
#include <stdio.h>
int main()
{
int i=0, j=0, N;
scanf("%d",&N);
int c[N][N];
for (i=0;i<N;i++)
{
for (j=0;j<N;j++)
{
scanf("%d",&c[i][j]);
}
}
for (i=0;i<N;i++)
{
for (j=0;j<N;j++)
{
printf("%d ",c[i][j]);
}
printf("\n");
}
return 0;
}