C - store even numbers until end-of-input - c

I am trying to create a C program that reads standard input until it reaches the end-of-input, then store the even numbers to an array and prints it.
I don't know why my program isn't working as intended. Any help would be appreciated.
#include <stdio.h>
int main(){
int num = getchar();
int list[10000];//array to store even nums
int i = 0;
while(num != EOF){
if(num % 2 == 0){
list[i] = num;//store even nums
i++;
}
num = getchar();
}
for(int j = 0;j < i;j++){
printf("%d ",list[j]);
}
return 0;
}
//example output from terminal
Test 8 (1 1 2 3 5 8 13 21 34) - failed (Incorrect output)
Your program produced these 1 lines of output:
10 10 50 10 10 10 56 10 10 50 10 52 10
Last line of output above was not terminated with a newline('\n') character
The correct 1 lines of output for this test were:
2 8 34
The difference between your output(-) and the correct output(+) is:
- 10 10 50 10 10 10 56 10 10 50 10 52 10
+ 2 8 34
The input for this test was:
1
1
2
3
5
8
13
21
34

If you only get one line of input you don't have to store all numbers, just print them:
#include <stdio.h>
int main(void)
{
int num;
while (scanf("%d", &num) == 1) {
if(num % 2 == 0)
printf("%d ", num);
}
putchar('\n'); // from your output it is clear that
// a newline at the end is expected.
return 0;
}
If you have to handle multiple lines:
#include <stddef.h>
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
size_t capacity = 0;
int *numbers = NULL;
size_t count = 0;
int input;
while (scanf("%d", &input) == 1) {
if(input % 2 == 0) {
if(count == capacity) {
capacity += 10;
numbers = realloc(numbers, capacity * sizeof(int));
}
numbers[count++] = input;
}
}
for(size_t i = 0; i < count; ++i)
printf("%d ", numbers[i]);
putchar('\n');
free(numbers);
return 0;
}

getchar() reads only one char at a time, you need to use a function that reads a complete input.
scanf("%d", &num);
or better yet fgets and strtol:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define N 10000
int main(void)
{
int list[N];
int num, i = 0;
char buf[32], *ptr;
while ((i < N) && fgets(buf, sizeof buf, stdin)) {
if (buf[0] == '\n') {
break;
}
num = (int)strtol(buf, &ptr, 10);
if (*ptr != '\n') { // not a valid number
continue;
}
if (num % 2 == 0) {
list[i] = num; //store even nums
i++;
}
}
for (int j = 0; j < i; j++) {
printf("%d ", list[j]);
}
printf("\n");
return 0;
}

Related

How to stop at a specific number using loops

