Strange error with a For loop in C - c

int main(void)
{
const char * attributeNames = "StrDexConIntWisCha";
int characterValues[7] = {0};
int characterBonuses[7] = {0};
characterStats(characterValues);
}
void characterStats(int * characterValues)
{
int numberOfDice = 4; int diceType = 6;
int x = 1;//because characterValues[0] is level.
printf("What is your level? > ");
scanf("%d",&characterValues[0]);
printf("Current Level [%d]", characterValues[0]);
printf("Rolling stats.\n");
for(x; x <= numberOfDice; x++)
{
characterValues[x] = diceRoll(diceType);//rolling a d6
}
}
int diceRoll(int diceType)
{
int numberOfDice = 4;
int x,y,z = 0;
int diceResult, finalValue, lowestResult = 0;
int diceRoll[4] = {0};
for(x; x <= numberOfDice; x++)
{
printf("%d", diceRoll[x]);
}
}
I'm trying to create a function that will roll a 6-sided dice, 4 times, for a character generator for dungeons and dragons. The last for loop in diceRoll, doesn't appear to execute, it just skips it over and I don't understand why. At the moment, I'm just testing to see if everything works before adding in the rand().

int x,y,z = 0;
Here you only initialized z to 0, leaving x and y uninitialized, and then in the for loop:
for(x; x <= numberOfDice; x++)
Again, x is not initialized.

You should always initialize your loop counter in the for loop:
for(x=0; x<numberOfDice; x++)
and too, notice I used < not <=; a loop from 0 will always do n iterations from 0 for <n (using <= will do n+1). Looping from 0 to n-1 is idiomatic in all C-like languages since it tends to match things like indexes an an array being iterated, or pointer manipulations, which are all 0-based.

either make
int x=0,y,z=0;
or make
for(x = 0; x <= numberOfDice; x++)

Related

Efficiently print every x iterations in for loop

I am writing a program in which a certain for-loop gets iterated over many many times.
One single iteration doesn't take to long but since the program iterates the loop so often it takes quite some time to compute.
In an effort to get more information on the progress of the program without slowing it down to much I would like to print the progress every xth step.
Is there a different way to do this, than a conditional with a modulo like so:
for(int i = 0; i < some_large_number; i++){
if(i % x == 0)
printf("%f%%\r", percent);
//some other code
.
.
.
}
?
Thanks is advance
This code:
for(int i = 0; i < some_large_number; i++){
if(i % x == 0)
printf("%f%%\r", percent);
//some other code
.
.
.
}
can be restructured as:
/* Partition the execution into blocks of x iterations, possibly including a
final fragmentary block. The expression (some_large_number+(x-1))/x
calculates some_large_number/x with any fraction rounded up.
*/
for (int block = 0, i = 0; block < (some_large_number+(x-1))/x; ++block)
{
printf("%f%%\r", percent);
// Set limit to the lesser of the end of the current block or some_large_number.
int limit = (block+1) * x;
if (some_large_number < limit) limit = some_large_number;
// Iterate the original code.
for (; i < limit; ++i)
{
//some other code
}
}
With the following caveats and properties:
The inner loop has no more work than the original loop (it has no extra variable to count or test) and has the i % x == 0 test completely removed. This is optimal for the inner loop in the sense it reduces the nominal amount of work as much as possible, although real-world hardware sometimes has finicky behaviors that can result in more compute time for less actual work.
New identifiers block and limit are introduced but can be changed to avoid any conflicts with uses in the original code.
Other than the above, the inner loop operates identically to the original code: It sees the same values of i in the same order as the original code, so no changes are needed in that code.
some_large_number+(x-1) could overflow int.
I would do it like this:
int j = x;
for (int i = 0; i < some_large_number; i++){
if(--j == 0) {
printf("%f%%\r", percent);
j = x;
}
//some other code
.
.
.
}
Divide the some_large_number by x. Now loop for x times and nest it with the new integer and then print the percent. I meant this:
int temp = some_large_number/x;
for (int i = 0; i < x; i++){
for (int j = 0; j < temp; j++){
//some code
}
printf("%f%%\r", percent);
}
The fastest approach regarding your performance concern would be to use a nested loop:
unsigned int x = 6;
unsigned int segments = some_large_number / x;
unsigned int y;
for ( unsigned int i = 0; i < segments; i++ ) {
printf("%f%%\r", percent);
for ( unsigned int j = 0; j < x; j++ ) {
/* some code here */
}
}
// If some_large_number canĀ“t be divided evenly through `x`:
if (( y = (some_large_number % x)) != 0 )
{
for ( unsigned int i = 0; i < y; i++ ) {
/* same code as inside of the former inner loop. */
}
}
Another example would be to use a different counting variable for the check to execute the print process by comparing that to x - 1 and reset the variable to -1 if it matches:
unsigned int x = 6;
unsigned int some_large_number = 100000000;
for ( unsigned int i = 0, int j = 0; i < some_large_number; i++, j++ ) {
if(j == (x - 1))
{
printf("%f%%\r", percent);
j = -1;
}
/* some code here */
}

