I have this function to find the max and min value of numbers in file with uknown text("ADS 50 d 15"). It works fine with only digits in the file, but when there is a characters it just stops.
{
int n;
int min = INT_MAX, max = INT_MIN;
int flag = 0;
rewind(f);
while (fscanf(f, "%d", &n) != EOF)
{
if (ferror(f))
{
perror("Error:");
}
if (flag == 0)
{
min = n;
max = n;
flag = 1;
}
if (min>n)
min = n;
if (max<n)
max = n;
}
printf("\nMax value: %d\nMin value: %d\n", max, min);
}
fscanf will return EOF after reaching the end of the file. It will return 1 on successful scanning an integer. If the input is not an integer, it will return 0 and the problem input has to be removed.
{
int n;
int min = INT_MAX, max = INT_MIN;
int result = 0;
char skip = 0;
rewind ( f);
while ( ( result = fscanf ( f, "%d", &n)) != EOF)
{
if (result == 0)
{
fscanf ( f, "%c", &skip);//remove a character and try again
}
else
{
if (min>n)
min = n;
if (max<n)
max = n;
}
}
printf("\nMax value: %d\nMin value: %d\n", max, min);
Try the following approach as it is shown in this demonstrative program. You have to use the fscanf instead of scanf used in this program.
#include <stdio.h>
#include <ctype.h>
int main( void )
{
int min, max;
size_t n = 0;
while ( 1 )
{
char c;
int x = 0;
int success = scanf( "%d%c", &x, &c );
if ( success == EOF ) break;
if (success != 2 || !isspace( ( unsigned char )c ) )
{
scanf("%*[^ \t\n]");
clearerr(stdin);
}
else if ( n++ == 0 )
{
min = max = x;
}
else if ( max < x )
{
max = x;
}
else if ( x < min )
{
min = x;
}
}
if ( n )
{
printf( "\nThere were enetered %zu values\nmax value: %d\nMin value: %d\n",
n, max, min );
}
return 0;
}
If the input looks like
1 2 3 4 5a a6 7 b 8
then the output will be
There were enetered 6 values
max value: 8
Min value: 1
Related
I am starter in the C.I wrote a simple code which are calculating how many digits are the entered Number and sum of entered number’s digits.Code calculating digit count right but sum of digits being given as ‘0’ every time.Could you say where is my error?thanks.
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
int ndigit(int val) {
if (val == 0)
return 0;
int digit_count = 1;
while ((val = getchar() != '\n')) {
digit_count++;
val /= 10;
}
return digit_count;
}
int sumdigit(int number) {
int result = 0;
while ((number = getchar()) != '\n'){
result += number - '0';
}
return result;
}
int main()
{
int a;
printf("Bir tam sayi giriniz: \n");
a = getchar();
printf("Bu sayinin basamak sayisi =%d", ndigit(a));
printf("Bu sayinin basamak degeri toplami= %d", sumdigit(a));
}
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
The program does not make sense. To enter a number you should use one function. That is the number of digits and the sum of digits must be calculated for the same number.
This condition in the while statement
while ((val = getchar() != '\n')) {
is equivalent to
while ( ( val = ( getchar() != '\n' ) ) ) {
and as a result the integer val gets either 1 or 0.
As the variable val stores an internal representation of a character (for example its ASCII value) then this statement
val /= 10;
also does not make sense. Also the user can enter a non-digit character.
You should either use a character array for the entered number by means of calls of the function getchar or use the function scanf to enter a value of an integer object.
If to use a character array then the program can look the following way
#include <stdio.h>
char * get_number( char *number, size_t n )
{
size_t i = 0;
int c;
while( i + 1 < n && ( c = getchar() ) != EOF && c != '\n' && '0' <= c && c <= '9' )
{
number[i++] = c;
}
number[i] = '\0';
return number;
}
size_t ndigit( const char *number )
{
size_t n = 0;
while ( number[n] != '\0' ) ++n;
return n;
}
unsigned int sumdigit( const char *number )
{
unsigned int sum = 0;
while ( *number != '\0' )
{
sum += *number++ - '0';
}
return sum;
}
int main(void)
{
enum { N = 50 };
char number[N];
printf( "Bir tam sayi giriniz: " );
get_number( number, N );
printf( "Bu sayinin basamak sayisi = %zu\n", ndigit( number ) );
printf( "Bu sayinin basamak degeri toplami = %u\n", sumdigit( number ) );
return 0;
}
The program output might look like
Bir tam sayi giriniz: 123456789987654321
Bu sayinin basamak sayisi = 18
Bu sayinin basamak degeri toplami = 90
If to use an integer number then the program can look the following way
#include <stdio.h>
size_t ndigit( unsigned long long number )
{
const unsigned long long Base = 10;
size_t n = 0;
do
{
++n;
} while ( number /= Base );
return n;
}
unsigned int sumdigit( unsigned long long number )
{
const unsigned long long Base = 10;
unsigned int sum = 0;
do
{
sum += number % Base;
} while ( number /= Base );
return sum;
}
int main(void)
{
unsigned long long number = 0;
printf( "Bir tam sayi giriniz: " );
scanf( "%llu", &number );
printf( "Bu sayinin basamak sayisi = %zu\n", ndigit( number ) );
printf( "Bu sayinin basamak degeri toplami = %u\n", sumdigit( number ) );
return 0;
}
The program output might look as it is shown above.
Bir tam sayi giriniz: 123456789987654321
Bu sayinin basamak sayisi = 18
Bu sayinin basamak degeri toplami = 90
You code has 3 getchar() that are independent. Just use one getchar, either in main, or ndigit or sumdigit.
I propose, you should get the number in main function using scanf instead of getchar(), then pass the number as the argument to the other functions (ndigit and sumdigit). Because getchar reads character by character, and it does not guarantee the character is a digit or not.
The main function becomes:
int main () {
int num;
printf("enter the number: ");
scanf("%d", &num);
// calling the ndigit and sumdigit function:
printf("sum of digits = %d\n number of digits = %d\n", sumdigit(num), ndigit(num));
return 0;
}
For two function ndigit and sumdigit, you can change to:
ndigit function:
int ndigit(int number) {
number = abs(number); // calculate abs if the number is negative
if(number == 0)
return 1;
int count = 0;
do {
count++;
num /= 10;
} while(num != 0);
return count;
}
sumdigit function:
int sumdigit(int number) {
number = abs(number); // calculate abs if the number is negative
int sum = 0, temp = 0;
while (number != 0) {
temp = number % 10;
sum += temp;
number /= 10;
}
return sum;
}
The complete code:
#include <stdio.h>
#include <stdlib.h>
int ndigit(int number) {
number = abs(number); // calculate abs if the number is negative
if(number == 0)
return 1;
int count = 0;
do {
count++;
number /= 10;
} while(number != 0);
return count;
}
int sumdigit(int number) {
number = abs(number); // calculate abs if the number is negative
int sum = 0, temp = 0;
while (number != 0) {
temp = number % 10;
sum += temp;
number /= 10;
}
return sum;
}
int main () {
int num;
printf("enter the number: ");
scanf("%d", &num);
// calling the ndigit and sumdigit function:
printf("sum of digits = %d\nnumber of digits = %d\n", sumdigit(num), ndigit(num));
return 0;
}
The output of test:
enter the number: 222333
sum of digits = 15
number of digits = 6
After using scanf, change your sumdigit while loop to:
while (number > 0) {
result += number % 10;
number /= 10;
}
in my program the user enters an array and the pc generates a random array (with the max number picked from user) and then the program creates a third array that shows the number from the first array that are not in the second . however i only want to type the numbers once each but the program types them again and again until array is full .
for example if i entered 0 3 1 and generated number was 1 5 9 it would print 0 3 3
i want to print 0 3 only .
full code :
#include <stdio.h>
#define N 7
void input(int ar1[N]);
void max(int* mx);
int input2(int ar2[N], int mx);
int input3(int ar3[N], int ar1[N], int ar2[N]);
int main()
{
int ar1[N], mx, ar2[N], ar3[N], i;
input(ar1);
max(&mx);
input2(ar2, mx);
input3(ar3, ar1, ar2);
printf("array1 = %d %d %d %d %d %d %d\n", ar1[0], ar1[1], ar1[2], ar1[3], ar1[4], ar1[5], ar1[6]);
printf("array2 = %d %d %d %d %d %d %d\n", ar2[0], ar2[1], ar2[2], ar2[3], ar2[4], ar2[5], ar2[6]);
printf("array3 = %d %d %d %d %d %d %d\n", ar3[0], ar3[1], ar3[2], ar3[3], ar3[4], ar3[5], ar3[6]);
}
void input(int ar1[N])
{
int i;
printf("Enter 7 numbers: ");
for (i = 0; i < N; i++)
scanf("%d", &ar1[i]);
}
void max(int* mx)
{
printf("Enter random number bigger than 0 :- ");
scanf("%d", mx);
if (mx < 0)
{
printf("you have entered a number smaller than 0 please enter a number bigger than 0 :-");
scanf("%d", mx);
}
return mx;
}
int input2(int ar2[N], int mx)
{
int i;
srand(time(0));
for (i = 0; i < N; i++)
{
ar2[i] = 0 + rand() % (mx - 0 + 1);
printf("%d ", ar2[i]);
}
return ar2;
}
int input3(int ar3[N], int ar1[N], int ar2[N])
{
int i, j, a = 0;
for (i = 0; i < N; i++)
{
if (ar1[i] != ar2[0] && ar1[i] != ar2[1] && ar1[i] != ar2[2] && ar1[i] != ar2[3] && ar1[i] != ar2[4] && ar1[i] != ar2[5] && ar1[i] != ar2[6])
a = ar1[i];
ar3[i] = a;
}
return ar3;
}
Thanks for your help.
the following proposed code:
handles the problems exposed in the comments to the question
cleanly compiles
has some 'appropriate' horizontal spacing added for readability
caveat: I have not verified that the OPs posted logic is correct.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define N 7
// prototypes
void input ( int ar1[N] );
void max ( unsigned* mx );
void input2( int ar2[N], int mx );
void input3( int ar3[N], int ar1[N], int ar2[N] );
int main( void )
{
int ar1[N];
int mx;
int ar2[N];
int ar3[N];
srand( (unsigned)time(0) );
input( ar1 );
max( (unsigned*)&mx );
input2( ar2, mx );
input3( ar3, ar1, ar2 );
printf( "array1 = %d %d %d %d %d %d %d\n",
ar1[0], ar1[1], ar1[2], ar1[3], ar1[4], ar1[5], ar1[6] );
printf( "array2 = %d %d %d %d %d %d %d\n",
ar2[0], ar2[1], ar2[2], ar2[3], ar2[4], ar2[5], ar2[6] );
printf( "array3 = %d %d %d %d %d %d %d\n",
ar3[0], ar3[1], ar3[2], ar3[3], ar3[4], ar3[5], ar3[6] );
} // end function: main
void input( int ar1[N] )
{
printf( "Enter 7 numbers: " );
for ( size_t i = 0; i < N; i++ )
{
if( 1 != scanf("%d", &ar1[i]) )
{
perror( "scanf failed" );
exit( EXIT_FAILURE );
}
}
} // end function: input
void max( unsigned* mx )
{
printf("Enter random number bigger than 0 :- ");
if( 1 != scanf("%u", mx) )
{
perror( "scanf failed" );
exit( EXIT_FAILURE );
}
} // end function: max
void input2( int ar2[N], int mx )
{
for ( size_t i = 0; i < N; i++ )
{
ar2[i] = 0 + rand() % (mx - 0 + 1);
printf("%d ", ar2[i]);
}
} // end function: input2
void input3( int ar3[N], int ar1[N], int ar2[N] )
{
int a = 0;
for (size_t i = 0; i < N; i++)
{
if( ar1[i] != ar2[0]
&& ar1[i] != ar2[1]
&& ar1[i] != ar2[2]
&& ar1[i] != ar2[3]
&& ar1[i] != ar2[4]
&& ar1[i] != ar2[5]
&& ar1[i] != ar2[6] )
a = ar1[i];
ar3[i] = a;
}
} // end function: input3
IIUC your problem can be reduced to removing duplicates from the array. I tried to fix it and hope that it works for you:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <assert.h>
#define N 7
void input(int ar1[N]);
int max(int * mx);
int input2(int ar2[N], int mx);
static int compact(int *array, int size)
{
int i;
int last = 0;
assert(size >= 0);
if (size <= 0)
return size;
for (i = 1; i < size; i++)
{
if (array[i] != array[last])
array[++last] = array[i];
}
return(last + 1);
}
int i, a = 0;
int j = 0;
static void print(int *array, int size, const char *tag, const char *name)
{
int k;
printf("%s\n", tag);
for (k = 0; k < i-j; k++)
printf("%s[%d] = %d\n", name, k, array[k]);
}
int * input3(int ar3[N], int ar1[N], int ar2[N]);
int main() {
int ar1[N], mx, ar2[N], ar3[N], i;
input(ar1);
max(&mx);
input2(ar2, mx);
input3(ar3, ar1, ar2);
int a_size = sizeof(ar3) / sizeof(ar3[0]);
a_size = compact(ar3, a_size);
print(ar3, a_size, "\nAnswer:", "a");
printf("array1 = %d %d %d %d %d %d %d\n", ar1[0], ar1[1], ar1[2], ar1[3], ar1[4], ar1[5], ar1[6]);
printf("array2 = %d %d %d %d %d %d %d\n", ar2[0], ar2[1], ar2[2], ar2[3], ar2[4], ar2[5], ar2[6]);
}
void input(int ar1[N]) {
int i;
printf("Enter %d numbers: ", N);
for (i = 0; i < N; i++)
scanf("%d", &ar1[i]);
}
int max(int *mx) {
printf("Enter random number bigger than 0 :- ");
scanf("%d", mx);
if (mx < 0) {
printf("you have entered a number smaller than 0 please enter a number bigger than 0 :-");
scanf("%d", mx);
}
return * mx;
}
int input2(int ar2[N], int mx) {
int i;
srand(time(0));
for (i = 0; i < N; i++) {
ar2[i] = 0 + rand() % (mx - 0 + 1);
printf("%d ", ar2[i]);
}
return * ar2;
}
int * input3(int ar3[N], int ar1[N], int ar2[N]) {
for (i = 0; i < N; i++) {
if (ar1[i] != ar2[0] && ar1[i] != ar2[1] && ar1[i] != ar2[2] && ar1[i] != ar2[3] && ar1[i] != ar2[4] &&
ar1[i] != ar2[5] && ar1[i] != ar2[6]) {
//a = ar1[i];
ar3[i-j] = ar1[i];
}
else {
++j;
continue;
}
}
return ar3;
}
Test
Enter 7 numbers: 2 4 6 8 9 11 12
Enter random number bigger than 0 :- 12
3 12 1 6 2 8 9
Answer:
a[0] = 4
a[1] = 11
array1 = 2 4 6 8 9 11 12
array2 = 3 12 1 6 2 8 9
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
So I need to make a C program that prints out the highest number inputed.
If the input is empty it shouldn't print anything.
If the input includes anything else than a number it shouldn't print anything.
example:
If the input is 1 2 3 2 1 it should print out 3.
If the input is 1 2 a 2 1 it shouldn't print out anything.
This is what i got so far:
#include <stdio.h>
int main()
{
int res, max, x;
res = scanf("%d", &max);
if (res == 1) {
while(res != EOF)
{
res = scanf("%d", &x);
if (x > max)
{
max=x;
}
}
printf("%d", max);
} else {
return 0;
}
return 0;
}
So my question is, how do i make it print out nothing if it contains a letter like in the example above.
Thank in advance!
#include <stdio.h>
int main()
{
int max, x;
if (scanf("%d", &max) != 1)
{
// If there is no number, exit the program.
return 0;
}
while ( scanf("%d", &x) == 1 )
{
if (x > max)
{
max=x;
}
}
// If we came to the EOF, we didn't see any bad input.
if ( feof(stdin) )
{
printf("Max: %d\n", max);
}
return 0;
}
#include <stdio.h>
int main(void){
int res, max, x;
if(1 != scanf("%d", &max))
return -1;
while(EOF != (res = scanf("%d", &x))){
if(res != 1)
return -1;
if (x > max){
max = x;
}
}
printf("%d\n", max);
return 0;
}
If the input is a number, scanf will return 1
#include <stdio.h>
int main()
{
int max, x;
int result;
if (scanf("%d", &max) != 1)
return -1;
x = max;
do {
result = scanf("%d[^\n]", &x);
if ((result != EOF) && (result != 1))
return 0;
else if ((result != EOF) && (x > max))
max = x;
} while (result != EOF);
printf("\n\nMaximum Input : %d\n", max);
return 0;
}
the previous program will stop when there is invalid input, i.e. something that is not a number.
So I created an dynamic array in C. The array contains only numbers. How can I scan the 1D array I created to print how many numbers are greater than the last one in the array? I created the code for scanning the file only, which is the following:
#include <stdio.h>
#include <limits.h>
int process( FILE *f ) {
int a, b;
static int total = 1;
if ( f == 0 ) return 0;
if ( fscanf( f, "%d", &a ) != 1 ) return INT_MIN;
if ( (b= check_file ( f )) == INT_MIN ) return a;
if ( a > b )
{total++; return printf( "%d > %d and total now is %d\n", a, b, total ), a; }
return b;
}
int main( void ) {
FILE *fp= fopen( "xxx.txt", "r" );
process( fp );
fclose( fp );
return 0;
}
Can I make the same with the array? How can I do that? Which commands should I use?
Dynamic array:
#include <stdio.h>
#include <stdlib.h>
int main ()
{
int t_size;
FILE * fp;
fp = fopen ("xxx.txt", "r");
fscanf(fp, "%d", &t_size);
printf("Create a size of %d array\n", t_size);
int* my_array = NULL;
my_array = malloc(t_size*sizeof(*my_array));
if (my_array==NULL) {
printf("Error allocating memory!\n"); //print an error message
return 1; //return with failure
getchar();
}
int i =0;
for ( i = 0; i < t_size; i++ )
{
fscanf(fp, "%d",&my_array[i]);
}
//if all is working smoothly...
printf("All up and running! Array created! :D\n");
for(i = 0; i < t_size; i++ )
{
printf(" %d : %d\n", i, my_array[i]);
}
getchar();
free(my_array);
}
You have to:
Add all the numbers from your file to the array (int arr[N], where N is number of the elements)
Find the value of the last element in the array (arr[N-1])
Go through the array and count how many are greater then the last one.
#include <stdio.h>
#include <limits.h>
int process( int *array, int *endp) {
int a, b;
if ( array == 0 ) return 0;
if ( array == endp ) return INT_MIN;
else a = *array++;
if ( (b= process( array, endp )) == INT_MIN ) return a;
if ( a > b ) return printf( "%d > %d\n", a, b ), a;
return b;
}
int main( void ) {
int array[] = { 4, 3, 2, 1};
int t_size = 4;
process(array, array + t_size);
return 0;
}