#include <stdio.h>
int main()
{
//Initialize array
int n; // n is use to decide the size of array
int x[n];
int y[n];
printf("enter the size of array:");
scanf("%d", &n);
if (n > 0)
{
for (int i = 0; i < n; i++)
{
printf("enter elements : \n");
scanf("%d", &x[i]);
}
}
printf("Array in reverse order: \n");
//Loop through the array in reverse order
for (int i = n - 1, j = 0; i >= 0; i--, j++)
{
y[j] = x[i];
printf("%d ", y[j]);
}
return 0;
}
In the above program, I have created a array whose size can be decided by the user. The user can also put elements in it.
After that I want to reverse this array and store the data in another array. But I get this error again and again. I am using CodeBlocks with the GCC compiler.
When the x and y arrays are created, n is uninitialized. There's no knowing how large these arrays will be. You loops are almost certainly accessing the array out of bounds.
You want to read n, then create the arrays. Of course you also want to error check the result of scanf.
int n; // n is use to decide the size of array
printf("enter the size of array:");
scanf("%d", &n);
int x[n];
int y[n];
Related
I'm writing a program which scanf integers and printf in double.
Here is my code:
int main(void) {
int arraySize;
scanf("%d",&arraySize);
double vector[arraySize];
for(int i=0;i<arraySize;i++) scanf("%lf", &vector[i]);
for(int a=0;a<arraySize;a++) printf("VECTORS:[%lf]",vector[a]);
}
Since I need to for loop every element in the array then printf all of them one by one.
this is the output I had:
VECTORS:[1.000000] VECTORS:[2.000000] VECTORS:[3.000000]
How can I change the format of the printf function and get ouput like this:
VECTOR: [ 1.000, 2.000, 3.000 ]
Your one major mistake is your array size. I know your compiler won't issue any warning but this is not any feature which language provide so size must be a
constant numerical value or const expression.
So in short you can't create array After asking size from user. This is completely wrong.
int arraySize;
scanf("%d",&arraySize);
double vector[arraySize];
You must make size const. If you want less values than the declared size you can decrease the no of times for loop will run but you can't decide array size as inputted by user.
const int size = 10; // this is how your size should be. Even your compiler allowed VLA you should not try this. size of arrays must be constant.
int main()
{
unsigned int i,s;
int arr[size];
printf ("Enter the size of array.");
scanf("%d",&s);
for(i = 0 ; i<s;i++){
scanf("%d",&arr[i]);
}
for(i = 0 ; i<s;i++){
arr[i] = arr[i]*arr[i];
}
for(i = 0 ; i<s;i++){
printf("%d",arr[i]);
}
}
Print VECTOR once then loop over all the vectors and output them in the desired format.
const int size = 10;
int main(void) {
double vector[size];
for(int i=0;i<size;i++)
scanf("%lf", &vector[i]);
printf("VECTOR: [ ");
for(int a=0;a<size;a++){
printf("%lf", vector[a]);
if(i < size - 1)
printf(", ");
}
printf(" ]");
}
You need to allocate memory dynamically to use it.
Use the printf in the code below to define precision.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int arraySize = 0;
scanf("%d",&arraySize);
double *vector = (double *) calloc(arraySize, sizeof(double));
for(int i=0; i<arraySize; i++) {
scanf("%lf", &vector[i]);
}
printf("VECTORS:[");
int a;
for(a=0;a<arraySize;a++) {
printf(" %.3lf",vector[a]);
if (a<(arraySize-1)) {
printf(",");
} else {
printf(" ");
}
}
printf("]");
}
Change your for loop to take 3 elements at once.
for(a=0;a<arraySize;a+=3) {
printf("VECTORS:[%lf", vector[a]);
if (a+1 < arraySize) printf(", %lf", vector[a+1]);
if (a+2 < arraySize) printf(", %lf", vector[a+2]);
printf("]\n");
}
Im making a code for an array that has a dynamic size and filling the array manually.Then, it will print. It will also ask for a number and finding the index that is equal to the two indexes.
I using codeblocks for this code. Id tried for loop to find the two indexes that is eqaul to the inputed number.
#include <stdlib.h>
#include <stdio.h>
void printArray(int *array, int size) {
printf("[");
for (int i = 0; i < size - 1; i++) {
printf("%i,", array[i]);
}
if (size >= 1)
printf("%i", array[size-1]);
printf("]\n");
int num;
printf("Enter number to be calculate: ");
scanf("%d",num);
for(int i= 0; i < size - 1; i++){
if (array[i] + array[size-1] == num){
printf("%d %d", array[i],array[size-1]);
}
size--;
}
}
int main(void) {
int count;
int num;
int sum;
printf("Enter the size of the array:\n");
scanf("%d", &count);
int *array = malloc(count * sizeof(*array));
if (!array) {
printf("There was a problem you entered");
exit(EXIT_FAILURE);
}
printf("Enter the elements of the array:\n");
for (int i = 0; i < count; i++)
scanf("%d", &array[i]);
printArray(array, count);
}
I expect the output:
Index 1 and 5 are eqaul to the inputed number.
but it gives error.
To begin with, the following bug is one of the problem -
scanf("%d",num);
should be -
scanf("%d", &num);
The final loop in printArray is basically iterating through the array one element both upwards & downwards at the same time.
So, for n=6, if sum of either (a[0]+a[5]), (a[1]+a[4]) or (a[2]+a[3]) does not equal the required number , it would show up as unmatched.
This loop should be replaced by a nested loop so that inner loop iterates from j=i+1 to size-1 to allow check for a[i]+a[j] == num for all possible permutations of array indexes.
Here is the code I have.
int *arr; // Indented this line
int sizeOfArr = 0;
printf("Enter size of arr.\n");
scanf("%d", &sizeOfArr);
arr = malloc(sizeOfArr * sizeof(int));
for (int i = 0; i < sizeOfArr; i++) {
scanf("%d", arr[i]);
}
For example, if the size of the dynamic array is 5, and I proceed to enter the input "1 2 3 4 5", the entire program crashes and gives me access violation.
In order to store array elements you need to use scanf("%d", &arr[i]); instead of
scanf("%d", arr[i]);
& in C is used to refer to address of a variable. So,by using &arr[i] you are telling your program to store the input variable at ith index of array arr[].
So the correct code will be
int *arr;
int sizeOfArr = 0;
printf("Enter size of arr.\n");
scanf("%d", &sizeOfArr);
arr = malloc(sizeOfArr * sizeof(int));
for (int i = 0; i < sizeOfArr; i++) {
scanf("%d", &arr[i]); //notice the diff here
}
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;
}
I don't know if I'm just being a total fool, most likely I am, it's been a long day, but this isn't working as I want it to, and, well, I don't see why.
It should be able to have 11 numbers entered, a new number on each line, add them to the array, then total them, yet it's just not working. It's not stopping to exit the loop, even though I am incrementing i.
Any ideas?
int main(void) {
int array[10];
int i;
int sum = 0;
for ( i = 0; i < 11; i++){
scanf("%d", &array[i]);
}
for (i = 0; i < 11; i++) {
sum += array[i];
}
printf("%d", sum);
return 0;
}
You have 10 elements in the array, numbered 0 - 9. You are overflowing the buffer, so all bets are off. This is undefined behaviour.
You can't add eleven entries to a ten-element array.
My guess is buffer over-run since the for-loop reads in 11 numbers and the 11th number gets stored outside the array, probably overwriting i.
Try changing the 11 to a 10 in the for loop.
You're storing eleven numbers into an array of size 10. Thus you're storing the last element out of bounds, which invokes undefined behavior.
The reason that this undefined behavior manifests itself as an infinite loop in your case is probably that i is stored after array in memory on your system and when you write a number into array[10] (which is out of bounds, as I said), you're overwriting i. So if you entered a number smaller than 11 this will cause the loop to continue and ask for input once more.
If an array is a[10], then every array starts from its index number 0, so here it will have 10 elements; given that their positions will start from 0 to 9, counting gives 10 elements.
You can try this:
main()
{
int a[10], i, n, sum=0;
printf("enter no. of elements");
scanf("%d",&n);
printf("enter the elements");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for (i=0;i<n;i++)
sum=sum+a[i];
for(i=0;i<n;i++)
printf("\n a[%d] = %d", i, a[i]);
printf("\n sum = %d",sum);
getch();
}
You have problems with your array declaration. You are defining an array of size 10 array[10] and saying the program to calculate the sum of 11 elements which is resulting in memory overflows.
To correct the program just increase size of the array as array[11]. Also if you wish you can check the recursive approach to find sum of array elements.
Try this:
void main() {
int array[10];
int i;
int sum = 0;
for ( i = 0; i < 11; i++){
scanf("%d", &array[i]);
}
for (i = 0; i < 11; i++) {
sum = sum + array[i] ;
}
printf("%d", sum);
return 0;
}
int main()
{
//this the sum of integers in an array
int array[] = { 22,2,2,1,5,4,5,7,9,54,4,5,4 },x,sum=0;
int cout_elements = sizeof(array) / sizeof(int);
for (x = 0; x < cout_elements; x++) {
sum += array[x];
}
printf("%d",sum);
return 0;
}
int main()
{
int a[10];
int i,j;
int x=0;
printf("Enter no of arrays:");
scanf("%d",&j);
printf("Enter nos:");
for(i=0;i<j;i++)
{
scanf("%d",&a[i]);
}
for (i=0;i<j;i++)
{
x=x+a[i];
}
printf("Sum of Array=%d",x);
return 0;
}