C For Loop Floyd's Triangle but different? - c

I need help on how to do a Flyod's Triangle style but instead of input value in rows, the triangle is based on the input value as a whole.
instead of;
Enter a number: 9
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31 32 33 34 35 36
37 38 39 40 41 42 43 44 45
it should be
Enter a number: 9
1
23
456
789
here is my code
#include <stdio.h>
int main() {
int rows, i, j, number = 1;
printf("Enter a number: ");
scanf("%d", &rows);
for (i = 1; i <= rows; i++) {
for (j = 1; j <= i; ++j) {
printf("%d ", number);
++number;
}
printf("\n");
}
return 0;
}

To easily structure your output you might retain a row counter; in contrast to your code it only serves to determine how many columns we need per row, so:
for(size_t row = 1; ; ++row) // note: no condition; we'll break from within!
{
for(size_t col = 0; col < row; ++col)
{
// we'll print the values here!
}
}
This is the basic structure how to define rows and colums.
Now you'll input before this loop the target number up to which to output values, and you'll have a separate counter running up to the number just received by the user, i.e.:
int number;
if(scanf("%d", &number) != 1) // test to catch invalid input, though it does not
// catch all types of, e.g. for 77xyz the value 77
// will be scanned!
{
// TODO: error message!
}
else if(number < 0)
{
// again invalid input!
// TODO: error message
}
else if(number == 0):
{
// special case, don't output anything
}
else
{
int counter = 1;
// now our loops:
for(size_t row = 1; ; ++row)
{
for(size_t col = 0; col < row; ++col)
{
printf("%.2d ", counter);
// .2 is optional, it serves for better alignment of the output
// though fit ails for number > 99; you might calculate *before*
// this nested loop how many indentation you actually need...
// and now we check if we need to stop!
if(counter == number)
{
// as within main, we can just return; maybe add another
// newline before:
return 0;
}
++counter; // go on with next number
}
putchar('\n');
}
}
Note how the loop counters don't have any influence on stopping the output, only our explicit counter variable has.
Note, too, that above code is untested, so if you find a bug, please fix yourself.

#include <stdio.h>
int main() {
int max_num, i, j, number = 1;
printf("Enter a number: ");
scanf("%d", &max_num);
for (i = 1; 1; i++) {
for (j = 1; j <= i; ++j) {
printf("%d ", number);
++number;
if (number > max_num) {
return 0;
}
}
printf("\n");
}
return 0;
}

Related

My loop doesn't loop through the array properly

