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..
Related
I'm trying to accomplish a simple task in C which is to print out the smallest number from array 1 and smallest number from array 2. Both array elements are imputed by the user.
First one just returns 0 (which in my testing case its supposed to be 1) and the other one returns the correct one (11). I seriously can't understand why and I also tried to google this with no result so that's when I once again decided to seek help here!
int main () {
int masyvas1[10] = {0};
int masyvas2[10] = {0};
for(int i = 0; i < 10; i++){
int x;
printf("Ivesk pirmo masyvo 10 sk: ");
scanf("%d", &x);
masyvas1[i] = x;
}
for(int i = 0; i < 10; i++){
int x;
printf("Ivesk antro masyvo 10 sk: ");
scanf("%d", &x);
masyvas2[i] = x;
}
int mas1maz[2] = {0, 0};
for(int i = 0; i < 10; i++){
if(masyvas1[i] < mas1maz[1]){
mas1maz[1] = masyvas1[i];
}
if(masyvas2[i] < mas1maz[2]){
mas1maz[2] = masyvas2[i];
}
}
printf("testas: %d %d", mas1maz[1], mas1maz[2]);
}
If I enter numbers say from 1 to 10 for the first array and 11 to 20 for the second the program output is: testas: 0 11 which I was expecting it to be testas: 1 11
Thank you in advance!
I would like you to go over your program by trying what is below
int mas1maz[2] = {0, 0};
The Array has 2 elements, try to print each element.
Note: there are only 2 elements but I am printing 3 as you have used mas1maz[2] ( this is grabage= 11)
printf("%d,%d,%d",mas1maz[0],mas1maz[1],mas1maz[2]);
Then you are trying to compare with mas1maz[1]=0, this will result in a minimum always equal to zero.
for(int i = 0; i < 10; i++) {
/*
*/
if(masyvas1[i] < mas1maz[1]) {
mas1maz[1] = masyvas1[i];
}
Here you are tyring to compare mas1maz[2] with garbage=11, this is the reason why you see 11.
if(masyvas2[i] < mas1maz[2]) {
mas1maz[2] = masyvas2[i];
}
What you should try is the following :
for(int i = 0; i<9; i++) {
if(masyvas1[i]>masyvas1[i+1])
{
/*copy to your array*/
mas1maz[0]=masyvas1[i]
}
/* similarly for masyvas2*/
}
see that for an array of length len, indices of the array ranges from 0 to len-1
if(masyvas2[i] < masyvas2[i]){
mas1maz[2] = masyvas2[i];
}
Change your second if as follow. You was checking for smaller number in masmaz1 array and was passing 2 in array parameters which is not compatible. As you have initialized an array for 2 locations 0 and 1 as array locations are started from 0. So change that Second if to compare it with itself for smallest number.
int min;
int max;
int i;
min=max=mas1maz[0];
for(i=1; i<10; i++)
{
if(min>mas1maz[i])
min=mas1maz[i];
}
You should use this after you fill your tables with scanf to find the minimum value
then compare the two different minimums
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++;
I'm trying to print out 100 numbers from an array using a loop and then add them all together. So far I have:
#include <stdio.h>
#include <stdlib.h>
int main(){
int* number = malloc(101 * sizeof(int));
int num = 0;
number[num] = 1;
while (number[num] <= 100){
printf(" %d\n ", number[num]);
num = num +1;
number[num] = number[num]+1;
}
return 0;
}
but this just prints 1 once.
number[num] = number[num]+1;
You only properly set number[0]. Now you are trying to take whats in number[1] and add to it, in the first iteration. You didn't set it to anything though, leaving it uninitialised. This is undefined behaviour. What you most likely wanted to do is
number[num] = number[num-1]+1;
To add one to the previous number before after printing it. Now it will print fine.
To add them up, simply do
for (int a = 0; a < 100; a++) {
number[100] += number[a]; // add number[a] to result
}
printf("%d\n",number[100]);
Also, don't forget to free your dynamically allocated array at the end.
Try this:
#include <stdio.h>
int main () {
int n[ 100 ]; /* n is an array of 100 integers */
int i,j;
int sum = 0;
/* initialization */
for ( i = 0; i < 100; i++ ) {
n[ i ] = i + 100; /* set element at location i to i + 100 */
}
/* output each array element's value */
for (j = 0; j < 100; j++ ) {
printf("Element[%d] = %d\n", j, n[j]);
sum += n[j];
}
printf("Sum of Elements = %d\n", sum);
return 0;
}
Remember that you should declare an array, then initialize it, print it out and after all print out the sum
You can just print out 1 to 100, then you could quickly use some maths to get the count of all numbers added together, for example, one of Gauss' algorithms, specifically http://betterexplained.com/articles/techniques-for-adding-the-numbers-1-to-100/
There’s a popular story that Gauss, mathematician extraordinaire, had a lazy teacher. The so-called educator wanted to keep the kids busy so he could take a nap; he asked the class to add the numbers 1 to 100.
Here's what I would do: -
int i = 0;
for (i = 1; i <= 100; i++) {
printf("%d", i);
}
// gauss technique 100(100 + 1) / 2
int count = (100 * 100 + 100 * 1) / 2;
printf("all numbers added: %d", count);
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.