Can anyone help me understand how this code prints a triangle? - c

I don't understand how this code displays a triangle. My main problem is understanding the working of integers j and k. How do they affect the triangle's position?
#include <stdio.h>
int main(){
int j,k,Rows;
printf("Enter The Number of Rows : ");
scanf("%d", &Rows);
for(j=2;j<=l;j++){
for(k=1;k<=j;k++){
printf(" %d ", j);
}
printf("\n");
}
return 0;
}

I guess the program you want is
#include <stdio.h>
int main(){
int j,k,Rows;
printf("Enter The Number of Rows : ");
scanf("%d", &Rows);
for(j=1;j<=Rows;j++){
for(k=1;k<=j;k++){
printf(" %d ", j);
}
printf("\n");
}
return 0;
}
Changes are:
Change l to Rows
Change j=2 to j=1
And here is an example result
Enter The Number of Rows : 6
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
6 6 6 6 6 6
My main problem is understanding the working of integers j and k. How do they affect the triangle's position?
j here can represent the row index. k can represent the column index. In another word, k represents how many items in current row. for(k=1;k<=j;k++) means the max value of k is j. Since j is increased by 1, so the max value of k is also increased by 1:
口 # j = 1, the max value of k is 1, so this row has 1 item.
口 口 # j = 2, the max value of k is 2, so this row has 2 items.
口 口 口 # j = 3, the max value of k is 3, so this row has 3 items.
口 口 口 口 # j = 4, the max value of k is 4, so this row has 4 items.

Related

How to compare array indexes with an integer in C?

A grocery store has N different types of chips. Chris wants to buy the chips as many as possible. He has M dollar in his pocket right now and he ask you to help him to count the number of chips he can buy as many as possible.
Format Input:
Input start with T, the number of test cases. For each test cases, there will be 2 integers N and M. In the second line there will be N integers, describing the price of one i-th chips. There will be unlimited supply of each type of chips.
Format Output:
Output starts with “Case #X: ”, where X is the test case number starting at 1, then followed by an integers, the maximum number of chips that Chris can buy
Constraints:
• 1 ≤ T ≤ 100
• 1 ≤ N ≤ 10000
• 1 ≤ M ≤ 10^9
• It is guaranteed the price will be between 1 and 10^6
Sample Input (user input) and Output (output in italic):
6
4 5
1 2 3 4
Case #1: 5
3 3
5 5 5
Case #2: 0
3 2
1 1 1
Case #3: 2
10 5
1 1 1 1 1 2 2 2 2 2
Case #4: 5
6 2
1 2 3 6 5 4
Case #5: 2
1 5
1
Case #6: 5
`
#include <stdio.h>
int main()
{
int t;
scanf("%d", &t);
for(int i = 1; i <= t; i++)
{
long long int n, m;
scanf("%lld %lld", &n, &m);
int chips[n];
for(int j = 0; j < n; j++)
{
scanf("%d", &chips[j]);
}
if(m > chips[n - 1])
{
printf("Case #%d: %lld\n", i, m);
}
else if(m < chips[n - 1])
{
printf("Case #%d: 0\n", i);
}
}
return 0;
}
`
I made a mistake in the if else part. I compare the m with the whole array, but I think I have to compare the m with the indexes of the array one by one. I don't know how to write the syntax to compare the indexes one by one. Does anyone know how to write the if else statement correctly for this problem?
If the problem is asking for the maximum number of packets chris can buy, then chris should only think about how many quantity of lowest-priced packet he can buy.
for example, in testcase 1, the lowest price of a packet is 1, so in this case, having m = 5, he can by 5 packets of worth 1.
So, first, you should find the lowest price of a packet (min value among the given array of costs)
then print:
printf("case #%d: %d\n", m/min);

Please help me transpose the matrix in C (with dynamic memory allocation)

