Iterate through an array with nonconsecutive integers - c

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(" ");
}

Related

Program asks for too many numbers when trying to add 2 arrays element wise

#include<stdio.h>
int main(){
int n,sum = 0;
scanf("%d",&n);
int num1[n],num2[n],num3[n];
for(int i = 0;i<n;i++){
scanf("%d",&num1[i]);
for(int j = 0 ;j<n;j++){
scanf("%d",&num2[j]);
for(int k = 0;k<n;k++){
num3[k] = num1[i] + num2[j];
}
}
}
for (int l = 0; l < n; l++)
printf("%d ",num3[l]);
printf("\n");
return 0;
}
I am trying to add the same indexed numbers from two arrays into a third array for a given size n. But it keeps asking for more numbers. Where is the problem?
You want to take 2 array as input and store their sum to a third array, i.e. sum[i] = num1[i]+num2[i]. Now, the array num1 and num2 are in no way dependent on one another. But the array sum is dependent on both num1 and num2.
So, You will take input num1 and num2 as independent arrays, and then use another loop to add the two arrays.
loop i from 0 to n: take num1[i]
loop i from 0 to n: take num2[i]
loop i from 0 to n: sum[i]=num1[i]+num2[i]
print sum[i];

Recursive function with stopping condition but without base case still works

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..

Trying to find smallest array elements from 2 arrays returns 0 (doesn't work) and the other works. (C lang)

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

Assigning a random value to an array

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++;

Create random numbers

this is my first question here, i'm making a little game, and for assigning the roles, i need random numbers. I have this code, but is possible that the numbers don't be repeated? Thanks.
void giveroles() {
srand(time(NULL));
int r = rand() % i + 1;
switch ( r ) { /* ... */ }
}
If you want to randomly assign a small set of numbers, rather than generate them at random, create a list of the numbers you want, and then randomise the order of the list (iterate over the list, randomly swapping entries).
For example:
int cards[52];
for(int i = 0 ; i < 52 ; i++)
{
cards[i] = i;
}
for(int i = 0 ; i < 1000 ; i++)
{
int r1 = rand()%52;
int r2 = rand()%52;
int t = cards[r1];
cards[r1] = cards[r2];
cards[r2] = t;
}
for(int i = 0 ; i < 52 ; i++)
{
printf("%d\n", cards[i]);
}
For completeness, it has been pointed out that shuffling in this fashion is biased. Here's a variation which should be unbiased:
cards[0] = 0;
for(int i = 1 ; i < 52 ; i++)
{
int r = rand() % (i+1);
cards[i] = cards[r];
cards[r] = i;
}
(it should be further noted that taking the module of rand() is also likely to be biased, as the range of rand() will not be an even multiple)
Take out the line srand(time(NULL));. You should in general only ever do this once in your program, e.g. at the start of main(), in order to randomize the seed used by subsequent calls to rand().
If you don't want to repeat random numbers, the solution is to keep track of which random numbers you have previously used, and if you get a "hit" in your list of existing numbers, try again.
Also, using srand(time(NULL)); should only be done once. I suspect this is more the question you were actually asking.

Resources