So I'm trying to code something that when entered an integer will stop at a certain place.
That is n % 7 == 1;
for example, I'm I input 5, and I want it to stop at n % 7 == 1;
(User inputs 5 stops till 8 which is n % 7 == 1)
#include <stdio.h>
int main ()
{
int nDay, I , nStop;
scanf("%d", &nDay);
nStop = nDay % 7 ==1;
if(nStop != 1)
{
for (i=nDay; i == nDay % 7 == 1; i++)
{
printf("%d", nDay);
}
return 0;
The problem is it is only printed once, is there a way to code this using loops only?
#include <stdio.h>
int main()
{
int num, i = 5;
// printf("Enter the number:\n");
// scanf("%d", &num);
num = 5;
while(i % 7 != 1){
printf("%d\n", i);
i++;
}
return 0;
}
If you feel and problem in understanding the code than just visualize the code using this website http://pythontutor.com/visualize.html#mode=edit

Count repeated numbers in a file

So I'm having this file myFile.txt with the following numbers in it: 1 2 3 4 5 6 7 8 9 0 2 3 4 5 6 6 5 4 3 2 1. I'm trying to write a program that calculates how many times a number from 0 to 9 is repeated, so it would be printed out like that Number %d repeats %d times. Right now I'm stuck at printing out the n number of elements of that file, so in example, if I would like to calculate how many times the 15 first numbers repeat themselves, firstly I would print out those 15 numbers, then the number of times each number repeats. But when I'm trying to print out those 15 numbers, it prints me this: 7914880640-10419997104210821064219560-1975428800327666414848.
Here's the code:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
int main() {
FILE *fp;
fp = fopen("myFile.txt", "r");
char c;
int n, i, count = 0;
for (c = getc(fp); c != EOF; c = getc(fp)) {
if (!(c == ' '|| c == '\n'))
count = count + 1;
}
printf("The amount of numbers is:%d\nTill which element of the list would you like to count the amount of the each element: \n", count);
scanf("%d", &n);
int a[n];
if (n <= count) {
for (i = 0; i < n; i++) {
fscanf(fp, "%d", &a[i]);
}
for (i = 0; i < n; i++) {
printf("%d", a[i]);
}
} else {
printf("Error");
}
fclose(fp);
return 0;
}
That's the final solution.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
int count_occur(int a[], char exist[], int num_elements, int value)
{
int i, count = 0;
for (i = 0; i<num_elements; i++)
{
if (a[i] == value)
{
if (exist[i] != 0)
return 0;
++count;
}
}
return(count);
}
int main()
{
int a[100],track[10];
FILE *fp;
fp = fopen("myFile.txt", "r");
char c,exist[20]= {0};
int n,i,num,count=0,k=0,eval;
for (c = getc(fp); c != EOF; c=getc(fp))
{
if (!(c==' '|| c=='\n'))
count=count+1;
}
rewind(fp);
printf("The amount of numbers is:%d\nTill which element of the list would you like to count the amount of the each element: \n", count);
scanf("%d", &n);
if (n<=count)
{
while(fscanf(fp, "%d", &num) == 1)
{
a[k] = num;
k++;
}
for (i=0; i<n; i++)
{
printf("%d ", a[i]);
}
}
else
{
printf("Error");
}
fclose(fp);
if (n<=count)
{
for (i = 0; i<n; i++)
{
eval = count_occur(a, exist, n, a[i]);
if (eval)
{
exist[i]=1;
printf("\nNumber %d was found %d times\n", a[i], eval);
}
}
}
return 0;
}

Printing biggest even number with multiple scanf

I would like to get an output of the biggest even number. but when I input 1 2 3 (3 calls to scanf) the output is 4.
#include <stdio.h>
#include <stdlib.h>
int main() {
int ary[100];
int x, y = 0;
int amount;
scanf("%d", &amount);
fflush(stdin);
for (x = 1; x <= amount; x++) {
scanf("%d", &ary[x]);
if (ary[x] % 2 == 0) {
if (ary[0] < ary[x]) {
ary[0] = ary[x];
}
}
}
printf("%d", ary[0]);
getchar();
return 0;
}
Before the loop initialize ary[0] for example the following way (otherwise uninitialized value of ary[0] is used in the program)
ary[0] = 1;
then substitute these if statements
if(ary[x]%2==0)
{
if(ary[0]<ary[x])
for
if( ary[x]%2==0 && ( x == 1 || ary[0]<ary[x] ) )
And at last write
if ( ary[0] != 1 ) printf("%d",ary[0]);
Take into account that this call
fflush(stdin);
has undefined behavior and should be removed.
In fact there is no need to declare an array. Without the array the program can look like
#include <stdio.h>
int main( void )
{
unsigned int n;
int max_even = 1;
printf("How many numbers are you going to enter: ");
scanf("%u", &n);
int x;
for (unsigned int i = 0; i < n && scanf( "%d", &x ) == 1; i++)
{
if ((x % 2) == 0 && (max_even == 1 || max_even < x))
{
max_even = x;
}
}
if (max_even != 1)
{
printf("maximum entered even number is %d\n", max_even);
}
else
{
puts("None even number was enetered");
}
return 0;
}
Its output might look like
How many numbers are you going to enter: 10
0 1 2 3 4 5 6 7 8 9
maximum entered even number is 8
#include <stdio.h>
#include <stdlib.h>
int main() {
int ary[100];
int ary[0 = 0;
int x, y = 0;
int amount;
scanf("%d", &amount);
fflush(stdin);
for (x = 1; x <= amount; x++) {
scanf("%d", &ary[x]);
if (ary[x] % 2 == 0) {
if (ary[0] < ary[x]) {
ary[0] = ary[x];
}
}
}
printf("%d", ary[0]);
getchar();
return 0;
}
Your code does not work because ary[0] is not yet initialized the first time you compare its value to the value read, furthermore it might not be even for the other comparisons.
You should use an indicator telling you whether an even value has been seen.
Here is a solution:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int has_even = 0, max_even = 0, value, amount, x;
if (scanf("%d", &amount) != 1)
return 1;
for (x = 0; x < amount; x++) {
if (scanf("%d", &value) != 1)
break;
if (!has_even || value > max) {
max_even = value;
has_even = 1;
}
}
if (has_even)
printf("%d\n", max_even);
else
printf("no even value\n");
getchar();
return 0;
}

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

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