I have this assignment to get and transpose a matrix using dynamic memory allocation in C
I did it by converting the linear position to (i,j) and swapping i,j
old and new element positions are perfect,
somehow the swap is not working as i intended,
might seem like i'm making others problem solve for me, but i'm blank at this point so help will be really appreciated
Here's the code:
#include <stdio.h>
#include <stdlib.h>
int main(){
int m,n;
printf("Enter the order of matrix, m*n:\n");
scanf("%d %d",&m,&n);
int *matrix_ptr;
matrix_ptr = (int *) malloc(m*n*sizeof(int));
printf("Enter the elements of %d*%d matrix\n",m,n);
for(int i=0; i<m*n; i++){
scanf("%d", matrix_ptr+i);
}
// Transposing the matrix
for(int i=0; i<m*n; i++){
int i_index = i / n;
int j_index = i % n;
// (i_index)*n + j_index gives the linear position
int new_linear_pos = (j_index)*n + i_index;
int temp = *(matrix_ptr + new_linear_pos);
*(matrix_ptr + new_linear_pos) = *(matrix_ptr + i);
*(matrix_ptr + i) = temp;
if(i==0){
printf("\nThe transpose is:\n");
}
printf("%d ", *(matrix_ptr+i));
if((i+1)%n == 0){
printf("\n");
}
}
}
The output:
You are swapping all values twice and you are printing the ones at the beginning of the line after the second swap. The first swap happened with i equal 1 and 2
Let's say you have this matrix at the begin:
1 2 3
4 5 6
7 8 9
swap index 0 with 0 stays the same thing. Prints 1
swap index 1 with 3: prints 4
1 4 3
2 5 6
7 8 9
swap index 2 with 6: prints 7\n
1 4 7
2 5 6
3 8 9
swap index 3 with 1: prints 4
1 2 7
4 5 6
3 8 9
etc...
The solution would be to swap elements only once.
The easiest fix would be a if (i > new_linear_pos) continue; //already swapped

Rectangle from numbers, internal numbers are high and external numbers are low, there is a problem with some numbers

I have an exercise I need to submit. The user should enter 2 numbers, one of height and one of width, and the output should be a rectangle that the outer numbers are low and the inner ones are high.
So I wrote it but it does not work in some numbers, for example 9 and 3, but in most things it works.
I made 2 variables that are equal to the numbers entered by the user, this data goes down, the other 2 variables are just indicators, of the loops, they have no meaning
If anyone has a different direction how to do it, I would love to hear, just in loops ..
For example:
1 1 1 1 1 1 1 1 1
1 2 2 2 2 2 2 2 1
1 2 3 3 3 3 3 2 1
1 2 3 3 3 3 3 2 1
1 2 2 2 2 2 2 2 1
1 1 1 1 1 1 1 1 1
Thanks
#include <stdio.h>
int main() {
int row, col, u, d;
scanf("%d", &row);
scanf("%d", &col);
int row_1, col_1;
for (u = 1, row_1 = row; u <= row; u++, row_1--) {
for (d = 1, col_1 = col; d <= col; d++, col_1--) {
if (col_1 < u && row_1 > col_1)
printf("%d", col_1);
else if (u > d && row_1 >= d)
printf("%d", d);
else if(row_1 > u)
printf("%d", u);
else
printf("%d", row_1);
}
printf("\n");
}
return 0;
}
I would start by learning to describe the problem. For example:
the user enters the number of rows and columns to print (presumably 1–9 each)
for each position, print the distance to the nearest edge of the rectangle, starting from 1
The above description would quite easily lead to a solution like:
for (int row = 1; row <= num_rows; ++row) {
int y_distance = distance_to_edge(row, num_rows);
for (int col = 1; col <= num_cols; ++col) {
int x_distance = distance_to_edge(col, num_cols);
printf("%d", x_distance < y_distance ? x_distance : y_distance);
}
putchar('\n');
}
(Implementation of distance_to_edge left as exercise.)
Of course this is not the only solution; you can also take advantage of the fact that you know how the position changes (as you have attempted in your solution), but such optimisation may make it harder to get right. One easy option there is to break each loop down to two halves (the distance increases in the first half and decreases in the second)…

C: How to take an input as unknown sized matrix

Question:
Given a matrix A, compute the sum of maximal elements row-wise (find a maximum element of each row and take their sum) and column-wise independently and return those values.
In which input is going to be :
First-line contains n, m number of rows and columns of input matrix.
Next n lines contains m integers.
Some examples:
Input1:
3 3
4 3 2
3 7 7
2 6 0
Output1:
17 18
Input2:
3 4
1 2 3 4
5 6 7 8
9 10 11 12
Output2:
24 42
I can't tell how I am supposed to take the matrix input using scanf. Please help.
just use scanf("%d", &variable) no matter if delimiter is a new line or a space:
#include <stdio.h>
int main()
{
int lines, cols;
scanf("%d", &lines);
scanf("%d", &cols);
for(int y = 0; y < lines; y++){
for(int x = 0; x < lines; x++){
int variable;
scanf("%d", &variable);
// your code
}
}
// your code
return 0;
}

