C - nested for loop patern - c

how to get output like flipped floyds triangle? and how's the best way to solve it?
Example :
5555
_555
__55
___5
note : _ is a space
already tried lot of code but still I cant get output like that.
one of my code:
#include<stdio.h>
int main () {
int a,b,c,n;
scanf("%d",&n);
for(a=1;a<=n;a++) {
for(b=n;b>=a;b--) {
printf(" ");
}
for(c=1;c<=a;c++) {
printf("*");
}
printf("\n");
}
}

This is not the best way... but the code is similar to the one posted by you.
int main()
{
int a, b, c, n;
scanf("%d", &n);
for (a = n; a > 0; a--)
{
for (b = n; b >= a; b--)
{
printf(" ");
}
for (c = 1; c <= a; c++)
{
printf("*");
}
printf("\n");
}
}
In the original post you first for loop was
for(a=1;a<=n;a++)
which meant the 2nd for loop would print n*space and the 3rd for loop would print 1 star.
By changing the first for loop to
for (a = n; a > 0; a--)
Everything gets inverted so first loop will print no space and last for loop n*stars.

As a joke;)
#include <stdio.h>
int main( void )
{
int n = 5555;
while (n)
{
printf("%5d\n", n);
n /= 10;
}
return 0;
}
The program output is the same as required.:)
5555
555
55
5
If to use loops then the program for example can look like
#include <stdio.h>
int main( void )
{
const char c = '5';
while (1)
{
printf("Enter a non-negative number (0 - exit): ");
unsigned int n;
if (scanf("%u", &n) != 1 || n == 0) break;
putchar('\n');
for (unsigned int i = 0; i < n; i++)
{
unsigned int j = i + 1;
printf("%*c", (int)j, c);
while (j++ < n) putchar(c);
putchar('\n');
}
putchar('\n');
}
return 0;
}
Its output might look like
Enter a non-negative number (0 - exit): 10
5555555555
555555555
55555555
5555555
555555
55555
5555
555
55
5
Enter a non-negative number (0 - exit): 0
The inner while loop can be substituted for the for loop
for ( ; j < n; j++ )

Related

How to get sequence of numbers and then print the last 5?

