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);
}
Related
I wrote a simple program to take names and numbers from the user and store it in an array, then compare between each cell until it reach the maximum grade then it displays it. The problem is that when it run it shows a message (segmentation fault (Core dump)). I really don't know what my mistake is.
#include <stdio.h>
int main() {
int n;
printf("Enter the number of students: ");
scanf("%d", & n);
char name[n];
float score[n];
for (int i = 0; i < n; i++) {
printf("\nEnter the name of Student: ");
scanf("%s", & name[i]);
printf("\nEnter the score: ");
scanf("%f", & score[i]);
}
float max;
int index;
max = score[0];
index = 0;
for (int i = 1; i < n; i++) {
if (max < score[i]) {
max = score[i];
index = i;
}
}
printf("\nHighest mark scored is %f by student %s", name[index], score[index]);
}
1- you use user input to define the size of an array (wrong)
-- array in c has static size so you must define it's size before the code reach the compiling stage(use dynamic memory allocation instead)
2- scanf("%s", & name[I]); you want to save array of char and save the address at the name variable but name it self not a pointer to save address it's just of char type (wrong)
-- you need pointer to save the address of every name so it's array of pointer and a pointer to allocate the address of the array to it so it's a pointer to poiner and define max size of word if you define size the user input exceed it will produce an error
3- finally you exchanged the %f,%s in printf
#include <stdlib.h>
#include <stdio.h>
#define SIZE_OF_WORD 10
int main() {
int n;
printf("Enter the number of students: ");
scanf("%d", & n);
char **name=(char**)malloc((sizeof(char*)*n));
for (int i = 0; i < n; i++) {
name[i]=(char*)malloc((sizeof(char)*SIZE_OF_WORD));
}
float *score=(float*)malloc((sizeof(float)*n));
for (int i = 0; i < n; i++) {
printf("\nEnter the name of Student: ");
scanf("%s", name[i]);
printf("\nEnter the score: ");
scanf("%f", & score[i]);
}
float max;
int index;
max = score[0];
index = 0;
for (int i = 1; i < n; i++) {
if (max < score[i]) {
max = score[i];
index = i;
}
}
printf("\nHighest mark scored is %s by student %.0f\n", name[index],score[index]);
}
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'm a beginner at C programming. I'm making a program that will input numbers and delete the last input even number from the array using stack or the push-pop method.
The problem is I can't pop the last even number and I don't know what is wrong.
#include <stdio.h>
#include <stdlib.h>
#define MAX 100
int top = -1;
int stack[MAX];
void deleteEven(int num[], int i);
int main() {
int num[100];
int i, size;
printf("\n-----------------\n\n");
printf("Enter size of array: ");
scanf("%d", &size);
for (i = 0; i < size; i++) {
printf("Enter number: ");
scanf("%d", &num[i]);
top++;
stack[top] = num[i];
}
printf("\nList: ");
for (i = 0; i < size; i++) {
printf("%d, ", num[i]);
}
printf("\n");
printf("Even: ");
for (i = 0; i < size; i++) {
if (num[i] % 2 == 0) {
printf("%d, ", num[i]);
}
}
deleteEven(num, i);
return 0;
}
void deleteEven(int num[], int i) {
printf("\nAnswer: ");
if (num[i] % 2 == 0) {
stack[top--];
}
for (int j = top; j >= 0; --j) {
printf("%d, ", stack[j]);
}
}
I have implement the working one in C with implementing on your code, you can see below. I added int checkEven(int stack[], int stackSize) function which control the array if there is any even number or not. If not, so end the problem with returning 0 or whatever your error code is, other side if there is even number it returns the index of it and deleteEven function swipe the array (stack). It working for size of 5 array but you can fix it. I use 5 for easy testing.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define MAX 5
int top = -1;
int stack[MAX];
void deleteEven(int num[], int indexOfEven);
int checkEven(int stack[], int stackSize);
int main() {
int num[5];
int i, size;
printf("\n-----------------\n\n");
printf("Enter size of array: ");
scanf("%d", &size);
for (i = 0; i < size; i++) {
printf("Enter number: ");
scanf("%d", &num[i]);
top++;
stack[top] = num[i];
}
printf("\nList: ");
for (i = 0; i < size; i++) {
printf("%d, ", num[i]);
}
printf("\n===stack===");
for( i = 0; i <size; i++){
printf("%d ", stack[i]);
}
int indexOfEven = checkEven(stack,5);
if(indexOfEven >= 0){
printf("This sequence has even number");
printf("the index => %d ",indexOfEven);
deleteEven(stack, indexOfEven);
}else{
printf("this sequence has no even number");
/*
no even number
exit
*/
return 0;
}
return 0;
}
int checkEven(int stack[], int stackSize){
for(int i = stackSize - 1; i >= 0; i--){
if(stack[i] % 2 == 0){
return i;
}
}
return -1;
}
void deleteEven(int num[], int indexOfEven) {
int simpleArray[5];
for(int t = 0; t < 5; t++){
simpleArray[t] = num[t];
}
int c;
for (c = indexOfEven; c < 4; c++)
simpleArray[c] = num[c+1];
for (c = 0; c < 4; c++){
printf("\n%d\n", simpleArray[c]);
}
}
So far you see the O(n) implementation of it with array but you describe that you want to implement it with push() - pop() - peek() stack mechanism. I want to write sudo code for fully Stack implementation.
let it inputs be 1 - 2 - 3 - 5 - 7
describe inputSize
describe mainStack
describe helperStack
read inputs to mainStack
show stacks
mainStack -> [1-2-3-5-7]
helperStack -> []
while mainStack.peek() != NULL :
if mainStack.peek() % 2 == 0: // even number
mainStack.pop()
break the loop
else:
describe popValue = mainStack.pop()
helperStack.push( popValue )
if inputSize == helperStack:
// no even number
// so nothing break the loop, every value is odd so, all there is another stack
// finish program with error code or return main array / inputs
show stacks
mainStack -> [ 1 ]
helperStack -> [ 3 5 7 ]
now pop() the all helperStack and push it to mainStack
while helperStack.peek() != NULL:
mainStack.push( helperStack.pop() )
show stacks
mainStack -> [ 1 3 5 7 ]
helperStack -> [ ]
Return mainStack as array format.
It seems that the last loop before the call to deleteEven will increment i until the end of the stack array regardless the last number is even or not, because all you do is checking if the current number is even and then printing it, and right after that going to the next one. that will iterate through all the numbers which will result in calling deleteEven with the last index of the array.
how about going from the last element of the array to index 0 (backwards) and printing the first encounter with even number?
Also, not really sure why you're using two different arrays and copying elements one by one after using scanf.
I would like to improve my program with user-input of array length. Is that possible in C?
This my code:
int main() {
int sum = 0;
int a;
int array[a] = {};
printf("Insert length of array:\n");
scanf("%d", &a);
for (int i = 0; i < a; i++) {
printf("Insert number %d \n", i + 1);
scanf("%d", &array[i]);
}
for (int i = 0; i < a; i++) {
sum = sum + array[i];
}
printf("Sum is %d \n", sum);
return 0;
}
However when I try to compile it, it says: error: variable-sized object may not be initialized
Any possible solution?
Yeah, in C you couldn't create variable-sized array, and variable-sized in this context means that you can't create array when it's size isn't constant on the compile time. But you can use pointers, and after user input you can allocate array with the appropriate length.
For example:
int* array;
int length;
printf("Enter length of the array: ");
scanf("%d", &length);
// maybe you need to add checking, like if length > 0
array = malloc(sizeof(int) * length);
// now you have array with `length` elements and 0..`length`-1 indexes
There are multiple reasons for your program to fail:
the definition int array[a] = {}; uses an uninitialized variable a, so the program has undefined behavior. You must define this array after reading the value of a.
variable sized automatic arrays cannot have an initializer. You must initialize the array some other way, or not at all since you read the values in the following loop.
if the size a is negative or too large, the creation of the local array will have undefined behavior. Allocating from the heap with malloc() or calloc() is preferable for potentially large objects.
you do not test the return value of scanf(), causing undefined behavior on invalid input.
Here is a corrected version:
#include <stdio.h>
int main() {
int sum;
int a;
printf("Insert length of array:\n");
if (scanf("%d", &a) != 1 || a <= 0 || a > 1000) {
fprintf(stderr, "Invalid input\n");
return 1;
}
int array[a];
for (int i = 0; i < a; i++) {
printf("Insert number %d:\n", i + 1);
if (scanf("%d", &array[i]) != 1) {
fprintf(stderr, "Invalid input\n");
return 1;
}
}
sum = 0;
for (int i = 0; i < a; i++) {
sum = sum + array[i];
}
printf("Sum is %d\n", sum);
return 0;
}
If you want to handle larger arrays, you can allocate the array with malloc(), but you can also just compute the sum on the fly and not store the values read in an array:
#include <stdio.h>
int main() {
int a, value, sum;
printf("Insert length of array:\n");
if (scanf("%d", &a) != 1 || a < 0) {
fprintf(stderr, "Invalid input\n");
return 1;
}
sum = 0;
for (int i = 0; i < a; i++) {
printf("Insert number %d:\n", i + 1);
if (scanf("%d", &value) != 1) {
fprintf(stderr, "Invalid input\n");
return 1;
}
sum += value;
}
printf("Sum is %d\n", sum);
return 0;
}
This code is supposed to recieve to arrays and then call function to return them in 1 array but I don't know how to print the last array returned from the function thanks in advance ???
and now I write anything because it says that the post is mostly code :D :D
#include <stdio.h>
#include <stdlib.h>
int join_arrays(int *array1, int *array2, int arr1_size, int arr2_size);
int main() {
int size_arr1, size_arr2, i, num1 = 1, s;
printf("Please enter the size of the first array: ");
scanf("%d", &size_arr1);
int arr1[size_arr1];
printf("start fill your first array: \n");
for (i = 0; i < size_arr1; i++) {
printf("enter element number %d: ",num1);
scanf("%d", &arr1[i]);
num1++;
}
num1 = 1;
printf("Please enter the size of the second array: ");
scanf("%d", &size_arr2);
int arr2[size_arr2];
int *ptr1_last;
printf("start fill your second array: \n");
for (i = 0; i < size_arr2; i++) {
printf("enter element number %d: ", num1);
scanf("%d", &arr2[i]);
num1++;
}
ptr1_last = join_arrays(arr1, arr2, size_arr1, size_arr2);
printf("sorted array= \n");
for (s = 0; s < (size_arr1 + size_arr2); s++) {
printf("%d\n", ptr1_last);
}
return 0;
}
int join_arrays(int *array1, int *array2, int arr1_size, int arr2_size) {
int counter_arr1, counter_arr2, m = 0;
int last_arr[arr1_size + arr2_size];
for (counter_arr1 = 0; counter_arr1 < arr1_size; counter_arr1++) {
last_arr[counter_arr1]=array1[counter_arr1];
}
for (counter_arr2 = counter_arr1; counter_arr2 < (arr1_size + arr2_size); counter_arr2++) {
last_arr[counter_arr2] = array2[m];
m++;
}
return last_arr[0];
}
Modified the code to create the receiving array in main and pass a pointer to it to the merge function because the local array last_arr would no longer exist when the function returned in your code.
#include <stdio.h>
#include <stdlib.h>
//Prototype changed to include a pointer to the receiving array, also no longer returns a value.
void join_arrays(int *last_arr, int *array1,int *array2,int arr1_size,int arr2_size);
int main()
{
int size_arr1,size_arr2,i,num1=1,s;
printf("Please enter the size of the first array: ");
scanf("%d",&size_arr1);
int arr1[size_arr1];
printf("start fill your first array: \n");
for(i=0; i<size_arr1; i++)
{
printf("enter element number %d: ",num1);
scanf("%d",&arr1[i]);
num1++;
}
num1=1;
printf("Please enter the size of the second array: ");
scanf("%d",&size_arr2);
int arr2[size_arr2];
int *ptr1_last;
printf("start fill your second array: \n");
for(i=0; i<size_arr2; i++)
{
printf("enter element number %d: ",num1);
scanf("%d",&arr2[i]);
num1++;
}
int last_arr[size_arr1 + size_arr2]; //Create receiving array here
join_arrays(last_arr, arr1,arr2,size_arr1,size_arr2); //And pass it to the function.
printf("merged array= \n");
for(s=0;s<(size_arr1+size_arr2);s++)
{
printf("%d\n", last_arr[s]);
}
return 0;
}
void join_arrays(int *last_arr, int *array1,int *array2,int arr1_size,int arr2_size)
{
int counter_arr1, m=0;
for(counter_arr1=0; counter_arr1<arr1_size; counter_arr1++)
{
last_arr[counter_arr1]=array1[counter_arr1];
}
for(; counter_arr1<(arr1_size+arr2_size); counter_arr1++)
{
last_arr[counter_arr1]=array2[m];
m++;
}
}
With that function you return only the first element of the last_array, you should create a global array so it's visible in all functions, or return a pointer of the last_array[0] position in memory