how to stop if loop once array has a number - c

I need to create a program where user will input a number of integers and the program will output the fibonacci sequence number having the next larger number than the user input.
fibonacci sequence as follows:
0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181,6765
Example:
user inputs: [1, 9, 22]
output should be: 2, 13, 34
I cant seem to make the if loop stop once it has already acquired a value because the output will always display 4181, 4181, 4181.
My code is as follows below:
#include <stdio.h>
#include <conio.h>
void main()
{
int i, n, a[100];
int inputarray[3], j;
int outputarray[3];
a[0] = 0;
a[1] = 1;
for (i = 2; i < 20; i++) {
a[i] = a[i-1] + a[i-2];
}
for (i = 0; i < 20; i++) {
printf("%5d",a[i]);
}
for (j = 0; j < 3; j++) {
printf ("\nEnter numbers of input array:");
scanf ("%d", &inputarray[j]);
}
for (i = 0; i < 3; i++) {
for (j = 0; j < 20; j++) {
if (a[j] > inputarray[i])
outputarray[i] = a[j];
}
}
for (i = 0; i < 3; i++) {
printf("%5d", outputarray[i]);
}
getch();
}

Add break statement because once you found required value, you don't have to keep looping for j
for (i=0; i<3; i++)
{
for (j=0; j<20; j++)
{
if(a[j] > inputarray[i])
{
outputarray[i] = a[j];
break;
}
}
}

