I am having issues with my c program. I am new to C programming and I have to write a program for class involving arrays. I have to use two sets of arrays and allow the user to remove a location and add a new value into that spot. I created a max array of 20 but we have to use 1 thru 5 and allow the user to remove the value in either data set. Here is what I have currently and I am getting a lot of errors saying I have ; and { in the wrong spots but it doesn't seem wrong when I go back to my text book and slides about arrays. I created constant values under myarr1 and myarr2 and SIZE is set to 20. Any and all help is appreciated I don't understand why i am getting all these errors.
int display_arr(int * count);
int remove_arr();
int myarr1[SIZE];
int main() {
printf("Data confirmation and update program written in C.\n");
int display_arr[6];
// display_arr[0]=NULLL;
int counter = 6;
my_identity();
for (i = 0, i < SIZE; i++) {
myarr1[i] = counter;
}
for (i = 0, i < SIZE; i++)
printf("Array[%d] is %d.\n", i, myarr1[i];
return EXIT_SUCCESS;
}
// deleting entry from data
int remove_arr() {
int position;
printf("Enter the location where you wish to delete element\n");
scanf("%d", & position);
}
int display_arr(int * count) {
int i;
for (i = 0; i < * count; i++)
printf("%d", myarr1[i]);
return 0;
}
//add an entry to data set
// int myarr()
}
// int input;
// printf("Enter the value you would like to add to the end of the arry:");
// scanf("%d", &input);
// if (array_select == 1){ // adds value to data set 1
// myarr1[*counter] == input;
// else
// myarr2[counter] == input; // adds value to data set 2
//return 0;
}
}
Computer programming is about being precise. This means also following the rules exactly to the point, not more, not less.
In this case, I see two things
Parenthesis/braces/brackets must be balanced:
printf("Array[%d] is %d.\n", i, myarr1[i];
Do you see the missing parenthesis at the end?
Comma and semicolon are not the same:
for (i = 0, i < SIZE; i++) {
Do you see the first comma?
For the other problems, look at the compiler error messages.
Related
My task is to write a function unesi_niz which allows the user to enter array of real numbers (maximum 100) where the entry ends with entering the number -1. The array that is entered in this way should be written to the binary file niz.bin as values of type double. The file must not contain anything other than members of the string (so it must not contain the entered number -1).
Then write a srednja_vrijednost function that calculates the mean value of the numbers in the niz.bin file and returns it. If the file does not exist or is empty, 0 should be returned.
So i started like this:
#include <stdio.h>
#include <stdlib.h>
#define vel 100
int i = 0;
int j = 0;
void unesi_niz() {
double pomocna;
double niz[100];
while (i != 100) {
scanf("%lf", &pomocna);
if (pomocna != -1) {
niz[i] = pomocna;
i++;
} else
break;
}
FILE *ulaz = fopen("niz.bin", "w");
if (!ulaz) {
printf("Greska pri otvaranju.\n"); //opening fault
}
for (j = 0; j < i; j++) {
fwrite(niz, sizeof(double), j, ulaz);
}
fclose(ulaz);
}
double srednja_vrijednost() {
double suma = 0;
if (i == 0)
return 0;
FILE *ulaz = fopen("niz.bin", "r");
if (!ulaz) {
printf("Greska pri otvaranju.\n");//opening fault
return 0;
}
double niz[100];
fread(niz, sizeof(double), i, ulaz);
int j;
for (j = 0; j < i; j++) {
suma += niz[j];
}
fclose(ulaz);
return suma / i;
}
int main() {
unesi_niz();
double n=srednja_vrijednost();
printf("%g\n", n);
return 0;
}
My code has several problems. the first is the wrong return value of the function srednja_vrijednost, when I enter the values 5 10 15, the result is 1.6667, which is nonsense, and then many "Profiler errors", my debug console says Error in line 56, main.c file: The program accesses a variable that is not initialized, however I don't see any "Forbidden Action".
Hope some of you can see what I have done wrong :)
Your code fails in unesi_niz at these lines:
for (j = 0; j < i; j++) {
fwrite(niz, sizeof(double), j, ulaz);
}
fwrite takes a pointer to the data, the size of individual elements in bytes and the number of such elements. This means your code writes j elements starting from the first element each time. You probably want to write 1 element each time. Or better yet, you want to write all i elements, since fwrite allows you to write more than one element.
fwrite(nix, sizeof(double), i, ulaz);
As an aside, your "srednja_vrijednost" logic will work, but only because you already know the size of your array in the current process (stored in i). I am not entirely sure what you are trying to do but I suspect you want to be able to read the same file back even after your process exits. For that, you would need some logic to find the size of the array. You can do this either by writing the length as well into the file, or (similar to the input) write an ending -1, or just figure out the size by calculating the file size.
I'm looking for help with this question:
"Create an array of 10 ints called myArray. Give the array contents an initial value of 0 in the variable declaration. Create a loop to prompt the user and get revised values for all of the array elements, pressing ENTER after each of the 10 items. Within the loop, keep track of which element has the lowest value. After the loop is done, display the minimum element's index and value."
I am a new student. The code I made doesn't work but hoping someone can see the problem or what I'm missing. The getNum variable was made by our teacher for us to use.
I need help being able to output the smallest element with the variable associated with that element.
int main()
{
int getNum(void);
int sizeArray = 10;
int myArray[11] = {0,0,0,0,0,0,0,0,0,0};
int counter = 0;
int smallestNumber =0;
print("Enter 10 Integers:\n");
for (counter = 0; counter < sizeArray; counter++)
{
myArray[sizeArray] = getNum();
}
for (counter = 0; counter < sizeArray; counter++)
{
if(myArray[counter] < smallestNumber) {
smallestNumber = myArray[counter];
}
}
printf("Smallest number is %d, in Element %d. \n", smallestNumber, counter);
return 0;
}
#pragma warning(disable: 4996)
int getNum(void) {
char record[121] = {0};
int number = 0;
fgets(record, 121, stdin);
if( sscanf(record, "%d", &number) != 1){
number = -1;
}
return number;
}
You edited your code so I will provide the main problem with your original code for context.
You initially declared and defined your myArray as follows:
int myArray[] = {0};
As mentioned in the comments, the proper way to accomplish this is with:
int myArray[10] = {0};
Alternatively, you could have done it using a for loop as you attempted to initially with:
for(int i = 0; i < 10; i++)
{
myArray[i] = 0;
}
But, for such a simple task, the first way is much easier.
We shouldn't stop there, however. There are some simple ways to improve your code. Instead of hardcoding the size of the array AND having the sizeArray variable, why not do something like a define statement before your main function:
#define SIZE_ARRAY 10
This will allow you to do some useful things in your code that can be changed MUCH easier in the future:
int myArray[SIZE_ARRAY] = {0};
...
for (int i = 0; i < SIZE_ARRAY; i++) {} //Note also the change to 'int i'
Another thing is the counter variable. It is an additional variable that you don't need. You can just utilize the 'int i' as above in your loop. What if instead of having a counter variable AND a smallestNumber variable, you combine them into a single variable called something like this:
int smallestIdx = 0;
Then, in your for loop you could do something like this:
for(int i = 0; i < SIZE_ARRAY; i++)
{
myArray[i] = getNum();
if (myArray[i] < myArray[smallestIdx]){
smallestIdx = i;
}
}
And because you are only keeping track of the index of the smallest integer in your array, you could print like this:
printf("Smallest number is %d, in Element %d. \n", myArray[smallestIdx], smallestIdx);
I am trying to implement Insertion sort algorithm in C.
But all I get is SIGSEGV error in online IDEs and the output doesn't show up in Code::Blocks. How to avoid Such errors.
#include <stdio.h>
#include <stdlib.h>
int main()
{
/* Here i and j are for loop counters, temp for swapping
count for total number of elements,array for elements*/
int i, j, temp, count;
printf("How many numbers are you going to enter");
scanf("%d", &count);
int n[20];
printf("Enter %d elements", count);
// storing elements in the array
for(i = 0; i < count; i++) {
scanf("%d", n[i]);
}
// Implementation of insertion sort algorithm
for(i = 0; i < count; i++) {
temp = n[i];
j = i - 1;
while(temp < n[j]) {
n[j+1] = n[j];
j = j - 1;
}
n[j+1] = temp;
}
printf("Order of sorted elements");
for(i = 0; i < count; i++) {
printf("%d", n[i]);
}
return 0;
}
There are a couple of problems with your code. First of all, what is a SIGSEGV error? Well, it's another name for the good old Segmentation fault error, which is basically the error you get when accessing invalid memory (that is, memory you are not allowed to access).
tl;dr: change scanf("%d",n[i]); to scanf("%d",&n[i]);. You're trying to read the initial values with scanf("%d",n[i]);, this raises a segmentation fault error because scanf expects addresses in which put the values read, but what you're really doing is passing the value of n[i] as if it were an address (which it's not, because, as you did not set any value for it yet, it's pretty much just memory garbage). More on that here.
tl;dr: change int n[20]; to int n[count]. Your array declaration int n[20]; is going to store at most 20 integers, what happens if someone wants to insert 21 or more values? Your program reserved a certain stack (memory) space, if you exceed that space, then you're going to stumble upon another program's space and the police (kernel) will arrest you (segmentation fault). Hint: try inserting 21 and then 100 values and see what happens.
tl;dr: change for(i = 0; i < count; i++) { to for(i = 1; i <= count; i++) {. This one is a logic problem with your indexes, you are starting at i = 0 and going until i = count - 1 which would be correct in most array iteration cases, but as j assumes values of indexes before i, you need i to start from 1 (so j is 0, otherwise j = -1 in the first iteration (not a valid index)).
My final code is as follows. Hope it helped, happy coding!
#include <stdio.h>
#include <stdlib.h>
int main() {
/*Here i and j are for loop counters,temp for swapping
count for total number of elements,array for elements*/
int i, j, temp, count;
printf("How many numbers are you going to enter?\n");
scanf("%d",&count);
int n[count];
printf("Enter %d elements\n",count);
//storing elements in the array
for(i = 0; i < count; i++) {
scanf("%d", &n[i]);
}
//Implementation of insertion sort algorithm
for(i = 1; i <= count; i++) {
temp = n[i];
j = i-1;
while(temp < n[j]) {
n[j+1] = n[j];
j--;
}
n[j+1] = temp;
}
printf("Order of sorted elements\n");
for(i = 0; i < count; i++) {
printf("%d\n",n[i]);
}
return 0;
}
Edit: If you're having trouble with online IDEs, consider running your programs locally, it saves a lot of time, plus: you never know what kernel version or magic the online IDEs are using to run your code (trust me, when you're coding in C -- fairly low level language, these things make a difference sometimes). I like to go all root style using Vim as text editor and gcc for compiling as well as gdb for debugging.
I have written the following code. But it doesn't run until the final printf. Plus if the validation I have set fails to pass, it prints a result I can't explain.
#include <stdio.h>
int main(void)
{
int k, j, z, i, n;
int l[30];
// Setting initial values 0 (0=off 1=on)
for (n=0; n<30; n++)
{
l[n] = 0;
}
// Employee number
printf("give employee number\n");
scanf("%d", &k);
// Validation of k
if (k<0 || k>30)
{
printf("wrong input");
}
else
// Lamp status change
for (i=1; i=k; i=i+1)
{
for (z=i; z=30; z=2*z)
{
if (l[z] = 0)
l[z] = 1;
else
l[z] = 0;
}
}
for (j=0; j<30; j++);
{
printf("lamp[%d] is: %d\n", j+1, l[j]);
}
return(0);
}
I suggest that you go work a little more your C basis...
First advice: As reported by halfer you should take care of your indentation code, it allows you (and us) to read it more easily.
First error, also pointed out by halfer: You probably forgot to declare a
block of code with {}, tips for your research to know when to put
it here.
Second error: You should take a look at the for loop syntax: for (j=0; j<30; j++);will basically do nothing due to ;at the end.
You confuse assignment and condition test, if (l[z]=0), for (i=1; i=k; i=i+1) and for (z=i; z=30; z=2*z) haven't condition test, but assignment (just = and not == or <=, etc.) so they are always true...
Also, you don't explain what you want your code to do... It seems like you want to turn on some lights, but the double statement loop with the wrong for is confusing. I don't know if you want to turn on 2^N bulbs or just the one selected by the user... Here is my correction of your code:
int main(void) {
int k, j, z, i, n;
int l[30];
// Setting initial values 0 (0=off 1=on)
for (n=0; n<30; n++) {
l[n] = 0;
}
// Employee number
printf("give employee number\n");
scanf("%d", &k);
// Validation of k
if (k<0 || k>30) {
printf("wrong input");
} else { // New block
// Lamp status change
/*
i = k is an assignment not a test, maybe i == k ?
but still false, for do while the condition is true
so use <= and why use i = i+1 here and not i++ like for n++ L6 ?
Ok for this loop, but with the other you gonna reswitch again and
again. If you want only switch the one selected, consider to use
an if instead of the 2nd for loop.
*/
for (i=1; i <= k; i=i+1) {
/*
Same test / assignment misunderstanding.
personally except 15, I don't know a lot of intergers
mutiplied by 2 that give 30. Example: if I set 1 in
my keyboard, k = 1, then i = 1, z = 1, z = 2,z = 4,
z = 8,z = 16, z = 32, z = 64, etc. to overflow.
So z = 30 (ouch z == 30) is never true.
If you tried to switch only the lamp selected by the user
I don't see the point of the second for loop.
But if you wanted to switch 1 light each 2^N bulbs you
should set z <= 30.
*/
for (z=i; z<=30; z=2*z) {
if (l[z] == 0) // = is an assignment, == instead?
l[z] = 1; // A block with {} is not needed here because there is only 1 instruction
else
l[z] = 0; // Same as above, {} are not needed here too
}
}
for (j=0; j<30; j++) { // No; here, see the 'for' loop syntax
printf("lamp[%d] is: %d\n", j+1, l[j]);
}
} // End of the else block
return(0);
}
I have an array of integers and I'm trying to find which one is the highest and set a new integer to the highest ones value. I'm very new to C, I literally just started learning it.
There is probably some kind of logical problem with what I'm doing but I haven't been able to spot it yet. so...
int my_array[4];
int highest_int = 0;
int i;
for (i = 0; i < 4; i++) {
if (my_array[i] > my_array[i++]) {
if (my_array[i] > highest_int) {
highest_int = my_array[i];
}
}
else {
if (my_array[i++] > highest_int) {
highest_int = my_array[i++]
}
}
}
So I loop through my array 4 times (4 elements) and I look at the iteration value and the next one and if the iteration value is highest I check it's also higher than the current value of the current 'highest integer' and if it is I set the current highest integer to the new highest value. If the value after the iteration value is higher I do the same thing but with that value instead.
That's what went through my head when I wrote this but when I enter 4 values it always comes out with the 3rd value in the array. No matter what I set those values to.
Can anyone tell me why?
Thanks a lot.
Why you are incrementing i inside the loop? Why do you need the else part?
Here's a simple way:
int my_array[4];
int highest_int = my_array[0];
int i;
for (i = 1; i < 4; i++) {
if (my_array[i] > highest_int) {
highest_int = my_array[i];
}
}
You're making this way more complicated than it really is :) Furthermore, you're writing i++ in too many places; each time i++ gets executed you're skipping over an array entry, which is probably not what you want.
Also, there's no need to compare to the previous value. Just compare to the highest one you've seen so far.
Here's a fixed version, just by deleting code, nothing changed or added:
int my_array[4];
int highest_int = 0;
int i;
for (i = 0; i < 4; i++) {
if (my_array[i] > highest_int) {
highest_int = my_array[i];
}
}
Note that this incorrectly reports 0 if all numbers in the array are negative. Start off highest_int = INT_MIN in case you need to handle those correctly, or use unsigned int.
If you are trying to find the highest number, here is the code:
int my_array[4];
int highest_int = my_array[0];
//Before entering the loop, assuming the first number to highest
int i;
for (i = 1; i < 4; i++) {
if (my_array[i] > highest_int) { //Compare every number with highest number
highest_int = my_array[i];
}
}
//Now we have the highest number
printf("Highest Number: %d",highest_int);