I need help with this problem that I was given at my school. The problem is writen in Serbian, I'll try my best to translate it.
Write a program that enters n elements of a one-dimensional array and then displays their ordinal number, index and value (see test example)
The test example is in Serbian as well, but I think you can guess what do you need to do. Here is what I tried to do:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n,i,clan,broj=0,b,a;
a=1;
printf("Unesi broj elementa niza:\n");
scanf("%d", &n);
for (i=1;i<=n;i++)
{
printf("Unesi %d clan niza:\n", i);
printf("a[%d]=", broj);
broj++;
scanf("%d", &clan);
}
for (b=1;b<=n;b++)
{
printf("%d. clan niza je a[%d]=%d\n", a, b, clan);
a++;
}
return 0;
}
Everything works fine except that "clan" will only show as the latest entered number.
"...only the last entered number will be printed back at me, and I can't find a solution..."
Use an array.
The variable clan is not able to contain more than one int value at a time, however, the array variable int clan[n]; can hold up to n int values. Below is your code modified to accommodate n elements of a clan array using a VLA:
int main(void)
{
int n,i,broj=0,b,a;//remove clan
a=1;
printf("Unesi broj elementa niza:\n");
if(scanf("%d", &n) == 1)//test for success here, exit if fail
{
int clan[n];//use user input value to help create array of clan
for (i=0;i<n;i++)//array index is from 0 to n-1
{
printf("Unesi %d clan niza:\n", i);
printf("a[%d]=", broj);
broj++;
scanf("%d", &clan[i]);//modify to populate 1 element of clan array
}
for (b=0;b<n;b++)
{
printf("%d. clan niza je a[%d]=%d\n", a, b, clan[i]);//modify to oupput 1 element of clan array
a++;
}
}
else
{
printf("scanf() call failed. Exiting.");
}
return 0;
}
You are storing all your values into the same variable, clan. Of course, each assignment overwrites the previous value - it is one variable, not a stack.
Reading it five times in a loop gives each time that last value.
Related
I am trying to print all inputted number by the user using the code below but instead of printing all inputted numbers it only print the last number I inputted.
#include<stdio.h>
int display(int n, int a, int b)
{
printf("\n\nOrdered pairs are: ");
for(int j=0;j<n;j++)
{
printf("(%d,%d) ",a,b);
}
return 0;
}
int main()
{
int num,i,j,x,y;
printf("Total number of points: ");
scanf("%d",&num);
for(i=0;i<num;i++)
{
printf("\n\nPoint #%d: \n",i+1);
printf("x=");
scanf("%d",&x);
printf("y=");
scanf("%d",&y);
printf("Point #%d: (%d,%d)",i+1,x,y);
}
display(i,x,y);
return 0;
}
You don't have memory for storing more than 2 numbers (x and y) which are over-written during each iteration of the loop.
Perhaps you meant to use arrays, or dynamically allocated memory. This:
int x[100], y[100];
is one way, then you can store up to 100 numbers in each of the two arrays. Use array indexing when accessing.
Actually you are changing the value stored in x and y again and again and so, the previous values get destroyed and only the last value is stored. So you can you arrays (which are more easier to use) or you can even use structure (I would prefer to use arrays).
I am new to c ,while i am writing a basic program in c ,it is showing two answers ..1)when i declare and intialize variables separately 2)when I declare and initialize variable in a same line.can any one tell me my mistake please?
#include <stdio.h>
#include <stdlib.h>
void sum()
{
printf("enter the numbers to be added\n");
int x=scanf("%d",&x);
int y=scanf("%d",&y);
int sum=(x+y);
printf("the sum of two numbers is %d\n",sum);
}
int main()
{
printf("welcome to addition calculator\n");
sum();
return 0;
}
I am getting 2 as answer when i gave 3 and 4 as inputs
scanf("%d", &x) will store the read number into x. It will return the number of successfully read fields (1 in your case). If you assign that return value to x afterwards, you overwrite whatever the user entered with that 1. And 1 + 1 produce 2.
Solution:
int x;
int y;
scanf("%d",&x);
scanf("%d",&y);
As David reminds in comments, you might want to check that all fields were read successfully. For example, in your case, if you enter a non-digit, scanf will not resolve the %d field as successful, and will return 0. You can test this result to make sure the user did what they were supposed to do:
int x;
int y;
while (scanf("%d", &x) != 1) {
printf("Enter a NUMBER, you illiterate buffoon!\n");
}
while (scanf("%d", &y) != 1) {
printf("Enter a NUMBER! You managed with %d, how is this suddenly hard now?!\n", x);
}
scanf() function returns 1 if it scan successfully otherwise it return 0. That's why when you put an integer to x, scanf() return 1 and assign it to x(x=1). Same for y(y=1).
As x=1 and y=1.
sum = 2
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
I'm trying to write a program which includes an array that filled by user and find a value in it which specified by user then print if it found and count of that number in array.But it works only for first element of array.My code is below:
`void searchh(int arr[],int search,int number,int counter);
int main()
{
int number,search,i;
int counter=0;
printf("How many numbers will you enter?");
scanf("%d",&number);
int array[number];
for(i=0;i<number;i++){
printf("Please enter the %d. element of the array:",i+1);
scanf("%d",&array[i]);
}
printf("Please enter the number that you're looking for:");
scanf("%d",&search);
searchh(array,search,number,counter);
return 0;
}
void searchh(int arr[],int search,int number,int counter){
int i,c;
int key=search;
int num=number;
counter=0;
int arrsize=(int)(sizeof(arr)/sizeof(int));
int arrayent[(int)(sizeof(num)/sizeof(int))];
for(i=0;i<arrsize;i++)
{
if(arr[i]==key)
{
arrayent[counter]=i;
counter++;
}
}
printf("The number that you're looking for which is %d is found %d times.\nLocations:",key,counter);
if(counter>0){
for(c=0;c<sizeof(arrayent)/sizeof(int);c++){
printf("%d\n",arrayent[c]);
}
}
else
printf("Number doesn't exist!!");
}`
And Outputs:
Thanks for your helps.
int arrsize=(int)(sizeof(arr)/sizeof(int));
This already doesn't do what you think it does. sizeof(arr) - could be 4 if size of pointer is 4 bytes. In other words you can't check array size like that inside function, arr decays to pointer of first element of array. Hence sizeof(arr) will return size of pointer which could be 4 or 8. You need to pass the number of elements of the array to the function as parameter - which is number in your case.
This:
int arrayent[(int)(sizeof(num)/sizeof(int))];
is also strange. num is int. sizeof(num) and sizeof(int) will be same - and division will give you 1.
IMO these two lines
int arrsize=(int)(sizeof(arr)/sizeof(int));
int arrayent[(int)(sizeof(num)/sizeof(int))];
should just go as
int arrsize = number;
int arrayent[number];
PS. Also try to use a debugger to help you with some kind of issues.
I wrote this program, which returns the biggest integer inserted by the user. Now, I would like the program to return the 2nd biggest integer. I created a new variable (called "status"), which is supposed to increment 1 unit every time the cycle repeats. Then, after the break condition happens, I would step back 1 unit in status variable, in order to retrieve the 2nd biggest number. I would like to follow this line of thought (if it is reliable in C) and I ask you fellows what is wrong with my current implementation.
#include <stdio.h>
int main()
{
int x, tmp=0, status=0, bigger;
printf("Insert numbers:\n");
do{
status+=1;
scanf("%d", &x);
if (tmp>=x)
bigger=tmp;
else {
bigger=x;
tmp=x;
}
}while (x!=0);
status-=1;
printf("The second biggest number is %d.\n", bigger);
return 0;
}
If you need only two biggest integers, you can just save them in each iteration, such that you have the max and max2 values:
#include <stdio.h>
int main()
{
int x, max=0, max2=0;
printf("Insert numbers:\n");
do {
scanf("%d", &x);
if (x > max) {
max2 = max; // Save the previous max, as the second largest value
max = x ; // Save the new max
}
else if (x > max2) {
max2 = x; // The input is not max, but greater than second max
}
}while (x!=0);
printf("The second biggest number is %d.\n", max2);
return 0;
}
The status in your code is just a counter. To solve your problem :
Use an array to store all the data.
Make a variable and test it if it is different than the biggest and bigger than all other entries
try this :
int main()
{
int x, status=0, bigger=0, secondbigger=0, Array[50];
while(true){
scanf("%d",&x)
if(x==0)break;
Array[status]=x;
status++;
}
for(i=0;i<status-1;i++){
if(Array[i]>bigger) bigger=Array[i];
}
for(i=0;i<status-1;i++){
if(Array[i]>secondbigger && Array[i]!=bigger) secondbigger=Array[i];
}
printf("The second biggest number is %d.\n", secondbigger);
return 0;
}