What should I do for sort array?

I tried to sort arr by excluding those who were already selected as the largest numbers but it didn't work.
The result is this:
As I intended, at first cycle, the store is {9, 0, 0, 0, 0 ... } and when arr[i] becomes 9, the rest of process should be skipped. I have to sort it without additional functions and it's too difficult to me. What is the problem?
int i = 0;
int j = 0;
int num = 0;
int sign = 0;
int arr[10] = { 1,5,3,4,8,7,5,9,8,0 };
int max = arr[0];
int store[10] = { 0 };
int k = 0;
for (j = 0; j < 10; j++) {
printf("store: ");
for (int n = 0; n < 10; on++)
printf("%d ", store[n]);
printf("\n");
for (i = 0; i < 10; i++) {
sign = 0;
k = 0;
while (k < 10) {
if (arr[i] == store[k]) {
sign = 1;
break;
}
k++;
}
if (sign == 1) {
continue;
}
if (arr[i] > max) {
max = arr[i];
}
}
store[j] = max;
}
You have several errors here:
The array store has a size of 10, but in the jth pass through the outer loop, only j values have been filled in; the rest is still zero. So whenever you iterate over store, you should use j as upper limit.
You are looking for the max in each iteration. Therefore, it is not enough to initialise max once outside the outer loop. You do that, and it will stay 9 ever after. You should reset max for every j.
Finally, your idea to go through the array to see whether you have already processed a certain value does not work. Your array has duplicates, two 8's and two 5's. You will only place one eight and one five with your strategy and re-use the last value of max for the last two elements. (Plus, that idea lead to O(n³) code, which is very wasteful.
You can work around that by keeping an extra array where you store whether (1) or not (0) you have already processed a value at a certain index or by setting processed entries in the array to a very low value.
What you want to implement is selection sort: Find the maximum value in the whole list and move it to the front. Then find the maximum in the whole list except the first item and move it to the second slot and so on:
* 1 5 3 4 8 7 5 9 8 0
9 * 5 3 4 8 7 5 1 8 0
9 8 * 3 4 5 7 5 1 8 0
9 8 8 * 4 5 7 5 1 3 0
9 8 8 7 * 5 4 5 1 3 0
9 8 8 7 5 * 4 5 1 3 0
9 8 8 7 5 5 * 4 1 3 0
9 8 8 7 5 5 4 * 1 3 0
9 8 8 7 5 5 4 3 * 1 0
9 8 8 7 5 5 4 3 1 * 0
9 8 8 7 5 5 4 3 1 0 *
Here, all items to the left of the asterisk have been sorted and everything to the right of the asterisk is still unsorted. When the * (at position j) has moved to the right, the whole array is sorted.
This sort is in-place: It destroys the original order of the array. That is useful, because the position of an element tells us whether it has been processed or not. In the third iteration, the algorithm can distinguish between the 8 that has been sorted and the 8 that hasn't been sorted yet. (This sort is often described as sorting a hand of cards: Look fo the lowest, put it to the left and so on. If you must sort into a second array, copy the original array and sort the copy in place.)
Here's the code that sorts your array and prints out the diagram above:
#include <stdlib.h>
#include <stdio.h>
int main()
{
int arr[10] = {1, 5, 3, 4, 8, 7, 5, 9, 8, 0};
int i = 0;
int j = 0;
for (j = 0; j < 10; j++) {
int imax = j;
int swap = arr[j];
// print array
for (i = 0; i < 10; i++) {
if (i == j) printf("* ");
printf("%d ", arr[i]);
}
printf("\n");
// find index of maximum item
for (i = j + 1; i < 10; i++) {
if (arr[i] > arr[imax]) {
imax = i;
}
}
// swap first unsorted item and maximum item
arr[j] = arr[imax];
arr[imax] = swap;
}
// print fully sorted array
for (i = 0; i < 10; i++) {
printf("%d ", arr[i]);
}
printf("*\n");
return 0;
}
Use i and j.
N is 10 and the data consists of shuffled numbers 0 to N-1.
j goes from 0 to N-1. At each step, you want to fill it with
the maximum of the unprocessed input.
So i goes from j+1 to N-1, in the inner loop. If arr[j] < arr[i],
swap arr[i] and arr[j].
It speeds up considerably as you get towards the end.

Resources