I have just started learning how to program and I came across an assignment whereby I have to create an array wherein the weight of the elephant seals is read & printed. Can someone please tell me what's wrong with my code, because I can read in the data but my data is being printed wrong when I call the printArray function.
Below is my code:
/*
compute the weight average of elephant seals using an array that will read in the data
*/
#include <stdio.h>
void arrayReadingData(const int sizeP) //array to read in the weight of the elephantseals
{
int weightP[sizeP];
for(int i = 1; i <= sizeP; i++)
{
printf("Elephant seal %d weight is: ", i);
scanf("%d", &weightP[i]);
}
}
void printArray(const int sizeP)
{
int weightP[sizeP];
for(int i = 1; i <= sizeP; i++)
{
printf("%d\t", weightP[i]);
}
}
int main(void)
{
int size;
printf("How many seals do you want to calculate the average weight for: ");
scanf("%d", &size);
arrayReadingData(size);
printArray(size);
};
You are doing the for loop wrong, your loop should start at i = 0 to i < sizeP, when i = sizeP weights[sizeP] will be assigned an arbitrary value.
Update:
I just noticed you are declaring the array as a local variable to each function and declaring it the wrong way, you should declare that array in the main function and pass it to your functions instead
Here is a solution you can use
/*
compute the weight average of elephant seals using an array that will read in the data
*/
#include <stdio.h>
#define SIZE 3
void arrayReadingData(int weightP[]) //array to read in the weight of the elephantseals
{
for(int i = 0; i < SIZE; i++)
{
printf("Elephant seal %d weight is: ", i);
scanf("%d", &weightP[i]);
}
}
void printArray(int weightP[])
{
for(int i = 0; i < SIZE; i++)
{
printf("%d\t", weightP[i]);
}
}
int main(void)
{
int weights[SIZE];
arrayReadingData(weights);
printArray(weights);
};
Note: if you want the size to be given by the user you can use pointers and allocate memory dynamically
Here is how you can achieve that:
/*
compute the weight average of elephant seals using an array that will read in the data
*/
#include <stdio.h>
#include <stdlib.h>
void arrayReadingData(int weightP[], int size) //array to read in the weight of the elephantseals
{
for(int i = 0; i < size; i++)
{
printf("Elephant seal %d weight is: \n", i);
scanf("%d", &weightP[i]);
}
}
void printArray(int weightP[], int size)
{
for(int i = 0; i < size; i++)
{
printf("%d\t", weightP[i]);
}
}
int main(void)
{
int* weightsArray;
int size;
printf("Enter the size of the array:\n");
scanf("%d", &size);
weightsArray = (int*)malloc(size*sizeof(int));
if(weightsArray == NULL){
printf("couldn't allocate memory");
exit(1);
}
arrayReadingData(weightsArray, size);
printArray(weightsArray, size);
free(weightsArray);
};
I redid the code, after learning from the comments and I came up with this solution, the problem is that now I can only read in 10 numbers and print 10 numbers if I read in 11 numbers and try to print it I get an error stating zsh: segmentation fault
/*
compute the weight average of elephant seals using an array that will read in the data
*/
#include <stdio.h>
void arrayReadingData(const int sizeP, int weightP[]) //array to read in the weight of the elephant seals
{
for(int i = 0; i < sizeP; i++)
{
printf("Elephant seal %d weight is: ", i);
scanf("%d", &weightP[i]);
}
}
void printArray(const int sizeP, int weightP[])
{
for(int i = 0; i < sizeP; i++)
{
printf("%d\n", weightP[i]);
}
}
int main(void)
{
int size;
int weight[size];
printf("How many seals do you want to calculate theaverage weightfor:");
scanf("%d", &size);
arrayReadingData(size, weight);
printArray(size, weight);
}
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.
How can we modify the following code (which initially asks the user for 10 numbers to be entered, get stored in an array, and printed on the screen) so that the even numbers are printed on the first line, and the odd on the second:
#include <stdlib.h>
#include <stdio.h>
int i,j;
int array_1[10];
int main() {
for(i=0;i<10;i++) {
printf("Enter a number: ");
scanf("%d", &array_1[i]);
}
printf("The elements of the array are: ");
for (j=0;j<10;j++) {
printf("%d ", array_1[j]);
}
printf("\n");
return 0;
}
O(n) Solution:
you have to add odd numbers at the back of the array and add the even numbers at the front of the array and keep track of the indexes.
int array_1[10];
int main() {
int even = 0, odd = 10;
for (int i = 0; i < 10; i++) {
printf("Enter a number: ");
int inp;
scanf("%d", &inp);
if (inp % 2 == 0) {
array_1[even++] = inp;
} else {
array_1[--odd] = inp;
}
}
// even numbers
for (int i = 0; i < even; i++) {
printf("%i ", array_1[i]);
}
printf("\n");
// odd numbers
for (int i = 9; i >= odd; i--) {
printf("%i ", array_1[i]);
}
printf("\n");
return 0;
}
Since you asked, here is how I would do it. I suspect this may leave you with more questions than answers through.
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#define NUMBERS_SIZE 10
typedef bool (*number_validator)(int num);
bool isEven(int num)
{
return (num & 1) == 0;
}
bool isOdd(int num)
{
return (num & 1) != 0;
}
void print(const char *title, int *array, int array_size, number_validator isValid)
{
printf("%s", title);
bool first = true;
for (int i = 0; i < array_size; ++i)
{
if (isValid(array[i]))
{
if (!first)
{
printf(", ");
}
printf("%d", array[i]);
first = false;
}
}
printf("\n");
}
int main()
{
int numbers[NUMBERS_SIZE] = { 0 };
for (int i = 0; i < NUMBERS_SIZE; i++)
{
printf("Enter a number: ");
scanf("%d", &numbers[i]);
}
printf("\n");
print("Even: ", numbers, NUMBERS_SIZE, isEven);
print(" Odd: ", numbers, NUMBERS_SIZE, isOdd);
return 0;
}
Demo on ideone
you can try this way.I have used binary AND(&) instead of MOD(%) as it is faster:
#include <stdlib.h>
#include <stdio.h>
int i,j;
int array_1[10];
int main()
{
for(i=0; i<10; i++)
{
printf("Enter a number: ");
scanf("%d", &array_1[i]);
}
printf("The Even elements of the array are: ");
for (j=0; j<10; j++)
{
if((array_1[j]&1) == 0)
printf("%d ", array_1[j]);
}
printf("\nThe Odd elements of the array are: ");
for (j=0; j<10; j++)
{
if((array_1[j]&1) != 0)
printf("%d ", array_1[j]);
}
printf("\n");
return 0;
}
No need to create a new array. You can just go through it first checking for even numbers, and then again for odd numbers. Also, there's no need to declare i and j before using them. You can just declare them and initialize them in the for loop:
#include <stdlib.h>
#include <stdio.h>
int array_1[10];
int main() {
for(int i=0;i<10;i++) {
printf("Enter a number: ");
scanf("%d", &array_1[i]);
}
printf("The elements of the array are: ");
// Print even numbers
for (int j=0;j<10;j++) {
if(array_1[j] % 2 == 0)
printf("%d ", array_1[j]);
}
printf("\n");
// Print odd numbers
for (int j=0;j<10;j++) {
if(array_1[j] % 2 != 0)
printf("%d ", array_1[j]);
}
printf("\n");
return 0;
}
Edit: As tadman suggested in the comment below, there's a better and cleaner way to do this kind of task. As you can see in the above example, I'm repeating 4 lines of code where only one character changes. This task could be abstracted into a function to reduce code repetition:
void printIfMod(int* arr, size_t array_size, int mod){
for (int j=0;j<array_size;j++) {
if(arr[j] % 2 != mod)
continue;
printf("%d ", arr[j]);
}
printf("\n");
Remember to add a function prototype before main if you place the function after main:
void printIfMod(int* arr, size_t array_size, int mod);
int main(){...}
Now, to print the numbers, call the method with modulo 0 to get even numbers, and 1 to get odd numbers:
// Print even numbers
void printIfMod(&array_1, 10, 0);
// Print odd numbers
void printIfMod(&array_1, 10, 1);
One last note, hard-coding array_size is not wise, and that goes for all arrays. I recommend using sizeof() to dynamically calculate the size of your array:
size_t size = sizeof(array_1) / sizeof(int);
// Print even numbers
void printIfMod(&array_1, size, 0);
// Print odd numbers
void printIfMod(&array_1, size, 1);
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");
}
I want to make a simple variable for number of the round for a loop, so I tried my code
int size,counter,marks[size];
scanf("enter %d/n",&size);
for(counter=0;counter<size;counter++)
{
scanf("%d",&marks[counter]);
}
and compiled with no error but in run, it just shows "process returned -1073741571 <0*c00000FD>.
so I tried gets function and it shows "too many arguments to function 'gets' ".
int size;
int counter;
int marks[size];
scanf("enter %d/n",&size);
for(counter=0;counter<size;counter++)
{
gets("%d",&marks[counter]);
}
I'm using code::blocks 17.12 and the gnu compiler.
size can have any value when the array marks is allocated because it is not initialized. The array might be smaller than the entered size and so marks are stored in non-allocated memory, giving you the error.
This is a possible solution, but it doesn't compile with strict ISO C90. Presumably your CodeBlocks uses GCC that accepts variable length arrays and mixed declarations and code.
#include <stdio.h>
int main(void) {
int size;
printf("enter size: ");
scanf("%d",&size);
int marks[size];
int counter;
for (counter = 0; counter < size; counter++) {
scanf("%d", &marks[counter]);
}
for (counter = 0; counter < size; counter++) {
printf("%d: %d\n", counter, marks[counter]);
}
return 0;
}
BTW, please don't say "build error" if you have a runtime error. ;-)
Please don't use gets. It's dangerous.
As for your error in the scanf example, the first problem is the line
int size,counter,marks[size];
which declares marks with the uninitialized size value. Try initializing size first, then declaring the marks array.
Your second problem is scanf formatting string. Use scanf to read formatted input, not output a prompt. Use puts or printf for that.
Here's a full example:
#include <stdio.h>
int main(void) {
int size;
printf("Enter a size value: ");
scanf("%d", &size);
int marks[size];
for (int i = 0; i < size; i++) {
printf("Enter element %d: ", i);
scanf("%d", &marks[i]);
}
printf("You entered: ");
for (int i = 0; i < size; i++) {
printf("%d ", marks[i]);
}
puts("");
return 0;
}
Here's a sample run:
Enter a size value: 4
Enter element 0: 88
Enter element 1: 77
Enter element 2: 66
Enter element 3: 55
You entered: 88 77 66 55
If you're writing ANSI C-compatible code you can use dynamic memory with malloc:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int i, size, *marks;
printf("Enter a size value: ");
scanf("%d", &size);
if (size < 1) {
fprintf(stderr, "Invalid size specified\n");
exit(1);
}
marks = malloc(size * sizeof(int));
if (!marks) {
fprintf(stderr, "malloc failed\n");
exit(1);
}
for (i = 0; i < size; i++) {
printf("Enter element %d: ", i);
scanf("%d", &marks[i]);
}
printf("You entered: ");
for (i = 0; i < size; i++) {
printf("%d ", marks[i]);
}
free(marks);
puts("");
return 0;
}
size must have a defined value, for example:
#include <stdio.h>
int main()
{
int size;
size = 5; // size must be constant
int counter, marks[size];
for (counter = 0; counter < size; counter++)
{
scanf("%d", &marks[counter]);
}
//Printing it returns correct values:
for (counter = 0; counter < size; counter++)
{
printf("%d\n", marks[counter]);
}
}
You can instead input it's value from the user if you want.
However, if for some reason, size is to be defined after the array is declared, use pointers:
#include <stdio.h>
#include "stdlib.h"
int main()
{
int size;
int counter, *marks;
size = 5; //declared after the array
marks = (int *)malloc(size * sizeof(int));
for (counter = 0; counter < size; counter++)
{
scanf("%d", &marks[counter]);
}
//Printing it returns correct values:
for (counter = 0; counter < size; counter++)
{
printf("%d\n", marks[counter]);
}
//Don't forget to free the array in the end
free(marks);
}
I have assignment to write program that sort an array and search for a specific number, that part I've already done, My problem is how to Initialize the array in the size that the user sets with random values smaller than 500? I know how to do that with known size but not with unknown size?
example for input/output:
"Please enter the size of the array:
5"
This will help you.
int main(void)
{
int n,i;
n=rand()%500; // Get random value
int arr[n]; // Initialize the dynamic array
for(i=0;i<n;i++)
scanf("%d",&arr[i]);
// Do your stuff
}
You can do something like this:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void printArray(int* p, int size)
{
for (int j = 0; j < size; ++ j) printf("%d ", p[j]);
printf("\n");
}
int main(void) {
srand(time(NULL)); // Start with a random seed based on time
int n = 0;
printf("Which array size do you need?\n");
if (scanf("%d", &n) != 1 || n < 1)
{
printf("Wrong input\n");
exit(0);
};
printf("Creating random array of size %d\n", n);
int* p = malloc(n * sizeof(*p)); // Reserve memory
for (int j = 0; j < n; ++j) p[j] = rand() % 500; // Generate random numbers
printArray(p, n); // Print the result
free(p); // free the allocated memory
return 0;
}