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.
Related
I would like to know if there's a way for me to get the current value of "j" outside of the foor loop whenever the conditions is true. The variable "totalvalid" will tell me how many times the condition was met but I would also like to know the exact value of j when the condition is true so that I can use it at a later point. So I would want to extract the value of "j" whenever the "totalvalid = totalvalid +1" happens. Sorry if it looks messy. I'm new to coding and still have no idea how to make it cleaner. Thank you.
for(int j = 0; j < stringnumber; j++){
int valid = 0;
if(str[j][10] == '\0'){
for(int k = 0; k < 10; k++){
if(str[j][k] >= 'A' && str[j][k] <= 'Z'){
valid++;
}
}
if (valid == 10){
totalvalid = totalvalid + 1;
}
}
}
It seems that you want an array of numbers from that pass the condition.
My suggestion would be to make an array of ints, where you will keep these numbers.
Before loop:
int *array_of_valid_ints = (int *) calloc(stringnumber, sizeof(int)); // allocate the array
int number_of_valid_ints = 0;
Inside the if statement:
array_of_valid_ints[number_of_valid_ints] = j;
number_of_valid_ints++;
After the loop ends, you can check the good values with:
printf("This are the good ints: ")
for (int i = 0; i < number_of_valid_ints; i++) {
printf("%d ", array_of_valid_ints[i]);
}
printf("\n");
maybe you can define a variable before the loop as int j=0; then use a while loop instead of for.also remember to write j++ in the while loop.this way you can use the value of j outside of the loop too!
I tried to solve the problem by calculating sum up to n without knowing about the base case and come up with this. It works but I don't know why.
int sumUpTo(int num)
{
int i, sum = 0; // I also tried not to initialize sum here but the results are the same
for(i = 0; i < num; i++)
sum = sumUpTo(num - 1) + num;
return sum;
}
int main()
{
int num;
printf("Enter a number: ");
scanf("%d", &num);
printf("Sum = %d\n", sumUpTo(num));
return 0;
}
I figured out that this function has the stopping condition i=num but no base case, the loop will stop with sum = sumUpTo(0) + 1 + ... + num. How could the program work without knowing the value of sumUpTo(0)?
What could possibly happen here?
Did the program assume the value of sumUpTo(0) is 0 (even with/without initialization of the variable sum)?
Suppose you enter 3 as your input.
for(i = 0; i < 3; i++) // Returns 3 + 3 = 6
for(i = 0; i < 2; i++) // Returns 2 + 1 = 3
for(i = 0; i < 1; i++) // Returns 1 + 0 = 1
for(i = 0; i < 0; i++) // Returns 0
Here the recursion will end because that will not call another instance
If you don't initialize sum, as your comment says, the function can still work, only the result is undetermined.
You didn't set base value of num variable, but it works successfully
This is specific case of your code.
In this code, you used 'for' statement
If incoming num is 0, it doesn't pass via 'for' statement because 0 < 0 is not true. that's why it returns initial sum value with zero in last final loop
Take this reference for safe algorithm, This is the standard code for recursive function
int sumUpTo(int num)
{
if(num == 0)
return 0;
return sumUpTo(num - 1) + num;
}
It works as in your for loop you have
for(i = 0; i < num; i++)
if num is a 0 or lower the for loop would never execute and since you have
int sum = 0;
it will return 0 as it never entered the for loop and everytime your function gets restarted(recalled) it will the current copy of num to 0..
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 */
}
I'm writing a code that will call a function repeatedly for each value in the Fibonacci sequence. For instance, let's say I want to print the sequence number each iteration, but I also want to print it in iteration-number times in that particular iteration. I'll want my output to be
1 1 22 333 55555 88888888 ... and so on.
Currently, I have a for-loop set up that creates an array with the Fibonacci sequence:
for(index = 0; index < 10; index++)
{
fibonacci[index] = fibonacci[index] + fibonacci[index-1]+fibonacci[index-2];
}
I'm not sure where to proceed from here. I've experimented with adding additional for-loops both inside and outside this one, but I'm coming up short. Primarily the problem lies within the fact that the loop can't take on the sequene's nonconsecutive values.
You need to have a nested for loop, this means a for loop within your for loop for the repetitive display of characters.
int a = 0;
int b = 1;
int c = 0;
for (int i = 0; i < 10; i++){
c = a + b;
a = b;
b = c;
for(int x = 0; x < c; x++) {
System.out.print(c);
}
System.out.print(" ");
}
I'm trying to
Get rid of the info in an array with 10 "spots".
Fill the array with (10) random numbers
My code till time
int main()
{
int numbers[10] = { 0 };
int randNumber = 0;
int i = 0;
for (int i = 0; i <= 10; i++)
{
srand(time(NULL));
randNumber = rand() % 10 + 1;
printf("Random number saved in the array: %d\n", randNumber);
i++;
}
getchar();
getchar();
return 0;
}
First of all, you need to move the srand(time(NULL)); out of the loop.
Otherwise, because, time() has a time granularity of 1 second, in a second, if called multiple times in the loop (within a second, probably), it will re-initialize the PNRG with the same seed and all the next call to rand() will give you the same random number.
Now, once you have the random numbers, you need to assign it to the each array member like numbers[i] = randNumber; inside the loop, but there's more to it. Your loop, at present is off by one. You need to change
for (int i = 0; i <= 10; i++)
to
for (int i = 0; i < 10; i++)
to stay within bounds.
Your array's size is 10, and this loop runs 11 times, causing an overflow. This will solve it:
for (int i = 0; i < 10; i++)
Also remove the increasing of the loop's iterator, i, from inside the loop body. Remove the line:
i++;