Im trying to make a program that will get sequence from the user that end with 0, and then i want to print the last 5 numbers (not including the 0).
I can assume that the user will input all the numbers in one line and will end it with 0.
I wrote that code but something is wrong with it, I think its something about the scanf line.
Input:
1 6 9 5 2 1 4 3 0
Output: no output
#include <stdio.h>
#define N 5
int main()
{
int arr[N] = {0};
int last_input, j;
printf("please enter more than %d number and than enter 0: \n", N);
last_input = 0;
while (last_input<N) {
scanf(" %d", &j);
if (j == '0') {
last_input = N;
break;
}
else {
arr[last_input] = j;
}
if (last_input==(N-1)) {
last_input=-1;
}
++last_input;
}
printf("The last %d numbers u entered are:\n", N);
for (j=(last_input+1); j<N; ++j) {
printf(" %d", arr[j]);
}
for (j=0; j<last_input; ++j) {
printf(" %d", arr[j]);
}
return 0;
}
This comparison
if (j == '0') {
does not make a sense because the user will try to enter the integer value 0 instead of the value (for example ASCII 30h or EBCDIC F0h) for the character '0'.
You need to write at least
if (j == 0) {
Due to these sub-statements of the if statement
last_input = N;
break;
this for loop
for (j=(last_input+1); j<N; ++j) {
printf(" %d", arr[j]);
}
is never executed and does not make a sense.
This statement
last_input=-1;
results in breaking the order of the N last elements in its output. And moreover the result value of the variable last_input will be incorrect.
You need to move elements of the array one position left. For this purpose you can use a loop of standard C function memmove.
The program can look the following way.
#include <stdio.h>
#include <string.h>
int main( void )
{
enum { N = 5 };
int arr[N];
printf( "Please enter at least not less than %d numbers (0 - stop): ", N );
size_t count = 0;
for (int num; scanf( "%d", &num ) == 1 && num != 0; )
{
if (count != N)
{
arr[count++] = num;
}
else
{
memmove( arr, arr + 1, ( N - 1 ) * sizeof( int ) );
arr[N - 1] = num;
}
}
if (count != 0)
{
printf( "The last %zu numbers u entered are: ", count );
for (size_t i = 0; i < count; i++)
{
printf( "%d ", arr[i] );
}
putchar( '\n' );
}
else
{
puts( "There are no entered numbers." );
}
}
The program output might look like
Please enter at least not less than 5 numbers (0 - stop): 1 2 3 4 5 6 7 8 9 0
The last 5 numbers u entered are: 5 6 7 8 9
I made some changes based on ur comments and now its work fine!
#include <stdio.h>
#define N 5
int main()
{
int arr[N] = {0};
int last_input, j;
printf("please enter more than %d number and than enter 0: \n", N);
last_input = 0;
while (last_input<N) {
scanf("%d", &j);
if (j == 0) {
break;
}
else {
arr[last_input] = j;
}
if (last_input==(N-1)) {
last_input=-1;
}
++last_input;
}
printf("The last %d numbers u entered are:\n", N);
for (j=(last_input); j<N; ++j) {
printf("%d ", arr[j]);
}
for (j=0; j<last_input; ++j) {
printf("%d ", arr[j]);
}
return 0;
}
thank u guys <3.

C Program (Prime Number in a given range)

I have started learning C language. I wrote this program to find all prime numbers between the given range but I am unable to get the expected output.
Can anyone tell me what's wrong with this program please?
#include <stdio.h>
#include <conio.h>
void main() {
int min, max, i, j, count = 0;
printf("Enter Your First Number\n");
scanf("%d", &min);
printf("Enter Your Last Number\n");
scanf("%d", &max);
for(i=min; i<=max; i++) {
for(j=1; j<=i; j++) {
if(i % j == 0) {
count++;
}
}
if(count==2) {
printf("%d\t",i);
}
}
getch();
}
I just suggest getting rid of that count variable.
How do you know if a number N is prime? If for every j in the range (2 to N-1) you have N%j != 0.
So:
In the inner loop, use j from 2 to N-1 (instead of from 1 to N as you used tio do). In fact N%1 and N%N will be 0
The first time you find a j so that N % j == 0 break. You are sure it's not prime
Why incrementing count? For a prime number the j counter will be equal to i (because you looped until j<i, and the last j++ made j
equal to i). So just check for j == i and print the prime number i
#include <stdio.h>
#include <conio.h>
int main( void )
{
int min, max, i, j, count = 0;
printf("Enter Your First Number\n");
scanf("%d", &min);
printf("Enter Your Last Number\n");
scanf("%d", &max);
for(i=min; i<=max; i++)
{
// Was for(j=1; j<=i; j++)
for(j=2; j<i; j++)
{
if(i % j == 0)
{
//Was count++;
break;
}
}
//Was if(count==2)
if(j == i)
{
printf("%d\t",i);
}
}
getch();
return 0;
}
Here you are.
#include <stdio.h>
int main( void )
{
printf( "Enter the range of numbers (two unsigned integer numbers): " );
unsigned int first = 0, last = 0;
scanf( "%u %u", &first, &last );
if ( last < first )
{
unsigned int tmp = first;
first = last;
last = tmp;
}
do
{
int prime = first % 2 == 0 ? first == 2 : first != 1;
for ( unsigned int i = 3; prime && i <= first / i; i += 2 )
{
prime = first % i != 0;
}
if ( prime ) printf( "%u ", first );
} while ( first++ != last );
putchar( '\n' );
return 0;
}
The program output might look like
Enter the range of numbers (two unsigned integer numbers): 0 100
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
As for your program then you need re-initialize the variable count before the inner loop
for(i=min; i<=max; i++) {
count = 0;
for(j=1; j<=i; j++) {
if(i % j == 0) {
count++;
}
}
And the inner loop is inefficient.
Need to reset the value of count. It starts at count=0, then for any inputs, the loops will count up. The For each outer loop index, it will go like this:
1 (1%1=0 --> count++, count = 1)
2 (2%1=0 --> count++, and 2%2=0 --> count++, count = 3)
3 (3%1=0 --> count++, and 3%3=0 --> count++, count = 5)
etc... until max is reached.
You can use a simple isprime function to check whether a number is prime or not and then call the function for the given interval.
To find whether a number is prime or not , we can use a simple primality test to check it.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
bool isprime(int n)
{
if(n <= 1) return false;
if(n <= 3) return true;
if(n%2 == 0 || n%3 == 0) return false;
for(int i = 5;i*i <= n;i += 6)
{
if(n%i == 0 || n%(i + 2) == 0)
{
return false;
}
}
return true;
}
int main()
{
int a,b;
printf("Enter the first number :");
scanf("%d",&a);
printf("Enter the second number :");
scanf("%d",&b);
for(int i = a;i <= b;i++)
{
if(isprime(i)) printf("%d ",i);
}
return 0;
}
There is a simple change you should do:
#include <stdio.h>
#include <conio.h>
void main() {
int min, max, i, j, count;
printf("Enter Your First Number\n");
scanf("%d", &min);
printf("Enter Your Last Number\n");
scanf("%d", &max);
for(i=min; i<=max; i++)
{
count=1;
for(j=2; j<=i; j++)
{
if(i % j == 0) {
count++;
}
}
if(count==2) {
printf("%d\t",i);
}
}
}
My answer may be a bit late, but since it's the same issue, i'll write it here in case it helps someone else coming to this thread in the future.
My code is written from the POV of a beginner (No complex functions or data types are used) as this is a code that mostly they will get stuck on.
Working:
User inputs the range.
Using the for loop, each number in the range is sent to the isprime function which returns TRUE or FALSE after checking the condition for being a prime number.
if TRUE : program prints the number.
if FALSE : program skips the number using continue function.
#include<stdio.h>
int isprime(int num);
int main() {
int min, max;
printf("Input the low number: ");
scanf("%d", &min);
printf("Input the high number: ");
scanf("%d", &max);
for(int i = min; i<=max; i++) {
if(isprime(i) == 1) {
printf("%d ", i);
}
else if(isprime(i) == 0){
continue;
}
}
return 0;
}
int isprime(int num) {
int count = 0;
for(int i=2; i<=(num/2); i++) {
if(num % i == 0 ) {
count ++;
}
else{
continue;
}
}
if(count>0){
return 0;
}
else if (count == 0){
return 1;
}
}

Optimize code to get following output in c

I had an interview last week. They asked me to write a code to print like this
input :5
0
101
21012
3210123
432101234
54321012345
i wrote the below code but he said i could optimize this more . i cant figure it out.
,
int main(){
int n,i,j,k,lim,num;
scanf("%d",&n);//getting input starting number of last row
lim=n;
int collen=n+2;//it denotes end of row
for(i=0;i<n+1;i++)
{
num=i;
k=0;
for(j=0;j<collen-1;j++){
if(j<lim)
printf(" ");
else if(num<0){
printf("%d",++k);
}
else{
printf("%d",num--);
}
}//j for
printf("\n");
collen++;
lim--;
}//i for
}// main end
I have different code at first attempt, I used flag to detect when num reaches for incrementing and decrementing, it was complex there was about 4 if inside second loop, so I optimized that code to the above one. He said can you optimize more? I have no idea to optimize it .
My question: can it be optimized? If it can be - please post the code
There are more for-loops than those comparing by <. for(i=0;i<n+1;i++) is much clearer written as for (i = 0; i <= n; i++).
If you initialize a value, in example int collen=n+2;, and later use it like collen-1, save the subtraction and initialize it adjusted.
Separate this complex inner loop with ifs into their own loops.
Use less variables.
Use more and consistent whitespace.
And now my solution, but as yours it can only handle inputs from 0 to 9:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int n;
printf("input :");
if (scanf("%d", &n) != 1 || n < 0 || n > 9) {
printf("input not recognized or invalid\n");
return EXIT_FAILURE;
}
for (int i = 0; i <= n; ++i) {
printf("%*d", n - i + 1, i);
for (int j = i - 1; j >= 0; --j) {
printf("%d", j);
}
for (int j = 1; j <= i; ++j) {
printf("%d", j);
}
printf("\n");
}
return EXIT_SUCCESS;
}
This looks optimized to the brims:
int main( int argc, char **argv )
{
puts( "input :5");
puts( " 0");
puts( " 101");
puts( " 21012");
puts( " 3210123");
puts( " 432101234");
puts( "54321012345");
}
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
/* Print a pyramid */
int
main(int argc, char **argv)
{
int size = argc > 1 ? strtol(argv[1],NULL,10) : 5;
if( size > 9 || size < 0) {
fprintf(stderr, "Invalid size\n");
return EXIT_FAILURE;
}
for(int line = 0; line <= size; line++) {
char template[]="9876543210123456789";
char *s = template + 9 - size;
template[10 + line] = '\0';
memset(s, ' ', size - line);
if(puts(s) == EOF) {
perror("puts");
return EXIT_FAILURE;
}
}
return EXIT_SUCCESS;
}

Need 10 outputs per line

I am having trouble refining some code. My code takes a number "n" and calculates that many prime numbers. I need to display 10 primes per line of output data. Any tips would be appreciated.
#include <stdio.h>
int main()
{
int n, i = 3, count, c;
printf("How many primes would you like?");
scanf("%d",&n);
if ( n >= 1 )
{
printf("2");
}
for ( count = 2 ; count <= n ; )
{
for ( c = 2 ; c <= i - 1 ; c++ )
{
if ( i%c == 0 )
break;
}
if ( c == i )
{
printf(" %d",i);
count++;
}
i++;
}
return 0;
}
Just try
printf(" %5d", i);
/* ^ to help align the numbers
and
if ((count + 1) % 10 == 0)
fputc(stdout, '\n');
fix for the first time when you already print 2.
bool is_prime(int anyNum) //takes an integer array returns, is_prime
{
bool is_prime = true;
for (int c = 2; c <= anyNum - 1; c++)
{
if (anyNum % c == 0)
{
//printf("%d is not prime\r\n" , anyNum);
is_prime = false;
}
}
return is_prime;
}
int main()
{
int num_primes;
printf("How many primes would you like: ");
std::cin >> num_primes;
printf("\r\nScanned Primes Are---\r\n");
int foundPrimes = 0;
int x = 0;
for (; x <= num_primes; x++)
{
bool gotLuckyFindingPrime = is_prime( x );
if (gotLuckyFindingPrime)
{
if (foundPrimes % 10 == 0)
{
printf("\r\n");
}
printf(" %d", x);
foundPrimes = (foundPrimes + 1) % 10;
}
}
}
Does handle ten digit showing on cmd too, you can experiment with formatting

Sum 2 Big Integers store in array by using getchar not scanf - C programing

I need a help with this program, below is the object and the program I wrote so far:
Objective: Write a C program that allow user 100 digit positive integers and then print out the sum of the two numbers.
Program I wrote so far by using scanf:
#include <stdio.h>
int main(void) {
int sum=0,i,j,array[100];
for(i=1;i<3;i++)
{
printf("operand #%d :",i);
scanf("%d",&array[i]);
printf("value entered: %d\n", array[i]);
}
for(j=1;j<i;j++)
{
sum=sum+array[j];
}
printf("The sum of array is %d ", sum);
return 0;
}
The following is the code I used getchar():
#include <stdio.h>
int main(void) {
int c,i,j,sum=0;
char a[100];
for(i=1;i<3;i++)
{
printf("operand #%d :",i);
do{
if(i < 100){
a[i] = (char)c;
i++;
}
else{
printf("Error: Number must be greater than 0,try again");
}
} while((c = getchar()) != '\n');
printf("value entered: %d\n", a[i]);
}
for(j=1;j<i;j++)
{
sum=sum+a[j];
}
printf("The sum of array is %d ", sum);
return 0;
}
Any help is appropriate!
One of your problems is that you're using i for two different jobs at the same time. It isn't going to work.
for(i=1;i<3;i++) // Use #1
{
printf("operand #%d :",i);
do{
if(i < 100){
a[i] = (char)c; // Use #2
i++;
}
else{
printf("Error: Number must be greater than 0,try again");
}
} while((c = getchar()) != '\n');
printf("value entered: %d\n", a[i]);
}
The outer loop will probably execute just once — it would execute twice if the first number was a single-digit number.
This code also assigns c before you've called getchar(), which is not going to improve things, either. You probably also need to convert the ASCII digits into single-digit numbers (subtract '0' from the digits but you should check that it is a digit first, and should break the inner loop on a non-digit).
If you're going to store 3 numbers of up to 100 digits each, you're going to need to have storage for up to 300 digits. char a[100] isn't big enough.
You might use something like:
char a[3][100];
int n[3];
for (int i = 0; i < 3; i++)
{
int c;
int j;
printf("Operand #%d: ", i);
for (j = 0; j < 100 && (c = getchar()) != EOF && isdigit(c); j++)
a[i][j] = c - '0';
n[i] = j;
while (c != EOF && c != '\n')
c = getchar();
}
If you enter numbers with 80, 60 and 20 digits, then this stores the 80 digits in a[0][0..79] and puts 80 into n[0] (so you know how long the number is); it stores the 60 digits in a[1][0..59] and puts 60 into n[1]; and it stores the 20 digits in a[2][0..19] and puts 20 into n[2].
When it comes to doing the addition, you need to be careful to align the numbers correctly, and ensure that you don't overflow the answer buffer if your addition has 101 digits. With three positive decimal numbers of up to 100 digits each, the answer can't be more than 101 digits long.
However, your code doesn't work.
True: the previous version use for (int j = 0; …) and then tried to access j outside the loop. The fix is obviously to declare j before the loop.
However, otherwise, the code does work. I've adjusted the occurrences of 3 to 2 since you say you only need two numbers. I decline to mess with indexing from 1; this is C and arrays are indexed from 0 in C. If you want a 1-based language, go and use Pascal or something.
Sample code to demonstrate:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
int main(void)
{
char a[2][100];
int n[2];
for (int i = 0; i < 2; i++)
{
int c;
int j;
printf("Operand #%d: ", i);
for (j = 0; j < 100 && (c = getchar()) != EOF && isdigit(c); j++)
a[i][j] = c - '0';
n[i] = j;
while (c != EOF && c != '\n')
c = getchar();
}
for (int i = 0; i < 2; i++)
{
printf("%d: %2d digits: ", i, n[i]);
for (int j = 0; j < n[i]; j++)
putchar(a[i][j] + '0');
putchar('\n');
}
return 0;
}
Sample data:
124232345289086098234232398098403242380980256454798796324635
98068704234280980243242349080928402342398408920482080980482034278795847396
Sample output:
Operand #0: 124232345289086098234232398098403242380980256454798796324635
Operand #1: 98068704234280980243242349080928402342398408920482080980482034278795847396
0: 60 digits: 124232345289086098234232398098403242380980256454798796324635
1: 74 digits: 98068704234280980243242349080928402342398408920482080980482034278795847396
That's the way it is supposed to work. You may want to do it differently; that's your prerogative. Have at it! I'm not going to solve the addition part of the problem for you — I've pointed out the most obvious gotchas (primarily, adding a[0][1] to a[1][1] will produce nonsense for the given inputs).
This only uses tiny functions. There's some tricky code in it; be wary of handing it in because you might be asked to explain what it does in detail, and you'll need to understand it all to be safe.
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
static inline int max(int x, int y) { return (x > y) ? x : y; }
/* Return dth digit from RH end of string of n digits in x */
static inline int digit(char *x, int n, int d)
{
return (d < n) ? x[n - 1 - d] : 0;
}
int main(void)
{
char a[2][100];
int n[2];
/* Input - can probably be tightened up */
for (int i = 0; i < 2; i++)
{
int c;
int j;
printf("Operand #%d: ", i);
for (j = 0; j < 100 && (c = getchar()) != EOF && isdigit(c); j++)
a[i][j] = c - '0';
n[i] = j;
if (j == 0)
{
printf("No number - exiting\n");
exit(0);
}
if (c != EOF && c != '\n')
{
if (j < 100 && !isdigit(c) && !isblank(c))
{
printf("Bogus data in input (%c)\n", c);
exit(1);
}
while ((c = getchar()) != EOF && c != '\n')
{
if (!isblank(c))
{
printf("Bogus data in input (%c)\n", c);
exit(1);
}
}
}
}
/* Print for validation */
int n_max = max(n[0], n[1]);
for (int i = 0; i < 2; i++)
{
printf("V-%d: %2d digits: ", i, n[i]);
int n_blanks = n_max - n[i] + 1;
for (int j = 0; j < n_blanks; j++)
putchar(' ');
for (int j = 0; j < n[i]; j++)
putchar(a[i][j] + '0');
putchar('\n');
}
/* Addition */
char sum[101];
int carry = 0;
int max_digits = max(n[0], n[1]);
for (int i = 0; i < max_digits; i++)
{
int d0 = digit(a[0], n[0], i);
int d1 = digit(a[1], n[1], i);
int r = d0 + d1 + carry;
if (r > 9)
{
carry = 1;
r -= 10;
}
else
carry = 0;
sum[max_digits - i] = r;
}
if (carry)
sum[0] = 1;
else
sum[0] = 0;
/* Print result */
printf("Sum: %2d digits: ", (sum[0] == 0) ? max_digits : max_digits + 1);
if (sum[0] == 0)
putchar(' ');
for (int j = ((sum[0] == 0) ? 1 : 0); j <= max_digits; j++)
putchar(sum[j] + '0');
putchar('\n');
return 0;
}
Sample runs:
Operand #0: 888
Operand #1: 888
V-0: 3 digits: 888
V-1: 3 digits: 888
Sum: 4 digits: 1776
Operand #0: 1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890
Operand #1: 9876543210987654321098765432109876543210987654321098765432109876543210987654321098765432109876543210
V-0: 100 digits: 1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890
V-1: 100 digits: 9876543210987654321098765432109876543210987654321098765432109876543210987654321098765432109876543210
Sum: 101 digits: 11111111101111111110111111111011111111101111111110111111111011111111101111111110111111111011111111100
Operand #0: 9876543210a
Bogus data in input (a)
Operand #0: 9876543210987654321098765432109876543210987654321098765432109876543210987654321098765432109876543210a
Bogus data in input (a)
Operand #0: 98765432109876543210987654321098765432109876543210987654321098765432109876543210987654321098765432109
Bogus data in input (9)
Operand #0:
No number - exiting
It isn't perfect:
Operand #0: 0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
Operand #1: 0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
V-0: 100 digits: 0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
V-1: 100 digits: 0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
Sum: 100 digits: 0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
Stripping leading zeroes from input (and output) is left as an exercise for you.

Resources