Coast length, kattis

I'm trying to solve one problem, which I found on website https://open.kattis.com/problems/coast. Tl;dr version of problem is, that for given map of landscape, I should print out length of coastline (without inner islands).
I receive 0/26 mark, but I have no idea why, I've tested, and as far as i checked, it worked. I assume it doesn't compile, but if that is the case, why is that? It compiles for me perfectly fine.
#include <stdio.h>
int edgeCount(int, int, char*);
int topToBottomCount(int, int, char*);
int leftToRightCount(int, int, char*);
int removingInsides(int, int, char*);
int main()
{
int n = 0; // number of strings
int m = 0; // strings lenghts
//printf("Enter N(number of strings) x M(strings lenght): ");
scanf("%d", &n);
scanf("%d", &m);
char coast[1024];
for(int i = 0; i < n; i++){
scanf("%s", coast+i*m); // adding strings to char coast[1024], making array of ones and zeroes // e.g we are adding 3x4 strings - 111100001111
} // it can also be looked as 1111
// 0000 - matrix
int coasts = edgeCount(n, m, coast); // 1111
coasts += topToBottomCount(n, m, coast);
coasts += leftToRightCount(n, m, coast);
coasts -= removingInsides(n, m, coast);
printf("%d - coasts\n", coasts);
return 0;
}
int edgeCount(int n, int m, char *coast){ // if 1 is placed at the edge of the "map", it is 1 coast (2 if it is at corner)
int edgeCoast = 0;
for(int i = 0; i < m; i++){ // top edges
if(coast[i] == '1')
edgeCoast++;
}
for(int i = m*n - m; i < m*n; i++){ // bottom edges (m*n - m = first char in the last string, it can be also looked as the last row in matrix)
if(coast[i] == '1')
edgeCoast++;
}
for(int i = 0; i <m*n; i+=m){ // left side edges (first column in matrix)
if(coast[i] == '1')
edgeCoast++;
}
for(int i = m-1; i < m*n; i+=m){ // right side edges (last column in matrix)
if(coast[i] == '1')
edgeCoast++;
}
return edgeCoast;
}
int topToBottomCount(int n, int m, char *coast){
int coasts = 0;
for(int i = 0; i < m*n - m; i++){ // we start from first char in "matrix", and move to the (m*n - m = 2nd last "row")
if(coast[i] ^ coast[i+m]) // we are checking if zero is placed above one or via versa
coasts++;
}
return coasts;
}
int leftToRightCount(int n, int m, char* coast){
int coasts = 0;
int p = m-1;
for(int i = 0; i < n*m; i++){ // we start from the first charr, and we are going trough whole matrix, but the last column
if(i == p){ // p = m - 1 (last char in first row)
p+=m; // p+=m (last char in next column, and so on)
continue; // we move to next iteration
}
if(i == m*n - 1) //if we are at last char in matrix, we break out from loop
break;
if(coast[i] ^ coast[i+1])
coasts++;
}
return coasts;
}
int removingInsides(int n, int m, char* coast){ // Lakes and islands in lakes are not contributing to the sea coast. we are checking if they exist.
int innerCoasts = 0;
for(int i = m + 1; i < n*m - m - 1; i ++){
if( coast[i] == '0' && coast[i] ^ coast[i-1] && coast[i] ^ coast[i+1] && coast[i] ^ coast[i-m] && coast[i] ^ coast[i+m]) // char has to be 0, and to hist left, right, above and under there has to be 1
innerCoasts++;
}
return innerCoasts * 4; // *4 because we added 4 coasts before for each island.
}
I tried compiling your code using the GCC C++ compiler (4.9.2). It compiled fine and I tested it using the sample problem in the link you provided. It spit out the right answer.
However, when I tried compiling using the GCC C compiler (also v 4.9.2), it fails with 'for' loop initial declarations are only allowed in C99 or C11 mode, which is explained by this SO question. I think your assignment was graded using a C compiler and the compilation of your program failed due to this error.

C arrays and loops

I'm new to C and I got an assigment from school to calculate some stuff, but when I run the program nothing shows up, can anyone figure out what's wrong with this?
#include <stdio.h>
void main()
{
int arr[]= {3,6,18,12,15,30,60,70,11,10};
int rt,i,x;
for (i = 0;i >= 10; i++)
rt += arr[i];
for (x = 0;x >= 10; x++)
{
printf("The value of resistor at location %d is %d\n",i,arr[i]);
printf("The value of the RT is %d\n",rt);
}
}
Your for loop conditions to exit the loop are wrong. Specifically, i should be < 10 not >= 10. When i = 0, the loop immediately terminates because it isn't >= 10. As such, you need to modify your code so that it's < 10. The reason why is because C starts at index 0 when referencing an array, and you have 10 elements in your array. Also, rt looks like an accumulator variable, and so you'll also need to set this to 0 before looping.
Another small but fundamental bug in your code is the second for loop. Specifically, your increment variable is x, but you are using i within the for loop. As such, either change the variables within the for loop to x, or change the loop index so that it is i and not x. I did the former.
Another small suggestion I have is to place the printf statement that displays the rt variable outside of the for loop. This variable never changes during each iteration, and so it is safe to assume that you only want to display it once.
As such:
#include <stdio.h>
void main()
{
int arr[]= {3,6,18,12,15,30,60,70,11,10};
int rt,i,x;
rt = 0; // As you are accumulating values
for (i = 0; i < 10; i++)
rt += arr[i];
for (x = 0; x < 10; x++)
printf("The value of resistor at location %d is %d\n",x,arr[x]);
printf("The value of the RT is %d\n",rt);
}
The statement
for (x = 0;x >= 10; x++)
should be
for (x = 0;x < 10; x++)
otherwise it will never execute since first x is assigned zero, then you check if x >= 10.
Right off the bat? Your for loop condition is not correct, it's backwards.
for (i = 0;i >= 10; i++)
should be:
for (i = 0;i < 10; i++)
Your for loop should be testing x<= 10.