A Fibonacci program that I wrote is not working correctly. This program should display the nth and nth series but this is what happened: the resulting output is:
1 8 13 21 34 55 1284926876 32762 -440528208 678 1285217672
Whereas it should be the 5th to 15th Fibonacci:
1 8 13 21 34 55 89 144 233 377 610 987
Here is the code:
#include <stdio.h>
int main() {
int jbf, c, a, b, m, s;
int hasil[100];
printf("============================ \n");
printf("| Program Fiboonanci ");
printf("| \n");
printf("============================ \n");
printf("enter number of rows : ");
scanf("%d", &jbf);
printf("starting from line: ");
scanf("%d", &m);
s = jbf + m;
if (jbf > 0) {
a = 0;
b = 1;
printf("%d ", b);
for (int i = 1; i < jbf; i++) {
c = a + b;
hasil[i] = c;
a = b;
b = c;
}
for (int i = m; i < s; i++) {
printf("%d ", hasil[i]);
}
} else {
printf("enter a value > 0");
}
}
You have
scanf("%d", &jbf);
for ( int i = 1; i < jbf; i++) {
s = jbf + m;
for ( int i = m; i < s; i++) {
it looks to me that s > jbf so you also print values which were not calculated. I would also check for s>99, you have int hasil[100];, but the indexes in that field are 0..99 not 1..100, but you index from 1, which is fine as long as you remember that you allocated space for 100 int values, but you can use only 99 of them right now.

Sum of primes: what is the problem in result?

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

Printing first 50 numbers with 5 rows and 10 cols

I want to print the first 49 numbers with 5 rows and 10 columns.
I've tried using certain width implications and trying to make it aligned but I couldn't figure out how.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i, j;
int count = 50;
int r = 5;
int c = 10;
for (i = 0; i <= r; i++)
{
for(int j = 1; j <=count; j++)
{
printf("%9d", i);
i++;
}
}
return (0);
}
I was able to print from 0-49 but it wasn't aligned correctly, can someone help? Thank you.
No need to use two loops, one will do fine.
Use "%2d" to reserve two digits for each number.
Don't increase for loop variable inside loop. It isn't of much use here.
Code
#include <stdlib.h>
#include <stdio.h>
int main()
{
int i, j;
int count = 50;
int c = 10;
for (i = 0; i < count; i++)
{
printf("%2d ", i);
if (i%c == 9) printf("\n");
}
return (0);
}
You only need one loop and can use the remainder operator to detect when a new line is needed.
#include <stdio.h>
int main()
{
int count = 50;
int columns = 10;
for (int i = 0; i < count; i++)
{
printf("%9d", i);
if ((i % columns) == 9)
{
printf("\n");
}
}
return 0;
}
Output is:
0 1 2 3 4 5 6 7 8 9
10 11 12 13 14 15 16 17 18 19
20 21 22 23 24 25 26 27 28 29
30 31 32 33 34 35 36 37 38 39
40 41 42 43 44 45 46 47 48 49
You will need to know if the column has printed 10 values,you will need a offset to remind you that, where the last element occured which was the last 10th value, so we assign the offset variable to that element value based on 10 columns per row, so we take modulus if its the completely divisible by 10, then we will move to next row
#include <stdio.h>
#include <stdlib.h>
int main()
{
int count = 0;
int row = 5;
int column = 9;
int offset = 0;
for (int outer = 0; outer <= row; outer++)
{
for(int inner = offset; inner <= column; inner++)
{
if(count>=50){
break;
}
printf("%9d", count); // tab spaces between colums
count++;
}
printf("\n"); // new lines
}
return (0);
}
Adding space or any character before "%9d" fixes the problem.
printf(" %9d", i);

To find and assign primes to an array

Hi I have made a simple program to print primes between 1 and 100 but I cannot figure a way to assign these values to an array of size 25 as we all know there are 25 primes between 1 and 100:
#include <stdio.h>
int main() {
int i, k;
for (i = 3; i < 100; i = i + 2) {
for (k = 2; k < i; k++) {
if (i % k == 0)
break;
}
if (i == k)
printf("%d\n", i);
}
}
Just create an array at the top, write to it, and then read out of it after you've found all your primes. Note that this could definitely be done more efficiently, but given the number of calculations you're doing, that's beside the point.
Code
#include<stdio.h>
int main() {
int primes[25];
int i, k;
int j = 0;
// find primes
for(i = 2; i < 100; i++) {
for (k = 2; k < i; k++) {
if (i % k == 0) {
break;
}
}
if (i == k) {
primes[j] = i;
j++;
}
}
// print primes
for (j = 0; j < 25; j++) {
printf("%d\n", primes[j]);
}
return 0;
}
Also note that 2 is prime, so you'll want to make sure that that's included in your output.
Output
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
Make an array before you begin, then create a variable that increments while each prime is found. It might look something like this:
#include <stdio.h>
int main() {
int primes[25];
primes[0] = 2;
int count = 1;
for (int i = 3; i < 100; i += 2) {
int k;
for (k = 2; k < i; k++) {
if (i % k == 0) break;
}
if(i == k) {
primes[count] = i;
count++;
}
}
}
Warning: this is a humorous answer, not to be taken seriously.
Just like we all know there are 25 primes between 1 and 100, we might as well know the magic value to avoid using an array at all:
#include <stdio.h>
int main() {
long long magic = 150964650272183;
printf("2");
for (int i = 3; magic; magic >>= 1, i += 2)
magic & 1 && printf(" %d", i);
printf("\n");
return 0;
}
Output: 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

Prime number from 1 to 100 in C

I am writing a program to find prime numbers from 1 to 100. Please check if my code is correct or not. When I am running my code prime numbers are not getting printed. Please help.
#include <stdio.h>
#include <conio.h>
int main()
{
int i, j, flag, rem;
flag=0;
printf("2");
for(i=3; i<=100; i++)
{
for(j=2; j<=i; j++)
{
rem = i%j;
if(rem == 0)
{
flag=1;
break;
}
}
if(flag==0)
{
printf("%d", i);
}
}
getch();
return 0;
}
You have a couple of problems
First, the for(j=2;j<=i;j++) loop should be for(j=2;j<i;j++), as if j is equal to i, j % i == 0 will always be true
Second, your flag variable is not doing what you might think it is doing. As HolyBlackCat suggested this is a good opportunity to learn how to use a debugger to see what is happening. You need to reset the flag variable, because once you find a single composite number, your flag will not reset so all following numbers will be flagged as composite. Add:
for(i=3;i<=100;i++)
{
flag = 0;
for(j=2;j<=i;j++)
{
Change for (j = 2; j <= i; j++) to for (j = 2; j <= i/2; j++). You need to loop up to i/2.
int main()
{
int i, j, flag, rem;
printf("2\n");
for (i = 3; i <= 100; i++)
{
flag = 0;
for (j = 2; j <= i/2; j++)
{
if (i % j == 0)
{
flag = 1;
break;
}
}
if (flag == 0)
printf("%d\n", i);
}
getch();
return 0;
}
It is better to have a correct indentation for well-reading purposes. I added some comments in lines where you can optimize your code and I removed the unnecesary 'printf'. (\t is to write a tab space after what it is printed)
#include <stdio.h>
#include <conio.h>
int main()
{
int flag;
printf("Prime numbers: 2\t");
for(int i = 3; i <= 100; i++) // You can declare a temporal variable for the cycle
{
flag = 0; // reset the flag variable to zero when adding a new number
for(int j = 2; j < i; j++)
{
if(i%j == 0) // substitute the 'rem' variable for an operation
{
flag = 1;
break;
}
}
if(flag == 0)
{
printf("%d\t", i);
}
}
getch();
return 0;
}
The expected output will be:
Prime numbers: 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
You should reset flag at 0 each time you try a new number. Leaving the code like this, as soon as a number isn't prime, the code will never print again.
[...snip...]
for(i=3;i<=100;i++)
{
flag = 0;
for(j=2;j<=i;j++)
{
[...snip...]
The problem is flag is not set/reset correctly. and also there is a lot of scope for improvement in the code.
As you already print 2 as prime no so no need to check other even no as 2 is the only even no which is prime.
Instead of dividing form 2..n-1 we can check it for 2..n/2
Find the optimized code below:
// return 1 if no is prime else 0
int is_prime(int n)
{
for(int i = 3; i<= n/2; i+=2){
if (n%i == 0)
{
return 0;
}
}
return 1;
}
int main()
{
printf("2\n");
for(int i=3; i<=100; i+=2)
{
if (is_prime(i))
{
printf("%d\n", i);
}
}
return 0;
}

Resources