I would be much easier if you did not use a for loop (because you don't want to iterate over a given amount of values). If your loop depends on a condition use a do-while/while loop.
for (i = 0; i < 3; i++) {
while (a[j] <= inputarray[i])
{
j++;
}
outputarray[i] = a[j];
}

Related

How to transpose a matrix without using another matrix?

Write a program which will accept 2-dimensional square matrix and find out the transpose of it.
Program should not make use of another matrix
Hi I am trying to transpose a 2*2 matrix without using another matrix.
Is there anything wrong with my transpose logic?
I am a newbie
#include <stdio.h>
int main()
{
int mat[2][2];
int i, j, temp;
for (i = 0; i < 2; i++) {
printf("\nEnter elements of %d row of first matrix: ", i + 1); //i+1 so that it can print 1 row, 2 row, 3 row etc
for (j = 0; j < 2; j++) { //loop inside to loop to get value for a[0][0],a[0][1],a[0][2]
scanf("%d", &mat[i][j]);
}
}
printf("The matrix\n");
for (i = 0; i < 2; i++) {
for (j = 0; j < 2; j++) {
printf("%d\t", mat[i][j]);
}
printf("\n");
}
//transpose logic using same matrix
for (i = 0; i < 2; i++) {
for (j = 0; j < 2; j++) {
temp = mat[i][j];
mat[i][j] = mat[j][i];
mat[j][i] = temp;
}
}
printf("The transpose of the matrix is\n");
for (i = 0; i < 2; i++) {
for (j = 0; j < 2; j++) {
printf("%d\t", mat[i][j]);
}
printf("\n");
}
}
EDIT: I found an easier way to do it however I still don't understand why my transpose logic by using this
temp = mat[i][j];
mat[i][j] = mat[j][i];
mat[j][i] = temp;
cannot get it to transpose.
Below is my corrected answer
#include <stdio.h>
int main()
{
int mat[2][2];
int i, j, temp;
for (i = 0; i < 2; i++) {
printf("\nEnter elements of %d row of first matrix: ", i + 1);//i+1 so that it can print 1 row, 2 row, 3 row etc
for (j = 0; j < 2; j++) {//loop inside to loop to get value for a[0][0],a[0][1],a[0][2]
scanf("%d", &mat[i][j]);
}
}
printf("The matrix\n");
for (i = 0; i < 2; i++) {
for (j = 0; j < 2; j++) {
printf("%d\t", mat[i][j]);
}
printf("\n");
}
printf("The transpose of the matrix is\n");
for (i = 0; i < 2; i++) {
for (j = 0; j < 2; j++) {
printf("%d\t", mat[j][i]);
}
printf("\n");
}
}
Your program is a good attempt, but transposing the matrix is like reversing an array: you must stop half way to avoid swapping the transposed values twice, leading to the original matrix as you observe.
You should stop the inner loop when j == i, hence change the inner loop to:
for (j = 0; j < i; j++) { // j < i instead of j < 2
Here is a modified version:
#include <stdio.h>
int main() {
int mat[2][2];
int i, j, temp;
for (i = 0; i < 2; i++) {
printf("\nEnter elements of %d row of first matrix: ", i + 1);
for (j = 0; j < 2; j++) {
if (scanf("%d", &mat[i][j]) != 1)
return 1;
}
}
printf("The matrix:\n");
for (i = 0; i < 2; i++) {
for (j = 0; j < 2; j++) {
printf("%d\t", mat[i][j]);
}
printf("\n");
}
//transpose logic using same matrix
for (i = 0; i < 2; i++) {
for (j = 0; j < i; j++) {
temp = mat[i][j];
mat[i][j] = mat[j][i];
mat[j][i] = temp;
}
}
printf("The transpose of the matrix is:\n");
for (i = 0; i < 2; i++) {
for (j = 0; j < 2; j++) {
printf("%d\t", mat[i][j]);
}
printf("\n");
}
return 0;
}
Your corrected answer does not transpose the matrix at all, it merely outputs the transposed matrix. The matrix mat in memory is unchanged.

How to randomize a to p without repitition

I want to randomize a to p without repetition.
int main(){
int array2[4][4];
bool arr[100]={0};
int i;
int j;
srand(time(NULL));
for(i=0; i<=3; i++){
for(j=0; j<=3; j++){
int randomNumber1;
randomNumber1 = (rand() % (82-65+1))+65;
if (!arr[randomNumber1])
{
printf("%c ",randomNumber1);
array2[i][j]=randomNumber1;
}
else
{
i--;
j--;
arr[randomNumber1]=1;
}
}
printf("\n");
}
return;
the output still has repeat alphabet. I want to have the output in 4x4 with with all a to p without it repeating.
There are some errors in your code. IMHO the most serious is that arr[randomNumber1]=1; is is the wrong branch of the test. That means that your current code does not invalidate once a number was used but only if it has already been invalidated => if you control the arr array at the end of the program all value are still 0.
That is not all. When you get a duplicate, you should only reset the inner loop, and you are currently off by 2 in your maximum ascii code: you go up to R when you want to stop at P.
Your code should be:
for (i = 0; i <= 3; i++) {
for (j = 0; j <= 3; j++) {
int randomNumber1;
randomNumber1 = (rand() % (81 - 65)) + 65;
if (!arr[randomNumber1])
{
printf("%c ", randomNumber1);
array2[i][j] = randomNumber1;
arr[randomNumber1] = 1;
}
else
{
//i--;
j--;
}
}
printf("\n");
}
But this kind of code is terribly inefficient. In my tests it took 30 to 60 steps to fill 16 values, because random can return duplicates. This is the reason why you were advised in comments to use instead the modern algorithm for Fisher-Yates shuffle:
int main() {
int array2[16];
unsigned i, j, k=0;
// initialize array with alphabets from A to P
for (i = 0; i < sizeof(array2); i++) {
array2[i] = 'A' + i;
}
// Use Fisher-Yates shuffle on the array
srand(time(NULL));
for (i = 15; i > 0; i--) {
j = rand() % (i + 1);
if (j != i) {
int c = array2[i];
array2[i] = array2[j];
array2[j] = c;
}
}
// Display a 4x4 pattern
for (i = 0; i < 4; i++) {
for (j = 0; j < 4; j++) {
printf("%c ", array2[k++]);
}
printf("\n");
}
return 0;
}
Which shuffles the array in only 16 steps.
Here is the outline
// Need some #includes here - exercise for the reader
char items[] = "abcdefghijklmnopqrstuvwxyz";
int len = sizeof(items);
srand(time(NULL));
while (len > 0) {
int r = rand() % len;
printf("%c", items[r]);
len--;
items[r] = items[len];
}
This should do the trick to print the whole alphabet in random order without repeats. Modify to do what you need it to do

Attempt to arrange array elements in descending sequence (returning garbage values)

I wrote to program in C to attempt to print array elements in descending order. I wrote a nested loop which would find the maximum element of the array and the value of the element would be set to later 0. This process would be repeated for all the elements. However, in the output, I am getting the first 2-3 values as desired but the remaining values are garbage. Any suggestions?
int main() {
int i, j, n, k;
scanf("%d\n", &n);
int a[100], b[100];
for (i = 0; i < n; i++) {
scanf("%d", &a[i]);
}
for (i = 0; i < n; i++) {
int max = a[i];
for (j = i; j < n; j++) {
if (a[j] > max) {
max = a[j];
b[i] = max;
}
}
for (k = 0; k < n; k++) {
printf("%d", a[k]);
if (a[k] == b[i]) {
a[k] = 0;
}
}
printf("\n");
}
for (i = 0; i < n; i++) {
printf("%d ", b[i]);
}
}
The main issue is that you only set b[i] = max; when you find a new max, but since you initialized max to be a[i] it could happen that it already holds the maximum value. So the if never executes, therefore b[i] is not written and there's garbage value in it. You should move this line from the if after that for loop.
Another issue is that you initialize j with i in this loop. You should initialize it to 0.
The changed part:
for (j = 0; j < n; j++) {
if (a[j] > max) {
max = a[j];
}
}
b[i] = max;

How to make Bow Tie shape with for - while loops in C

Actually I did the easy part, but couldn't get more. I am a new Comp Eng student and we're trying to learn Loops. Our professor gave us this work to learn something. I did first part easily from last lesson. But I dont know how to lead it further.
I need to reflect this and get a full Bow Tie
Here it is my code:
#include <stdio.h>
main(); {
int sayi;
printf("Sayiyi gir > ");
scanf("%d",&sayi);
for (int i = 0; i < sayi; i++) {
for (int j = 0; j < i; j++) {
printf("*\t");
}
printf("\n");
}
for (int i = sayi; i >= 1; i--) {
for (int j = 0; j < i; j++) {
printf("*\t");
}
printf("\n");
}
return 0;
}
Change your code like:
for (i = 0; i <= sayi; i++) {
// Prints left part of the tie in row
for (j = 0; j < i; j++) {
printf("*\t");
}
// Prints the spaces between tie edges
for (j = 0; j < sayi - i; j++) {
printf("\t\t");
}
// Prints right part of the tie in row
for (j = 0; j < i; j++) {
printf("*\t");
}
printf("\n");
}
Repeat similar but reverse for lower part of the tie.

Bubble sort programming via C

I wrote a program for bubble sort which is showing a run time error saying "NULL Pointer Assignment". The code is given below:
#include <stdio.h>
void main()
{
int a[6], j = 0, count = 0, i, temp;
printf("Enter the number");
for(i = 0; i< 4; i++)
{
scanf("%d", &a[i]);
}
while(count < 4)
{
for(i = 0; i < 4; i++)
{
if(a[i] < a[++j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
count++;
}
printf("The sorted array is");
for(i = 0; i < 4; i++)
{
printf("\n%d\n", a[i]);
}
getchar();
}
But When I tried the below code then it runs successfully.
#include <stdio.h>
void main()
{
int a[6], count=0, i, temp;
printf("Enter the number");
for(i = 0; i < 4; i++)
{
scanf("%d", &a[i]);
}
while(count<4)
{
for(i = 0; i < 4; i++)
{
if(a[i] < a[i + 1])
{
temp = a[i];
a[i] = a[i + 1];
a[i + 1] = temp;
}
}
count++;
}
printf("The sort array is");
for(i = 0; i < 4; i++)
{
printf("\n%d\n", a[i]);
}
getchar();
}
So I need the reason that why my code is showing error, and why the 2nd code is working. I am a new learner in C so please explain to me the reason briefly and simply.
The reason you are getting a NULL pointer exception is in the first program, by the completion of the first iteration of the while loop the value of j has become 4. In the second iteration of the while loop the j value is not reset and continues from 4. Trying to access a[j] when j is equal to 6 will result in a the said error.
for (i = 0; i < n - 1; i++) {
for (j = 0; j <= i; j++) {
if(a[j] > a[j + 1]) {
// swap
}
}
}
Something like this will do the job.
The reason is that you don't reset the variable ´j´ at the beginning of the outer while loop and j is increased in the inner for loop. So you are increasing j in each of the 4 outer while loop transitions for 4 times in the inner for loop. So j has already reached the value 4 after the first while loop round. In the second while loop round it will be incremented to 5, 6, 7, 8 etc. So just reset the variable j to 0 at the beginning of the while loop:
while(count<4)
{
j = 0;
for(...
By the way it's still not a good implementation because you are comparing the last value with an undefined value: if(a[3] < a[4]).
Whereas a[3] contains the last entered value the variable a[4] contains an undefined value. Therefore you should change the for loop to for(i=0;i<3;i++).

Resources