Converting an int array to an int value in c

I have an integer array
int number[] = {1,2,3,4};
What can I do to get int x = 1234?
I need to have a c version of it.
x = 1000*number[0] + 100*number[1] + 10*number[2] + number[3];
This is basically how decimal numbers work. A more general version (when you don't know how long 'number' is) would be:
int x = 0;
int base = 10;
for(int ii = 0; ii < sizeof(number); ii++) x = base*x + number[ii];
Note - if base is something other than 10, the above code will still work. Of course, if you printed out x with the usual cout<<x, you would get a confusing answer. But it might serve you at some other time. Of course you would really want to check that number[ii] is between 0 and 9, inclusive - but that's pretty much implied by your question. Still - good programming requires checking, checking, and checking. I'm sure you can add that bit yourself, though.
You can think of how to "shift over" a number to the left by multiplying by ten. You can think of appending a digit by adding after a shift.
So you effectively end up with a loop where you do total *= 10 and then total += number[i]
Of course this only works if your array is digits, if it is characters you'll want to do number[i] - '0' and if it is in a different base you'll want to multiply by a different number (8 for instance if it is octal).
int i = 0, x = 0;
for(; i < arrSize; i++)
x = x * 10 + number[i];
x is the result.
int i;
int x = 0;
for ( i = 0; i < 4; i++ )
x = ( 10 * x + number[i] );
int number[]={1,2,3,4}
int x=0,temp;
temp=10;
for(i=0;i<number.length;i++)
{
x=x*temp+number[i];
}
cout>>x;
You could do something with a for loop and powers of 10
int tens = 1;
int final = 0;
for (int i = arrSize - 1; i <= 0; ++i)
{
final += tens*number[i];
tens*=10;
}
return final;
Answer is quite easy.Just list a complete function here.
int toNumber(int number[],arraySize)
{
int i;
int value = 0;
for(i = 0;i < arraySize;i++)
{
value *=10;
value += number[i];
}
return value;
}

For loop output in C

I am trying to understand the for loop better. I have the following variables:
x = 1
y = 10
I want to increment x and double it ten times with a for loop to have the following output: 1, 2, 4, 8, 16, etc.
This is what I have, but it is not quite doing the trick:
int x = 1;
int y = 10;
for (int i = 0; i < y; i++)
{
x *= 2;
}
printf("%d\n", x);
Do I need another variable to do this?
It looks fine to me. If you want it to print at each iteration, you need to move the printf into the loop.
Also, your code will only work in C99 or with GCC's default extensions since you have int i inside the for loop.
If you want it to display a running count then you should place printf inside the for-loop, so it gets executed with each iteration.
Do I need another variable to do this?
No. You could actually remove a variable - y. It is unneeded and you can specify 10 directly in the loop's conditional:
int i = 0;
int x = 1;
for (i = 0; i < 10; i++)
{
x *= 2;
printf("%d\n", x);
}
I want to increment x and double it ten times with a for loop to have the following output: 1, 2, 4, 8, 16, etc.
Your example contradicts your requirement. Incrementing an integer and doubling it would look produce 1, 4, 6, 8, 10, 12, 14...n. They are simply multiples of two. Your example produces powers of two, i.e.,
int x;
for( x = 0; x < 10; ++x )
{
printf("%d\n", pow(2, x) );
}
for (int i = 0; i < y; i++)
{
x *= 2;
printf("%d\n", x);
}
Think you want the printf statement inside the for loop... between the { and the }.
int x = 1;
int y = 10;
int i = 0;
int main() {
for(i = 0; i < y; i++) {
x *= 2;
printf("%d\n", x);
}
return 0;
}
Output:
2
4
8
16
32
64
128
256
512
1024
your answer contradict with your source code,if you want to print 1,2,4,8,16,... you will get first element 2, because you are multiplying every iteration 2 times than its value, you do not need to use extra variable,moreover you can remove y,put directly 10 and use printf statement inside {}.hope it will help
if you know that you have to increment it for only 10 times. Then why to use extra variable ? use this....
for(x = 1; x<=1024; x*=2)
{
printf("%d ",x);
}

Resources