I have to make a Floyd Triangle that prints in this order:
7 8 9 10
4 5 6
2 3
1
But currently my code print like this:
1
2 3
4 5 6
7 8 9 10
CODE:
#include <stdio.h>
int main()
{
int n, i, c, a = 1;
scanf("%d", &n);
for (i = 1; i <= n; i++)
{
for (c = 1; c <= i; c++)
{
printf("%d ", a);
a++;
}
printf("\n");
}
return 0;
}
Can someone help me?
Here you are.
#include <stdio.h>
int main(void)
{
while ( 1 )
{
printf( "Enter a non-negative number (0 - exit): " );
unsigned int n;
if ( scanf( "%u", &n ) != 1 || n == 0 ) break;
int width = 0;
for ( unsigned int tmp = n * ( n + 1 ) / 2; tmp != 0; tmp /= 10 )
{
++width;
}
putchar( '\n' );
for ( unsigned int i = 0; i < n; i++ )
{
unsigned int value = ( n - i ) * ( n - i + 1 ) / 2 - ( n - i - 1 );
for ( unsigned int j = 0; j < n - i; j++ )
{
printf( "%*u ", -width, value++ );
}
putchar( '\n' );
}
putchar( '\n' );
}
return 0;
}
The program output might look like
Enter a non-negative number (0 - exit): 10
46 47 48 49 50 51 52 53 54 55
37 38 39 40 41 42 43 44 45
29 30 31 32 33 34 35 36
22 23 24 25 26 27 28
16 17 18 19 20 21
11 12 13 14 15
7 8 9 10
4 5 6
2 3
1
Enter a non-negative number (0 - exit): 4
7 8 9 10
4 5 6
2 3
1
Enter a non-negative number (0 - exit): 0
I solved it by hacking (i.e. trying different things and adjusting the code based on the output):
I started by moving the generation code to a separate function. I then cut and pasted the function, giving it a different name. I then started modifying the for loops.
I went through four versions until I hit the correct one:
#include <stdio.h>
#include <stdlib.h>
void
fwd(int n)
{
int i, c;
int a = 1;
for (i = 1; i <= n; i++) {
for (c = 1; c <= i; c++) {
printf("%d ", a);
a++;
}
printf("\n");
}
}
void
rev1(int n)
{
int i, c;
int a = 1;
for (i = n; i >= 1; i--) {
for (c = 1; c <= i; c++) {
printf("%d ", a);
a++;
}
printf("\n");
}
}
void
rev2(int n)
{
int i, c;
int a = 0;
for (i = 1; i <= n; i++)
a += i;
for (i = n; i >= 1; i--) {
for (c = i; c >= 1; c--) {
printf("%d ", a);
a--;
}
printf("\n");
}
}
void
rev3(int n)
{
int i, c;
int a = 0;
for (i = 1; i <= n; i++)
a += i;
for (i = n; i >= 1; i--) {
for (c = i; c >= 1; c--) {
printf("%d ", (c - i) + a);
a--;
}
printf("\n");
}
}
void
rev4(int n)
{
int i, c;
int a = 0;
for (i = 1; i <= n; i++)
a += i;
for (i = n; i >= 1; i--) {
for (c = 1; c <= i; c++) {
printf("%d ", (c - i) + a);
}
a -= i;
printf("\n");
}
}
int
main(int argc,char **argv)
{
int n;
--argc;
++argv;
if (argc > 0)
n = atoi(*argv);
else
scanf("%d", &n);
printf("fwd:\n");
fwd(n);
printf("\nrev1:\n");
rev1(n);
printf("\nrev2:\n");
rev2(n);
printf("\nrev3:\n");
rev3(n);
printf("\nrev4:\n");
rev4(n);
return 0;
}
Here's the program output:
fwd:
1
2 3
4 5 6
7 8 9 10
rev1:
1 2 3 4
5 6 7
8 9
10
rev2:
10 9 8 7
6 5 4
3 2
1
rev3:
10 8 6 4
6 4 2
3 1
1
rev4:
7 8 9 10
4 5 6
2 3
1
The other answers are great, but no one posted a recursive function so I thought I'd add one.
#include <stdio.h>
void recursive(int n, int i);
void straight(int n);
// one way of doing it with a recursive function
void recursive(int n, int i) {
if(n <= 0)
return;
if(i <= n) {
printf( "%-3d", (((n * (n + 1) / 2) - n) + i) );
recursive(n, i + 1);
} else {
printf("\n");
recursive(n - 1, 1);
}
}
// straightforward nested loop way
void straight(int n) {
int i, j, row_sum;
for(i = n; i > 0; --i) {
// the sum: i + (i-1) + (i-2) + ... + 2 + 1 = (i * (i+1)) / 2
row_sum = (i * (i + 1)) / 2;
for(j = i; j > 0; --j) {
printf("%-3d", row_sum - j + 1);
}
printf("\n");
}
}
// entry point
int main(int argc, char **argv) {
int n = 0;
scanf("%d", &n);
printf("Recursive Output for n=%d\n", n);
recursive(n, 1);
printf("\nStraight Output for n=%d\n", n);
straight(n);
return 0;
}
Output:
Recursive Output for n=5
11 12 13 14 15
7 8 9 10
4 5 6
2 3
1
Straight Output for n=5
11 12 13 14 15
7 8 9 10
4 5 6
2 3
1
Related
The code works fine but why are my answers wrong in the int result?
in output:
3
10
2 3 5 7: 17 //correct
30
2 3 5 7 11 13 17 19 23 29: 146 //incorrect
50
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47: 474 //incorrect
Here is the code:
#include <stdio.h>
int main() {
int y, n, i, fact, j, result = 0;
scanf("%d", &y);
for (int x = 1; x <= y; x++) {
scanf("%d", &n);
for (i = 1; i <= n; i++) {
fact = 0;
for (j = 1; j <= n; j++) {
if (i % j == 0)
fact++;
}
if (fact == 2) {
result += i;
printf("%d ", i);
}
}
printf(": %d\n", result); //Not Getting correct answer please HELP!
}
return 0;
}
You forgot to initialize result before each calculation.
for(int x=1;x<=y;x++){
scanf("%d", &n);
result = 0; // add this for initialization
for (i = 1; i <= n; i++) {
/* ... */
}
/* ... */
}
The variable result is initialized only once
int y, n, i, fact, j, result = 0;
So it will accumulate values calculated in the loop
for(int x=1;x<=y;x++){
//...
}
Move the declaration of the variable result in the body of the loop
for(int x=1;x<=y;x++){
int result = 0;
//...
}
To avoid such an error you should declare variables in the minimum scope where they are used.
Also this loop
for (j = 1; j <= n; j++)
{
if (i % j == 0)
fact++;
}
does not make a great sense. Change the condition in the loop the following way
for (j = 1; j <= i; j++)
{
if (i % j == 0)
fact++;
}
substituting the variable n for the variable i.
Also you should use an unsigned integer type instead of the signed integer type int because prime numbers are defined for natural numbers.
The program can look for example the following way
#include <stdio.h>
int main(void)
{
unsigned int n = 0;
scanf( "%u", &n );
while ( n-- )
{
unsigned int max_value = 0;
scanf( "%u", &max_value );
unsigned long long int sum = 0;
for ( unsigned int i = 1; i <= max_value; i++ )
{
size_t count = 0;
for ( unsigned int j = 1; j <= i; j++ )
{
if ( i % j == 0 ) ++count;
}
if ( count == 2 )
{
printf( "%u ", i );
sum += i;
}
}
printf( ": %llu\n", sum );
}
return 0;
}
If to enter
3
10
20
100
then the output will be
2 3 5 7 : 17
2 3 5 7 11 13 17 19 : 77
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 : 1060
I am trying to print an array in order to the even strings print backwards but the not even string in usual way. What do I do wrong with it?
For example:
1 0 3
9 7 3
5 7 8
and I need it:
1 0 3
3 7 9
5 7 8
But I also have a problem with filling an array in spiral way; how should I take a center of an array? Please, could you give an idea — how should I do this? And the array must be square. For example:
1 2 3
4 5 6
7 8 9
but I need it:
3 2 9
4 1 8
5 6 7
My code so far:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a[10][10],n,m,i,j;
printf("Enter m: ");
scanf("%d",&m);
printf("Enter n: ");
scanf("%d",&n);
for(i=0;i<m;i++){
for(j=0;j<m;j++){
printf("a[%d][%d]: ",i+1,j+1);
scanf("%d",&a[i][j]);
}
}
// in usual order
for(i=0;i<m;i++){
for(j=0;j<n;j++){
printf("%d ",a[i][j]);
}
printf("\n");
}
for(i=0;i<m;i++){
for(j=0;j<n;j++){
if(i%2 != 0){
printf("%d ",a[i][j]);
}
else {
printf("%d ",a[n-i+1][j]);
}
}
printf("\n");
}
return 0;
}
example of filling an array in spiral
#include <stdio.h>
#include <string.h>
typedef enum {
N, W, S, E
} Dir;
typedef struct walker {
int row, col;
Dir dir;
int steps;
} Walker;
Walker go_forward(Walker walker){
switch(walker.dir){
case N:
walker.row -= 1;
break;
case W:
walker.col -= 1;
break;
case S:
walker.row += 1;
break;
case E:
walker.col += 1;
break;
}
return walker;
}
Walker proceed_left(Walker walker){
walker.dir = (walker.dir + 1) % 4;//turn left
walker = go_forward(walker);
return walker;
}
int main(void){
int n;
for(;;){
printf("Enter n(0 < n < 10): ");fflush(stdout);
int ret_s = scanf("%d", &n);
if(ret_s == 1){
if(0 < n && n < 10)
break;
} else if(ret_s == 0)
while(getchar() != '\n');//clear input
else //if(ret_s == EOF)
return 0;
}
int a[n][n];
memset(a, 0, sizeof(a));//zero clear
Walker walker = { .row = n / 2, .col = n / 2, .dir = E, .steps = 0 };
for(;;){
walker.steps += 1;
a[walker.row][walker.col] = walker.steps;
if(walker.steps == n * n)//goal
break;
Walker left = proceed_left(walker);
if(a[left.row][left.col] == 0)//left side is vacant
walker = left;
else
walker = go_forward(walker);
}
for(int r = 0; r < n; ++r){
for(int c = 0; c < n; ++c){
if(c)
putchar(' ');
printf("%2d", a[r][c]);
}
puts("");
}
}
Here is a program that includes the function spiral_fill(), which fills a square array with sequential ints, starting from 1 at the center, and proceeding in a counter-clockwise spiral. The function fills the array by first storing a 1 in the center, then filling the L-shaped region above and to the left, then below and to the right, and continuing until the array is filled.
#include <stdio.h>
#define ARR_SZ 3
void spiral_fill(size_t arr_sz, int arr[arr_sz][arr_sz]);
void print_arr(size_t rows, size_t cols, int arr[rows][cols]);
int main(void)
{
int test_arr[ARR_SZ][ARR_SZ];
spiral_fill(ARR_SZ, test_arr);
print_arr(ARR_SZ, ARR_SZ, test_arr);
return 0;
}
void spiral_fill(size_t arr_sz, int arr[arr_sz][arr_sz])
{
int center = arr_sz / 2;
int current = center;
int start_col, stop_col, start_row, stop_row;
size_t layer = 0;
int next_val = 1;
arr[center][center] = next_val++;
++layer;
while (layer < arr_sz) {
if (layer % 2) { // For odd layers, fill upper L
current -= layer;
start_col = center + layer / 2;
stop_col = center - (layer + 1) / 2;
for (int j = start_col; j >= stop_col; j--) {
arr[current][j] = next_val++;
}
start_row = center - layer / 2;
stop_row = center + layer / 2;
for (int i = start_row; i <= stop_row; i++) {
arr[i][current] = next_val++;
}
++layer;
} else { // For even layers, fill lower L
current += layer;
start_col = center - layer / 2;
stop_col = center + layer / 2;
for (int j = start_col; j <= stop_col; j++) {
arr[current][j] = next_val++;
}
start_row = center + (layer - 1) / 2;
stop_row = center - layer / 2;
for (int i = start_row; i >= stop_row ; i--) {
arr[i][current] = next_val++;
}
++layer;
}
}
}
void print_arr(size_t rows, size_t cols, int arr[rows][cols])
{
for (size_t i = 0; i < rows; i++) {
for (size_t j = 0; j < cols; j++) {
printf("%-5d ", arr[i][j]);
}
putchar('\n');
}
}
Here is a 3X3 array:
3 2 9
4 1 8
5 6 7
Here is a 6X6 array:
31 30 29 28 27 26
32 13 12 11 10 25
33 14 3 2 9 24
34 15 4 1 8 23
35 16 5 6 7 22
36 17 18 19 20 21
This is the code that I've tried which simply generates numbers and prints. I am totally stuck about how to access the row numbers and interchange the printing positions of the rows of the matrix.
#include <stdio.h>
int main(void)
{
int i,a[10][10],j,n,count=1;
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
a[i][j]=count;
printf("%d\t",count++);
}
printf("\n");
}
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
printf("%d*\t",a[i][j]);
printf("\n");
}
return 0;
}
I am providing a link for the pattern which is to be printed, please check.
https://drive.google.com/open?id=1DKwW8dQggzNjjtAxwPTEI3nRS9AmpK-2Zw
My approach is to avoid the matrix altogether:
#include <stdio.h>
int main() {
int number;
(void) scanf("%d", &number);
int twice = 2 * number;
int squared = number * number;
for (int row = 0, upward = number, downward = 2 * squared; row < number; row++) {
int n = ((upward > squared) ? downward : upward) - number + 1;
for (int column = 0; column < number; column++) {
printf("%d*\t", n++);
}
printf("\n");
upward += twice;
downward -= twice;
}
return 0;
}
EXAMPLES
> ./a.out
3
1* 2* 3*
7* 8* 9*
4* 5* 6*
> ./a.out
4
1* 2* 3* 4*
9* 10* 11* 12*
13* 14* 15* 16*
5* 6* 7* 8*
> ./a.out
5
1* 2* 3* 4* 5*
11* 12* 13* 14* 15*
21* 22* 23* 24* 25*
16* 17* 18* 19* 20*
6* 7* 8* 9* 10*
>
This is my solution to the problem:
#include <stdio.h>
int main() {
int input = 0;
int i = 0;
int j = 0;
int k = 1;
scanf("%d", &input);
int array[input][input];
for(i = 0; i < (input/2); i++) {
for(j = 0; j < input; j++) {
array[i][j] = k;
k++;
}
for(j = 0; j < input; j++) {
array[input-1-i][j] = k;
k++;
}
}
if((input % 2) == 1) {
for(j = 0; j < input; j++) {
array[input/2][j] = k;
k++;
}
}
for(i = 0; i < input; i++) {
for(j = 0; j < input; j++) {
printf("\t%d", array[i][j]);
}
printf("\n");
}
return 0;
}
These are the outputs of the program for diferent inputs:
1
1
2
1 2
3 4
3
1 2 3
7 8 9
4 5 6
4
1 2 3 4
9 10 11 12
13 14 15 16
5 6 7 8
5
1 2 3 4 5
11 12 13 14 15
21 22 23 24 25
16 17 18 19 20
6 7 8 9 10
I wish to print a pattern in C language like this:
1
2 6
3 7 10
4 8 11 13
5 9 12 14 15
Currently I have this:
int main()
{
int i,j;
for(i=1;i<=5;i++)
{
for(j=1;j<=5;j++)
{
if(i>=j)
{
printf(" %d ",j+i-1);
}
}
printf("\n");
}
printf("\n");
}
I am not getting the desired result.Please can anybody help
Basically if you analyze the difference between numbers at each row:
1
2 6
3 7 10
4 8 11 13
5 9 12 14 15
^ ^ ^ ^
diff 4 3 2 1
Then for each column (except the first one which is equal to the row) the formula is:
col_value = val(row, col-1) + (5-col))
For example, the last row:
5 9 12 14 15
9 = 5 + (5-1)
12 = 9 + (5-2)
14 = 12 + (5-3)
15 = 14 + (5-4)
Code:
#include<stdio.h>
int main()
{
int i,j,k;
for(i=1;i<=5;i++)
{
k = i;
for(j=1;j<=i;j++)
{
printf("%d ", k);
k += 5-j;
}
printf("\n");
}
return 0;
}
Check this :
int main()
{
int i,j;
for(i=1;i<=5;i++)
{
int temp = 4;
int sum = 0;
for(j=1;j<=i;j++)
{
if (j == 1)
sum = i;
else{
sum = sum + temp --;
}
printf("%d ",sum);
}
printf("\n");
}
}
int main () {
int k,i, j;
for (i = 1; i <=5; i++) {
k = i;
for (j = 1; j <= i; j++) {
printf ("%d ", k);
k = k + (5-j);
}
printf ("\n");
}
}
The logic is quite straight forward.
1) The number of elements in a row equals the row number. Hence use the inner loop with j = 1 to j <= i
2) If you see the pattern you observe that every row starts with the number equals to the row index, the next number is +4 and then +3 and so on.
3) Hence use k = k + (5-j)
int main()
{
int i,j,temp=0,l;
for(i=1;i<=5;i++)
{
l=4;
temp = i;
for(j=1;j<=i;j++)
{
if(j>1)
{
printf("%d\t",temp+l);
temp = temp+l;
l=l-1;
}
else
printf("%d\t",i);
}
printf("\n");
}
getch();
return 0;
}
I'm having a problem with saving my results to output file. Probably something's wrong with the function, but I can't find it and fix it. Does anybody know what's wrong ?
PROGRAM'S CODE:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int **str;
int *tab;
void read(){
int n = 1;
char help_sign;
FILE *fp = fopen("In0303.txt", "r");
if(fp == NULL){
printf("Blad odczytu z pliku!");
}
while((help_sign = fgetc(fp)) != EOF){
if (help_sign == '\n'){
n++;
}
}
fclose(fp);
}
void gen(){
int i, n;
int **str;
str =(int**)malloc(n*sizeof(int*));
for (i = 0; i < n; i++){
str[i] = (int*)malloc(4*sizeof(int));
}
}
void load_date(){
int i, n;
int **str;
FILE *fp = fopen("In0303.txt", "r");
for (i = 0; i < n; i++){
fscanf(fp, "%d" , &str[i][0]);
fscanf(fp, "%d" , &str[i][1]);
fscanf(fp, "%d" , &str[i][2]);
str[i][3]=0;
}
fclose(fp);
}
void gen_tab(){
int i, n, k = 0;
int **str;
int *tab;
for (i = 0; i < n; i++){
if (str[i][0] > k) k = str[i][0];
if (str[i][1] > k) k = str[i][1];
}
tab = (int*)malloc(k*sizeof(int));
for (i = 0; i < k; i++){
tab[i] = i + 1;
}
}
void sort(){
int i, n, j,tmp;
int **str;
for (i = 0; i < n-1; i++)
for (j = i+1; j < n; j++){
if (str[i][2] > str[j][2]){
tmp = str[i][0];
str[i][0] = str[j][0];
str[j][0] = tmp;
tmp = str[i][1];
str[i][1] = str[j][1];
str[j][1] = tmp;
tmp = str[i][2];
str[i][2] = str[j][2];
str[j][2] = tmp;
}
}
}
int min(int x, int y){
if (x > y) return y;
else return x;
}
int max(int x, int y){
if (x < y) return y;
else return x;
}
void make(){
int i, j, min1, max1, p, q, n, k;
int *tab;
int **str;
for (i = 0; i < n; i++){
if (tab[((str[i][0])-1)] != tab[((str[i][1])-1)]){
str[i][3] = 1;
min1 = min(tab[((str[i][0])-1)], tab[((str[i][1])-1)]);
max1 = max(tab[((str[i][0])-1)], tab[((str[i][1])-1)]);
for (j = 0; j < k; j++){
if (tab[j] == max1)
tab[j] = min1;
}
}
}
}
void save(){
int i, n;
int **str;
int *tab;
FILE *g = fopen("Out0303.txt","w");
for (i = 0; i < n; i++){
if (str[i][3] == 1){
fprintf(g, "%d ", str[i][0]);
fprintf(g, "%d ", str[i][1]);
fprintf(g, "%d\n", str[i][2]);
}
}
fclose(g);
}
int main(){
read();
gen();
load_date();
gen_tab();
sort();
make();
save();
printf("Wyniki zapisane do pliku!\n");
free(str);
free(tab);
return 0;
}
THIS IS INPUT FILE ("In0303.txt"):
9 17
2 3 8 4 9 8
1 3 3 6 4 5 9 6
2 6 4 4 9 1
2 5 3 4 5 3 9 2
4 3 6 1 9 5
5 1 7 5 9 2
6 5 8 4 9 2
1 4 7 4 9 2
1 8 2 6 3 1 4 2 5 5 6 2 7 2 8 2
AND THIS IS WHAT SHOULD BE CREATED IN OUTPUT FILE: ("Out0303.txt"):
17
3 9 [1]
5 6 [1]
4 9 [2]
6 9 [2]
7 9 [2]
8 9 [2]
1 2 [3]
1 8 [4]
Offhand - in your save function, you don't assign to "n"
Expanding a bit. You seem to want to use "n" as a global variable but you are declaring local instances of it so the value isn't retained across the functions. You could either make it global or pass it around.
Adding to DrC answers:
this piece of code:
for (i = 0; i < n; i++){
does very little if you do not set n, you have this mistake in gen(), gen_tab(), load(), save() and pretty much every other function.