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
Related
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.
I've tried so many different things but cant organize the structure properly to get the game actually working
I have the shell and functions layered out, but cant properly implement my defined functions into the sections where they are needed.
#define ROUNDS 3
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
void greeting();//display welcome message to user
int playRound(int round); //play one round
int humanPick(); //retrieve the user's guess
int computerPick(int choice, int leftover); //computer makes its pick
int leftOnTable(int toothpicks, int taken); //calculate number of toothpicks left
void winnerAnnouncment(int user); //overall winner of round announcement
int main()
{
void greeting();{
printf("Welcome to the Toothpick Game!\n");
printf("Here are the rules.\n");
printf("There are currently 31 toothpics on the table.\n");
printf("You and I will each get a turn to pick either 1, 2, or 3 toothpick off the table.\n");
printf("The player that gets to puck the last toothpicks looses the game!\n");
printf("Sounds easy right? Well lets see if you can beat me!\n");
printf("Ready to play?... Here we go!\n");
}
for(int x = 0; x < ROUNDS; ++x)
{
int result = playRound(x + 1); //call playRound and assign result the value function returns
void winnerAnnouncement(int user){
if (user == )
}
}
printf("********************************************************\n");
printf("Thank you for playing!\n");
return 0;
}
int playRound(int round)
{
printf("Welcome to a new round %d!\n", round);
printf("You may go first!\n");
int toothpicks = 31; //number of toothpicks to start with
//int taken;
int leftOnTable(int toothpicks, int taken);{
int taken;
while(toothpicks > 0){
toothpicks = toothpicks - taken;
return toothpicks;
}
}
//loop that keeps track of toothpicks until respective no more toothpicks left.
while(toothpicks != 0)
{
printf("There are currently %d toothpicks left.\n", toothpicks);
printf("How many toothpicks are you going to take off the table?");
printf("Pick a number between 1 , 2 , and 3.\n");
scanf("%d", &userChoice);
int humanPick()
{
if (userChoice >= 1 && userChoice <= 3)
return userChoice;
if(userChoice < 1 || userChoice > 3)
return 0;
}
int computerPick(int choice, int leftover)
{
if (toothpicks > 4)
choice = 4 - leftover;
if (toothpicks = 2 || 3 || 4)
choice =
if (toothpicks = 1)
choice = toothpicks;
}
return toothpicks; //terminates loop
}
return 0;
}
You do not want to be defining functions inside of other functions. Although some compilers allow that as an extension, it is not part of the language. But, even if you are using a compiler that allows it, your syntax is wrong. Consider:
int leftOnTable(int toothpicks, int taken);{
int taken;
while(toothpicks > 0){
toothpicks = toothpicks - taken;
return toothpicks;
}
In the body of another function, the semi-colon after int taken) ends the declaration of the function, and the {...} after that is not a function definition but is just a block of commands to be executed in the enclosing function. You want to write this (outside of any enclosing function) as:
int
leftOnTable(int toothpicks, int taken)
{
...
}
and then call it as:
int
main(void)
{
...
int toothpicks = 31;
int taken = humanPick();
...
toothpicks = leftOnTable(toothpicks, taken);
...
}
Your attempt to define humanPick() seems incorrect. Getting user input is notoriously difficult, and scanf is almost always the wrong tool. (See http://sekrit.de/webdocs/c/beginners-guide-away-from-scanf.html). By "almost always", I am being conservative and I actually mean that it is absolutely never the right choice. But, if you want to use scanf, you might try something like:
int
humanPick(int toothpicks)
{
int userChoice;
printf("There are currently %d toothpicks left.\n", toothpicks);
puts("How many toothpicks are you going to take off the table?");
puts("Pick a number between 1, 2 and 3.");
int rv;
while( 1 != (rv = scanf("%6d", &userChoice))
|| userChoice > 3 || userChoice < 1 )
{
char *msg = "Invalid input.";
switch( rv ){
case EOF:
puts("Terminating. Thanks for playing!");
exit(0);
case 1:
msg = "Choice must be 1, 2, or 3";
/* Fall thru */
default:
fprintf(stderr, "%s. Try again\n", msg);
while( (rv = getchar()) != EOF && rv != '\n' ){
;
}
}
}
return userChoice;
}
Be aware that this function changes the function prototype, and this version take toothpicks as a parameter.
Note two things about the usage of scanf here that are absolutely essential. You must always check the value returned by scanf, and you must always use a width modifier on the conversion specifier in the format string. If you do not understand what this means, you should stop using scanf. Without a width modifier, the behavior is undefined for certain inputs. Note that using a width modifier on %d means that you cannot reliably scan the full range of values that can be stored in an integer, and this is just one more reason to avoid using scanf.
"but cant organize the structure properly"
This section will work the way you have it, but I would place the #define below the #includes:
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
#define ROUNDS 3
Your prototype section looks okay, but its idiomatic in declarations to use (void) rather than ()
void greeting(void); //display welcome message to user
int playRound(int round); //play one round
int humanPick(void); //retrieve the user's guess
int computerPick(int choice, int leftover); //computer makes its pick
int leftOnTable(int toothpicks, int taken); //calculate number of toothpicks left
void winnerAnnouncment(int user); //overall winner of round announcement
The highest number of compile errors have to do with using nested functions. The C language does not support them, and it is not a good idea IMO to use extensions that allow them. The form of the program should be shaped like this:
int main(void)
{
// declare variables and call functions here
greeting();
//other constructs & function calls here.
return 0;
}
//Functions definitions should include 1 definition for each prototype:
void greeting(void)
{
printf("Welcome to the Toothpick Game!\n");
printf("Here are the rules.\n");
printf("There are currently 31 toothpics on the table.\n");
printf("You and I will each get a turn to pick either 1, 2, or 3 toothpick off the table.\n");
printf("The player that gets to puck the last toothpicks looses the game!\n");
printf("Sounds easy right? Well lets see if you can beat me!\n");
printf("Ready to play?... Here we go!\n");
}
int playRound(int round)
{
//content here (but your current content has issues)
return something;
}
int humanPick(void)
{
//content here
return something;
}
int computerPick(int choice, int leftover)
{
//content here
return something;
}
...and so on.
Note also I see you are using = to do comparisons. = is an assignment operator, for example toothpicks = 2 means assign the value 2 to the variable toothpicks. If you want to check equality, then use ==, eg if(toothpicks == 2){do something}.
An additional general note about function implementation and usage. Functions are seen in different forms:
prototype - is a declaration in the code that instructs the compiler about the data type of the function, arguments and parameter list. example: int add(int a, int b);
definition - The signature of a function is presented in the same way as that of its prototype but includes {...} enclosures which contain the body of executable code the function is designed to execute during run-time. Example:
int add(int a, int b)
{
return a + b;
}
calling a function - When a function is called, its signature, including the decorations around its name are not shown, but instead contain objects that are of the same type as specified in the function formal signature. For example, inside main(), or some other function:
int sum = 0;
int a = 10;
int b = 20;
sub = add(a, b);
Keep in mind that syntax errors will always be flagged by a good compiler, and prevent an executable from being created. But the number and type of warning messages you see at compile time is settable, and depend to some extent on how you have your compiler set. Setting the warnings on your compiler to a strict enough setting will output messages to warn of syntax errors, or possible mis-use of operators, or regarding function definition / usage and often suggest how to correct. if using GCC for example set compiler to use -Wall.
#include <stdio.h>
int playerscores() //function asking how many points each player has
{
// int p; //player number we are on
// p++; //since player number starts on zero, add one to print player #1
int n;
n++;
printf("how many points does player %d have?\n", n);
scanf("%d", &n); //asking how many points and writing to variable n
return n; //output variable n
}
int main()
{
int n; //numberof players
int scoret = 0; //score total
printf("How many players are on your team?\n");
scanf("%d", &n); //asking number of players
int score[n]; // integer array to store player scores
int a = 1; //starting number for loop, indicating to start on player 1
while(a <= n)
{
score[a-1] = playerscores(); //calling function and define array at position b as equal to function output
printf("%d", score[a-1]); //me trying to trouble shoot
a++; //next player
scoret = scoret + score[a-1]; //adding up scores thus far
printf("%d", scoret); //more of me attempting to trouble shoot
}
return scoret; //final score
}
I'm just getting into coding and trying to learn on my own, using codesdope.com. I am on the array section now. I like to write a little bit of custom code just to familiarize my self but i can't seem to figure this one out. Every time i run this, the output is some crazy big number, looks like it is the address rather than the value. I don't think i ever call the address at any point but i'm not sure what else i could be doing wrong. Thanks for your alls help!
There biggest issues I see here:
1) As already mentioned the local variable p / n. As you make the declaration within the function body, this variable will be initialized every time you call that function, so it will not remember the current value. Additionally, you don't initialize the variable with a value, means it could be 0 when you call it, but also any other number.
2) The issue with the big number comes from the order of the commands you execute. When you execute your loop the first time, you store your result in score[a-1] which is score[0]. Now your issue: you increase a by 1, and afterwards you add the score to your global score, which results in scoret = scoret + score[1]. As you didn't initialize or assign something to score[1], you don'T know what'S inside, it may be 0, but maybe also 13567325.
One possibility to implement your functionality would be:
#include <stdio.h>
int playerscores(int n) //function asking how many points each player has
{
int p = 0; //variable storing the points
printf("how many points does player %d have?\n", n+1);
scanf("%d", &p); //asking how many points and writing to variable p
return p; //return p for the points
}
int main()
{
int n = 0; //number of players
int scoret = 0; //score total
printf("How many players are on your team?\n");
scanf("%d", &n); //asking number of players
int score[n]; // integer array to store player scores
// using a for loop -> don't need to worry about incrementing the index
for (int a = 0; a < n; a++)
{
score[a] = playerscores(a); //calling function and define array at position a
scoret += score[a]; //adding up scores thus far
}
printf("Total score: %d\n", scoret);
return scoret; //final score
}
In
printf("%d", score[a-1]); //me trying to trouble shoot
a++; //next player
scoret = scoret + score[a-1]; //adding up scores thus far
you need to change the order of the lines
printf("%d", score[a-1]); //me trying to trouble shoot
scoret = scoret + score[a-1]; //adding up scores thus far
a++; //next player
or change the index
printf("%d", score[a-1]); //me trying to trouble shoot
a++; //next player
scoret = scoret + score[a-2]; //adding up scores thus far
Side note: if you don't need the side effect of post-fix operator++ (as in a++), then use the prefix variant (as in ++a).
I've just changed the ordering of scoret variable, hope this code will work the way you want it to.
#include <stdio.h>
int playerscores(int curr_player) //function asking how many points each player has
{
int p = curr_player; //player number we are on
int curr_score = 0;
// p++; //since player number starts on zero, add one to print player #1
printf("how many points does player %d have?\n", p);
scanf("%d", &curr_score); //asking how many points and writing to variable n
return curr_score; //output variable n
}
int main()
{
int n; //numberof players
int scoret = 0; //score total
printf("How many players are on your team?\n");
scanf("%d", &n); //asking number of players
int score[n]; // integer array to store player scores
int a = 1; //starting number for loop, indicating to start on player 1
while(a <= n)
{
score[a] = playerscores(a); //calling function and define array at position b as equal to function output
printf("%d", score[a]); //me trying to trouble shoot
scoret += score[a]; //adding up scores thus far
a++;
}
printf(" %d", scoret); //more of me attempting to trouble shoot
return scoret; //final score
}
In the lines:
a++; //next player
scoret = scoret + score[a-1]; //adding up scores thus far
you were incrementing a to the next position in the memory before adding it to scoret and the next position seems to hold garbage values that was showing up every time in your
printf("%d", score[a-1]); //me trying to trouble shoot
line
a.) (function 1) take user input and decrement the value until userNum = zero
b.) (function 2) take the original user input and have zero increase by +1 until reaching said user input.
therefore, the output would look like this:
Please enter a positive integer: 5 (enters 5)
5
4
3
2
1
0
(four asterisks)
0
1
2
3
4
5
My problem is, I cant figure out how to set the original input for userNum in place so I can all it in the "loop_up_to_int" function. Any help would be appreciated, thank you.
#include <stdio.h>
int loop_down_to_zero(void);
int loop_up_to_int(void);
int main(int argc, char * argv[])
{
int userNum;
printf("Please enter a positive integer: ");
scanf("%d", &userNum);
//printf("%d\n", userNum);
loop_down_to_zero();
loop_up_to_int();
return 0;
}
//definitions here
int loop_down_to_zero() {
//scanf("%d", &userNum); do i scan for input here?
while (userNum >= 0) {
printf("%d\n", userNum);
userNum = userNum - 1;
}
printf("****\n");
}
int loop_up_to_int() {
int newNum;
int userNum;
newNum = 0;
printf("%d\n", newNum);
while (newNum != userNum)
{
newNum = newNum + 1;
printf("%d\n", newNum);
}
}
error message:
daily08.c:58:14: error: 'userNum' undeclared (first use in this function)
while (userNum >= 0) {
Your error message is because userNum doesn't exist in the function. It's only declared in main. Passing values is the solution.
You can pass values into functions (a core idea behind programming; variables shouldn't be global). Similar to how main has int in it's declaration; update both your functions to take a variable:
int loop_down_to_zero(int number)
Don't forget to update the function definition on top of your program also.
And you call the function by simply saying loop_down_to_zero(userNum). What you entered can now be accessed via number in each function, and userNum will stay intact in main().
Side note: When functions are done, they can return a value back to the caller. In your case you don't do that (nor do you need to). Both your functions should show they don't return anything, which is marked by using void i.e. void loop_down_to_zero(int number). Again remember to update the top of your program also.
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.