I've started learning C. I'm doing functions right now.
In these exercise they want me to ask for a value that means an error. If they input the number 8, it means that it's error "8", if value 6 error is "6"(the error part don't matter). I should call a fuction to store this error and other functio to go trought it and see if any value ("error"), Was stored more than once.
I started by asking for how many errors the user will introduce, soo I could run a loop "N" times to ask for the value.
Then I made a function called aviso(means warning ~ error), to store them in a array.
When the function reaches the last value of "error" it calls other function to count if the numbers are repeated .
My main problem right now is how to store the values in the array and keeping them. Every time I introduce a value in the array it happear other like: array[0] = 7 the output is like array[0] = -32134123.
So my function is not storing any value in the array.
My code is very messy right now, please any suggestions are welcome since I'm clearly very new at C.
Excuse my code I just "try" to translate some names to english.
`
#include <stdio.h>
#include <stdlib.h>
// Function Incomplete since my array is not sotring values
int alertwarning(int array[]){
for(int i = 0; i < sizeof(array)/sizeof(int); i++){
}
}
int warning(int num , int n, int count){
int check = count - 1 , array[n];
if(count <= n){
array[check] = num;
}
if(count == n){
alertwarning(array);
for(int i = 0; i < sizeof(array)/sizeof(int); i++){
}
}
return 0;
}
int main(int argc, char *argv[]) {
int num, count, n;
printf("|Warning System!|(Only values equal or above 0 are acepted!)\n");
printf("\nIntroduce how many warnings are being stored: ");
scanf("%d", &n);
fflush(stdin);
int array[n];
do{
printf("\nIntroduce a value equal or bigger then 0: ");
scanf("%d", &num);
fflush(stdin);
//system("cls");
if(num < 0){
printf("|Please introduce a valuer equal or above 0!|\n");
system("pause");
}
else if(num >= 0){
count++;
}
warning(num, n, count);
}while( count < n);
return 0;
}
`
I tried to store the array inside the main() and it worked but it was required to do it in other function to complete this exercise. I don't know if the function just don't save the values of the last time it was called.
how to store the values in the array and keeping them. Every time I introduce a value in the array it happear other like: array[0] = 7 the output is like array[0] = -32134123.
So my function is not storing any value in the array.
I tried printf to see where I go wrong with the few knowledge I own. When they are called they work but the next time they are called I think they reset the values of the array.
Related
I have been coding the battleship game in C but I have a few problems. First of all, I would like to have a counter for the "hit and sunk" ships (it is coded, but it doesn't seem to work, after you hit a ship, it always prints 1), and therefore, this doesn't end the program when all ships are sunk. Here is my code for the main and "shoot" functions:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define rows 5
#define columns 5
int mainint main(){
srand(time(NULL));
int grid[rows][columns], attemps=0, ships;
int sunk;
printf("Let's play the battleship game!\n");
printf("You have 20 tries.\n");
printf("Enter the number of ships: ");
scanf("%d",&ships);
prepare_grid(grid); //Prepare grid with items of value -1
gen_ships(grid,ships); //Generate random ships surrounded by water (value 1)
print_grid(grid); //Print grid without showing the generated ships (all items will be "~" meaning "undiscovered water).
sunk=0;
for (int a=0;a<20;a++){
shoot(grid,sunk,ships);
attemps++;
print_grid(grid);
printf("\nAttemps: %d\n",attemps);
}
print_secret_grid(grid); //Print final grid, showing all sunk ships and positions shot
return 0;
}
void shoot(int grid[rows][columns], int sunk, int ships) {
int x, y;
printf("\nLine --> ");
scanf("%d", &x);
printf("Column --> ");
scanf("%d", &y);
do {
if (grid[x-1][y-1] == 1) {
grid[x-1][y-1] = 2; //We assign value 2 because we want to print only the ones the user hits, it will print X which means "hit and sunk".
sunk++;
printf("\nHit and sunk\n");
printf("Sunk ships:%d \n\n", sunk);
} else if (grid[x - 1][y - 1] == -1) { //It will print "*" which means "discovered water".
grid[x - 1][y - 1] = 0;
printf("\nMiss\n\n");
}
}while (sunk=!ships);
}
When using a function call in C, the value is passed by copy. This means that
int value = 0;
function(value);
printf("%d\n", value);
will always print the value 0, even if the function reads like
void function(int value) {
value++;
}
because within the function function, a copy of the int value is being incremented.
To fix this, pass a copy of the memory location of value, and then increment the number stored at that location.
int value = 0;
function(&value);
with
void function(int* value) {
(*value)++;
}
sunk is passed by value. It needs to be passed by reference. Send the pointer to sunk, and receive sunk as a pointer in the shoot function.
Alternatively, make sunk a global variable and increment it, although I'd not suggest this for bigger programs!
Read more about passing by value and passing by reference to prevent such things from happening in the future! :D
This a dot_product function of 2 vectors of the same length.
I don't understand how to build the array because how the machine will know which input goes to which input (for example i want a={1,2,3} but the input of 123 will come a[0]= 123)...
How do I make end of array[index] input and how do I make end of the whole array.
#include <stdio.h>
#include <stdlib.h>
#define MAXINPUT 100
int dot_product(int v[], int u[], int n)
{
int result = 0;
int i;
for (i=0; i < n; i++)
result += v[i]*u[i];
return result;
}
int main(){
int v1[MAXINPUT];
int v2[MAXINPUT];
int count = 0
int i,print;
printf(" first vector:");
for(i=0;i<MAXINPUT;i++){
scanf("%d", &v1[i]);
count +=1;
}
printf(" second vector:");
for(i=0;i<MAXINPUT;i++)
scanf("%d", &v2[i]);
print = dot_product(v1, v2, count);
printf("v1*v2:%d",print);
return 0;
}
The first problem I observe here is with
count +=1;
where count is an uninitialized automatic local variable, which makes it's initial value indeterminate. Attempt to use that value invokes undefined behavior.
You should be initializing count to 0.
That said, here, you're depending on the user to input the second array with exact same dimension of that of the first one. In case that does not happen, your program will blow up, as you did not initialize the arrays, again.
I'm trying to write a simple program that'll prompt the user to enter N numbers, store them in an array, then just sum them all up
I understand I can just do this with a recursion but I'm trying to learn how array works
Example:
1 (hit enter)
2 (hit enter)
...
10 (hit enter)
Expected output: 55
#include <stdio.h>
int main (void){
int n;
int a[n];
int counter;
printf("How many numbers do you want to enter? \n");
scanf("%d", &n);
printf("OK! now enter your number: \n");
for (int i = 0; i <= n; i++){
scanf("%d", &a[i]);
counter =+ a[i];
}
printf("The answer is: %d\n", counter);
return 0;
}
Right now there's no error message, no output, just the standard windows error message
"scanner.exe has stopped working..."
I'm using Win8 and GCC compiler
First of all, you can't create an static array without first knowing its size. You first need to ask the user for the "n" variable and then declare your array.
You also need to explicitly initialize your counter variable to be zero before you start counting. In C, variables don't default to 0 when you declare them.
The operator "=+" doesn't exist AKAIK, change it to "+=".
Last but not least, the limit in your loops is a little off, you're asking for 11 values ;)
(I edited this post, I was wrong about only asking for 9 values. I tend to confuse that sort of stuff)
#include <stdio.h>
int main (void){
int n;
int counter = 0;
printf("How many numbers do you want to enter? \n");
scanf("%d", &n);
int a[n];
printf("OK! now enter your number: \n");
for (int i = 0; i < n; i++){
scanf("%d", &a[i]);
counter += a[i];
}
printf("The answer is: %d\n", counter);
return 0;
}
You are using variable length arrays. At run time the value of n must be known. Place the declaration
int a[n];
after taking input for n, i.e, after scanf("%d", &n); and initialize counter to zero before using it otherwise you will get garbage value (because of undefined behavior).
Also change the for loop condition from i <= n to i < n.
After this line:
int n;
What do you think the value of n is?
Now go to the next line:
int a[n];
How big is this array?
Can you access it properly?
I have a class project to make an array, declare it's size (add 1) then fill it in numerical, nondecreasing order. After that, I need to declare x, a value to be added to the array in the appropriate spot, so the array is still nondecreasing.
The program builds without error (for once!) but I'm getting some really weird outputs.
#include <stdio.h>
int main (void) {
//Local Declarations
int size;
int ary[100];
int x;
int i;
int j;
//Statements
printf("Enter the size of the array: ");
scanf("%d", &size);
printf("\nEnter digits to fill the array, in numerical order: ");
for (i = 0; i < size; i++) scanf("%d", &ary[i]);
size++;
printf("\nInput x, the value to add to the array: ");
scanf("%d", &x);
while(i <= x && x > ary[i]){
i++;
j = size - 1;
while(j >= i) {
ary[j++] = ary[j];
j--;
}
}
for(i = 1; i < size; i++) {
printf("%d", &ary[i]);
}
return 0;
} //main
When it runs I get:
Enter the size of the array: 3
Enter digits to fill the array, in numerical order: 1
2
3
Input x, the value to add to the array: 4
268634426863482686352
Process returned 0 (0x0) execution time : 7.124 s
Press any key to continue.
I would examine your print function . It looks like you're printing the memory address of that particular array index rather than the value at that spot in the array.
Don't increase the size variable before you iterate through. Then walk backwards through the array, and populate as needed.
for (i = size; i >0; --i)
{
if (ary[i-1] > x)
{
ary[i] = ary[i-1];
}
else
{
ary[i] = x;
break;
}
}
if (i == 0)
ary[i] = x;
Afterwards, you can increase size as you print the output.
I've reproduced your desired output using this array walk.
There are other ways that I would solve this problem in real life, but this works well enough within your existing code.
First things first: what do you EXPECT to see as the output?
Second things first: you aren't clearing out the memory for the array before use. You have garbage values in any slots you aren't using.
Third things first: using GCC I'm seeing at least two warnings without even trying.
test.c:32:15: warning: format specifies type 'int' but the argument has type 'int *' [-Wformat]
printf("%d", &ary[i]);
test.c:27:14: warning: unsequenced modification and access to 'j' [-Wunsequenced]
ary[j++] = ary[j];
In your printing loop your are not printing the value but your are printing the address of that element. Change the last loop to
for(i = 1; i < size; i++) {
printf("%d", ary[i]);
}
I am not sure why your are printing the array from index 1. But if you want to print whole array you should initialize i to zero in above loop.
To me, my program looks like it should do what I want it to do: prompt a user to enter 10 values for an array, then find the largest of those values in the array using a function, then return the largest number to the main () function and print it out.
But, when I enter values, I never get numbers back that look anything like the ones I'm entering.
For example, let's say I enter just "10, 11" I get back "1606416648 = largest value".
Does anyone know what I'm doing wrong?
Here's the code:
#include <stdio.h>
#define LIMIT 10
int largest(int pointer[]);
int main(void)
{
int str[LIMIT];
int max;
int i = 0;
printf("Please enter 10 integer values:\n");
while (i < LIMIT)
{
scanf("%d", &str[i]);
i++;
}
// Thanks for your help, I've been able to make the program work with the above edit!
max = largest(str);
printf("%d = largest value\n", max);
return 0;
}
int largest(int pointer[])
{
int i;
int max = pointer[0];
for (i = 1; i < LIMIT; i++)
{
if (max < pointer[i])
max = pointer[i];
}
return max;
}
scanf("%d", &str[LIMIT]); reads in one number and puts it in the memory location one past the end of your array.
After changes:
You don't need scanf() in your while condition; it should go in the while body instead.
Your scanf() still isn't quite right. You need to tell it where in the array you want to store the input.
str[i]; doesn't do anything.
printf("Please enter 10 integer values:\n");
scanf("%d", &str[LIMIT]);
This doesn't do what you think. First, it only reads one number in. Second, you are reading it into the last position + 1 of the array.