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

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.

Related

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;
}
}

Unable to print numbers entered into an array in reverse order

I'm attempting to write a program with an array in which:
The user enters 10 integers, and the integers are then displayed in reverse order, or
The user enters up to 10 integers and exits the while-loop using a 0, and the integers entered are then displayed in reverse order.
The code below is my best effort (my 5th attempt at solving the problem), but it's collecting the integer zero and displaying it in the array index (I've attempted to attach the other five, but it keeps producing an error):
int main()
{
#define ARRAY_LENGTH 10
int numbers[ARRAY_LENGTH];
int numbersEntered = 0;
for (int i = 0; i < ARRAY_LENGTH; i++)
{
numbers[i] = 0;
}
int number = 0;
printf("Enter an integer; 0 to quit: ", ARRAY_LENGTH - 1);
scanf_s("%d", &number);
while (number != 0 && numbersEntered < ARRAY_LENGTH - 1)
{
numbersEntered++;
numbers[numbersEntered] = number;
printf("Enter another integer; 0 to quit: ", ARRAY_LENGTH - 1);
scanf_s("%d", &number);
}
for (int i = numbersEntered; i >= 0; i--)
{
printf("index %d -> %d\n", i, numbers[i]);
}
}
See the problem is first you're initializing the entire array with zero here
for (int i = 0; i < ARRAY_LENGTH; i++)
{
numbers[i] = 0;
}
Then you're doing this
while (number != 0 && numbersEntered < ARRAY_LENGTH - 1)
{
numbersEntered++;
numbers[numbersEntered] = number;
printf("Enter another integer; 0 to quit: ", ARRAY_LENGTH - 1);
scanf_s("%d", &number);
}
So what is happening is, since numbersEntered was already initialized with zero you're incrementing it by 1, so the first digit is entered in the array numbers is 0 as you initialized the entire array itself in the start.
So a quick fix would be just to move it a line down and change the while loop code to this
while (number != 0 && numbersEntered < ARRAY_LENGTH - 1)
{
numbers[numbersEntered] = number;
numbersEntered++;
printf("Enter another integer; 0 to quit: ", ARRAY_LENGTH - 1);
scanf_s("%d", &number);
}
Also as pointed out by Kiran in the comments, the printing for loop needs to be changed to this
for (int i = numbersEntered-1; i > 0; i--)
{
printf("index %d -> %d\n", i, numbers[i]);
}
The line
printf("Enter an integer; 0 to quit: ", ARRAY_LENGTH - 1); should be
printf("Enter an integer; 0 to quit: ");
You should use scanf not scanf_s
The following code could work:
#include <stdio.h>
#define ARRAY_LENGTH 10
int main()
{
int numbers[ARRAY_LENGTH];
int i;
int k;
for (k = 0; k != ARRAY_LENGTH; ++k)
{
printf("Enter an integer; 0 to quit: ");
if (scanf("%d", numbers + k) != 1 || numbers[k] == 0)
break;
}
for (i = k - 1; i >= 0; --i)
printf("index %d -> %d\n", i, numbers[i]);
return 0;
}
This here is a solution of mine which includes some good practices, that is a tweak of your code:
1) you would want your defines outside of a function (or main) so that you can use the same constant in the entire program;
2) any function that has a return type (e.g int main) must return something at the end, thus you must have a "return 0" at the end of your main function;
3) the do-while part will ensure that your piece of code will be executed once before the while condition is checked;
4) numbers[numbersEntered++] = number; will assign to "numbers[numbersEntered]" the value of "number" and then will increment "numbersEntered" by one; This is to reduce the amount of code that you have to write :);
Hope this helped, and if you have more questions, I hope I can answer them :).
#define ARRAY_LENGTH 10
int main()
{
int numbers[ARRAY_LENGTH];
int numbersEntered = 0;
for (int i = 0; i < ARRAY_LENGTH; i++)
numbers[i] = 0;
int number = 0;
do
{
printf("Enter an integer; 0 to quit: ");
scanf_s("%d", &number);
if (number == 0)
break;
numbers[numbersEntered++] = number;
} while (number != 0 && numbersEntered < ARRAY_LENGTH);
if (numbersEntered > 0)
{
for (int i = numbersEntered - 1; i >= 0; i--)
printf("index %d -> %d\n", i, numbers[i]);
}
return 0;
}
I think it's because you are not inserting any number to the first place in the array (place[0]), because you are prompting the value of numbersEntered too early. Try to write your loop this way:
while (number != 0 && numbersEntered < ARRAY_LENGTH - 1){
numbers[numbersEntered] = number;
printf("Enter another integer; 0 to quit: ", ARRAY_LENGTH - 1);
scanf_s("%d", &number);
numbersEntered++;
}

C - nested for loop patern

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++ )

C Programming While Loop Assignment

Question: Take n as input. Then take n numbers as input and print the summation of those n numbers. But this time output as the format below.
Example:
Input:
4
1 5 3 -4
output 1 + 5 + 3 – 4 = 5
I got the output value correctly, but I do not know how am I going to show the actual summation sequence, especially in one line....
My Code:
main ()
{
int n,m,cnt=0,sum=0;
printf("Input: ");
scanf("%d", &n);
while(cnt<n)
{
scanf("%d\b", &m);
sum=sum+m;
cnt=cnt+1;
if(m>0 && m!=n)
{
printf("\b+",m);
}
else if (m<0)
{
printf("%d",m);
}
}
printf("=%d\n\n",sum);
}
Here's a sample solution that I came up with:
#include <stdio.h>
int main() {
int n = 0,
count = 0,
sum = 0;
int first = 1;
printf("How many numbers do you wish to sum? " );
scanf("%d", &n);
while (count < n) {
int m;
scanf("%d\b", &m);
if (!first) {
if (m < 0) {
printf("- %d ", -m);
} else {
printf("+ %d ", m);
}
} else {
first = !first;
printf("%d ", m);
}
sum += m;
count++;
}
printf("= %d\n\n", sum);
return 0;
}
Here's a sample execution:
$ gcc stackoverflow.c -o stackoverflow
$ ./stackoverflow
How many numbers do you wish to sum? 5
1 -2 -3 4 10 -40
1 - 2 - 3 + 4 + 10 = 10
If the summation sequence is to be printed after the input, the problem could be solved by using a dynamically allocated array int[] of length n in which the input is read. After the input is read, the actual summation can be done and the summands can be printed, as they have been stored in the array. The dynamic allocation can be done with the malloc function; you would also have to use the free function after the summation.
Catch!:)
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
unsigned int n = 0;
printf( "Enter number of items (0-exit): " );
scanf( "%u", &n );
if ( n != 0 )
{
int items[n];
printf( "Enter %u numbers: ", n );
unsigned int i = 0;
while ( i < n && scanf( "%d", &items[i] ) == 1 ) ++i;
int sum = 0;
_Bool first = 1;
n = i;
for ( i = 0; i < n; i++ )
{
sum += items[i];
if ( !first || items[i] < 0 )
{
printf( "%c ", items[i] < 0 ? '-' : '+' );
}
if ( first ) first = 0;
printf( "%u ", ( unsigned int )abs( items[i] ) );
}
printf( "= %d\n", sum );
}
return 0;
}
The output might look like
Enter number of items (0-exit): 4
Enter 4 numbers: 1 5 3 -4
1 + 5 + 3 - 4 = 5
#include <stdio.h>
int main()
{
int num;
int answer=0;
do
{
printf("\nEnter the number(s) to be added: (enter 0 to quit) ");
scanf("%d", &num);
answer=answer + num;
}
while (num!=0);
printf("Answer is %d", answer);
return 0;
}
Advantage of above approach is that you don't require an array and don't have to declare the no. of values that you are adding. Sort of like adding using a calculator where you simply press the "=" button when you are done.

finding a palindrome using arrays

i have this problem that i'm having troubles to solve.
the user needs to enter 15 numbers (whole numbers) and i need to check if there's a palindrome.
if there are more then one i must take the longest one, and if there are more then one with the same size, i must take the one whose index comes first. i.e:
Input:
1 2 1 3 5 6 7 8 9 4 5 6 8 9 8
Output:
Palindrome Found: 121
Input:
1 2 1 3 3 1 6 4 8 7 9 5 4 8 6
Output:
1 3 3 1
that is my code at the moment:
when i run it, the values of k and array1[k], seems to be an error. i've gor them back with the value 5373952.
even if there is a palindrome it call back that the palindrome was not found.
#include <stdio.h>
#include <stdlib.h>
int main()
{
double arr[15]={0};
int array1[15];
int i,j,k=0;
for (i=0; i<15; i++) // the program is asking for 15 numbers from the user.
{
scanf("%lf", &arr[i]);
if ((arr[i]-(int)arr[i])!= 0)// if the number is not a whole number, the program will stop immediately.
{
printf("Error \n");
return (0);
}
}
for (i=0; i<15; i++)
{
for(j=14; j>=i; j--) // going back-wards to the start. checking at each point for a match.
{
if ((int)arr[i]==(int)arr[j])
{
array1[k]=(int)arr[j];
i++;
j--;
k++;
break;
}
}
}
if ( (int)arr[j] == array1[k] )
{
printf("Palindrome Found:%d \n", array1[k]);
}
else
{
printf("Palindrome Not Found \n");
}
return (0);
}
The number must be between 0 and 9, or can be bigger? For example
1 2 13 22 16 4
Anyway, it's wise to work with the input as a string.
#include <stdio.h>
int main(void){
int arr[15]={0};
int i,j;
int start, end, max_len = 1;
for (i=0; i<15; i++){
if(1 != scanf("%1d", &arr[i]) || arr[i] < 0){
printf("input error\n");
return 1;
}
}
for(i = 0; i < 15 - max_len; ++i){
for(j=i+max_len; j<15; ++j){
if(arr[i]==arr[j]){
int found = 1;
int s, e, len = j - i + 1;
for(s=i, e=j; s < e; ++s, --e){
if(arr[s] != arr[e]){
found = 0;
break;
}
}
if(found && max_len < len){
start = i;
end = j;
max_len = len;
}
}
}
}
if(max_len == 1)
printf("Palindrome Not Found \n");
else {
printf("Palindrome Found:");
for(i=start; i<=end; ++i)
printf(" %d", arr[i]);
printf("\n");
}
return 0;
}

Resources