Scanning numbers from an array - c

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

Related

write a program that computes and displays the factorial of a positive integer n entered by the user

Been working on this question for class. Not sure what I'm doing wrong.
Seems like I just don't have the correct format. My professor wants the output to look like "5!=1 * 2* 3* 4* 5=120"
Can someone help me with this? Below is what I have so far:
#include <iostream>
#include <stdio.h>
int main() {
int n, i, fact;
printf("Enter a positive integer: \n");
scanf("%d", &n);
if (n < 0)
printf("Error! Factorial of a negative number doesn't exist.");
else {
for( i = 1; i <= n; ++i) {
fact *= i;
n= n * (n-1);
}
printf("Factorial of %d = ", &n, &fact) ;
}
return 0;
}
remove #include <iostream> if it is the C code
Use functions.
Initialize local variables (you do not and it is undefined behaviour)
Compile C program using C compilers
unsigned long long fact(unsigned val, char *buff)
{
unsigned result = 1;
*buff++ = '1';
*buff = 0;
for(unsigned c = 2; c <= val; c++)
{
buff += sprintf(buff, "x%u", c);
result *= c;
}
return result;
}
int main(void)
{
unsigned x;
char y[1000];
unsigned long long res;
if(scanf("%u", &x) == 1){res = fact(x, y); printf("factoral(%u) = %s = %llu\n", x, y, res);}
else printf("Invalid number!!!\n");
}
or without printing steps
unsigned long long fact(unsigned val)
{
unsigned result;
switch(val)
{
case 0:
case 1:
result = 1;
break;
case 2:
result = 2;
break;
default:
result = 2;
while(val > 2) result *= val--;
break;
}
return result;
}
int main(void)
{
unsigned x;
if(scanf("%u", &x) == 1) printf("factioral(%u) = %llu\n", x, fact(x));
else printf("Invalid number!!!\n");
}
https://godbolt.org/z/Tf5431zco
For starters it does not make a sense to declare the variable n as having a signed integer type. It is better to declare it as having unsigned integer type. For example
unsigned int n, i, fact;
Secondly the variable fact was not initialized. You should initialize it by the value equal to 1.
So the above declaration could look like
unsigned int n, i;
unsigned long long fact = 1;
In this for loop
for( i = 1; i <= n; ++i) {
fact *= i;
n= n * (n-1);
}
the statement
n= n * (n-1);
does not make a sense and shall be removed.
In the printf call you have to use values of variables instead of pointers to the variables like
printf("Factorial of %u = %llu\n", n, fact) ;
Pay attention to that neither declaration from the header <iostream> is used in your program So whether it is a C program or a C++ program nevertheless remove this header.
Here is a demonstration C program.
#include <stdio.h>
int main( void )
{
unsigned int n = 0;
unsigned long long int fact = 1;
printf( "Enter a positive integer: " );
scanf( "%u", &n );
printf( "%u! = ", n );
for ( unsigned int i = 1; i <= n; i++ )
{
fact *= i;
if ( i != 1 ) printf( " * " );
printf( "%u", i );
}
printf( " = %llu\n", fact );
}
The program output might look like
Enter a positive integer: 5
5! = 1 * 2 * 3 * 4 * 5 = 120
If you are allowed to use only variables of the type int as you wrote in a comment to the answer then the program can look like
#include <stdio.h>
int main( void )
{
int n = 0;
int fact = 1;
printf( "Enter a positive integer: " );
scanf( "%d", &n );
if ( n < 0 )
{
puts( "Error! Factorial of a negative number doesn't exist.");
}
else
{
printf( "%d! = ", n );
for ( int i = 1; i <= n; i++ )
{
fact *= i;
if ( i != 1 ) printf( " * " );
printf( "%d", i );
}
printf( " = %d\n", fact );
}
}
To output multipliers in the reverse order like
5! = 5 * 4 * 3 * 2 * 1 = 120
rewrite the for loop the following way
for ( int i = n; i != 0; i-- )
{
fact *= i;
if ( i != n ) printf( " * " );
printf( "%d", i );
}

Is there a way to display "number not found" after the forloop ends?

#include <stdio.h>
void main()
{
int n,i;
int arr[5]={5,4,3,2,1};
int *ptr;
printf("input the number you want to find:\n");
scanf("%d",&n);
for(i=0;i<5;i++)
if(arr[i]==n)
{
ptr=&arr[i];
printf("number '%d' is present in the array and it is the %d st/nd/rd/th term in the array.\n its address is: %d",n,i+1,ptr);
}
}
**>i added else printf("number not found"); here but its also looping and printing a lot **
Keep it simple... just add the print after the loop and add a return when you have a match.
Like:
#include <stdio.h>
int main(void)
{
int n,i;
int arr[5]={5,4,3,2,1};
int *ptr;
printf("input the number you want to find:\n");
if (scanf("%d",&n) != 1)
{
// Input error
exit(1);
}
for(i=0;i<5;i++)
{
if(arr[i]==n)
{
ptr=&arr[i];
printf("number '%d' is present in the array and it is the %d st/nd/rd/th term in the array.\n its address is: %p",n,i+1,(void*)ptr);
return 0; // Done... just end the program
}
}
puts("not found");
}
BTW:
Notice that it shall be int main(void)
Notice that pointers are to be printed using %p with a cast to (void*)
Just put the call of printf outside the for loop. For example
int *ptr = NULL;
printf("input the number you want to find:\n");
scanf("%d",&n);
for( i = 0; ptr == NULL && i < 5; i++ )
{
if ( arr[i] == n )
{
ptr = arr + i;
}
}
if ( ptr != NULL )
{
printf("number '%d' is present in the array and it is the %td st/nd/rd/th term in the array.\n its address is: %p\n",
n, ptr - arr + 1, ( void * )ptr );
}
else
{
printf( "number %d is not present in the array.\n", n );
}
Also do not use magic numbers like 5. Instead use named constants. And declare variables in minimal scopes where they are used.
And using the conversion specifier %d with a pointers has undefined behavior. You need to use the conversion specifier %p.
Here is a demonstrative program.
#include <stdio.h>
int main(void)
{
int arr[] = { 5, 4, 3, 2, 1 };
const size_t N = sizeof( arr ) / sizeof( *arr );
int n = 0;
printf( "input the number you want to find (default is %d): ", n );
scanf( "%d", &n );
int *ptr = NULL;
for ( size_t i = 0; ptr == NULL && i < N; i++ )
{
if ( arr[i] == n )
{
ptr = arr + i;
}
}
if ( ptr != NULL )
{
printf( "number '%d' is present in the array and it is the %td st/nd/rd/th term in the array.\n its address is: %p\n",
n, ptr - arr + 1, ( void * )ptr);
}
else
{
printf( "number %d is not present in the array.\n", n );
}
}
The program output might look like
input the number you want to find (default is 0): 3
number '3' is present in the array and it is the 3 st/nd/rd/th term in the array.
its address is: 0x7ffefecb1778
Always check the return value of the scanf!!
Initialize pointer to NULL. If nothing found it will remain NULL
Use the correct format for the address (%p), and cast pointer to (void *) before passing to printf
main return type is int.
int main()
{
int n;
int arr[]={5,4,3,5,2,5,1};
int *ptr = NULL;
printf("input the number you want to find:\n");
if(scanf("%d",&n) == 1)
{
for(size_t i=0;i<sizeof(arr)/ sizeof(arr[0]);i++)
if(arr[i]==n)
{
ptr=&arr[i];
printf("number '%d' is present in the array and it is the %zu st/nd/rd/th term in the array.\n its address is: %p",n,i+1, (void *)ptr);
}
if(!ptr) printf("NUMBER NOT FOUND!!!!!\n");
}
else
{
printf("SCANF ERROR\n");
}
}
https://godbolt.org/z/6zcE4nnz8

How to read only numbers from file until EOF in C

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

C: I keep getting errors that say error: expected expression

I keep getting five errors in my code that say error: expected expression when talking about the variables in my function. I have looked on this site and other places but I can't find what's wrong.
Here's the code:
#include <stdio.h>
#define TRUE 1
#define FALSE 0
void separate_digits (long int n);
void print_array ( int a[10] );
int digits_different ( int a[10] );
int divisible ( int a[10], int n );
int main ()
{
long int n;
printf("Enter a positive integer or 0 (zero) to end:");
scanf("%ld\n", &n);
while ( n != 0)
{
if (n < 0)
{
printf("Wrong input\n");
}
else
{
separate_digits (long int n);
}
printf("Enter a positive integer or 0 (zero) to end:");
scanf("%ld\n", &n);
}
printf("*** Program Terminated ***\n");
}
void separate_digits (long int n)
{
int a[10] = {0};
int digit;
int num = n;
while ( num > 0)
{
digit = num % 10;
++a[digit];
num = num / 10;
}
print_array ( int a[10] );
if ( a[0] != 0 )
{
printf("Wrong input for the second part.\n");
printf("Input should not contain zero.\n");
}
else if ( digits_different ( int a[10] ) == FALSE )
{
printf("Wrong input for the second part.\n");
printf("Input should not contain each digit more than once.\n");
}
else if ( divisible ( int a[10], int n ) == FALSE )
{
printf("%1ld is not divisible by its digits.\n", n);
}
else
{
printf("%1ld is divisible by its digits.\n", n);
}
}
void print_array ( int a[10] )
{
int i;
printf("\n\n\n");
printf("Digits: 0 1 2 3 4 5 6 7 8 9\n");
printf("Occurrences: ");
for (i = 0; i < 10; i++)
{
printf("a[i] ");
}
}
int digits_different ( int a[10] )
{
int i;
for (i = 0; i < 10; i++)
{
if (a[i] > 1)
return FALSE;
else
return TRUE;
}
}
int divisible ( int a[10], int n )
{
int i;
int num;
for (i = 0; i < 10; i++)
{
if (a[i] == 0)
continue;
else if (num % i != 0)
return FALSE;
}
return TRUE;
}
Here's the errors I keep getting:
Lab_Assignment_6_Sarah_H.c:27:21: error: expected expression
separate_digits (long int n);
^
Lab_Assignment_6_Sarah_H.c:53:16: error: expected expression
print_array ( int a[10] );
^
Lab_Assignment_6_Sarah_H.c:61:31: error: expected expression
else if ( digits_different ( int a[10] ) == FALSE )
^
Lab_Assignment_6_Sarah_H.c:67:24: error: expected expression
else if ( divisible ( int a[10], int n ) == FALSE )
^
Lab_Assignment_6_Sarah_H.c:67:35: error: expected expression
else if ( divisible ( int a[10], int n ) == FALSE )
You shouldn't be prepending your variables with a type name when you actually pass them to a function.
That's only required in the declarations for those functions, as you've done near the top of the code.
The function call syntax only takes the variable name, not the type.
separate_digits (long int n);
should be
separate_digits (n);
Also, print_array ( int a[10] ); is wrong, you only need to pass the array name to pass the array, like
print_array ( a );
and so on.
Related, quoting C11, chapter ยง6.5.2.1, Postfix operators, function call syntax
postfix-expression ( argument-expression-listopt )
and
argument-expression-list:
assignment-expression
argument-expression-list , assignment-expression
there, the "type" is not to be mentioned in argument list, it is
An argument may be an expression of any complete object type.
In other words, each element in the argument-expression-list need to have a type which is not to be written.
separate_digits (long int n); is not syntactically correct. This is confusing the compiler.
Drop the long int to give separate_digits (n);

Simple C Program is not getting printed

I am trying to run this simple code:
#include <stdio.h>
int main()
{
int n = 3;
printf("Enter your number: ");
scanf("%d",&n);
int faculty(int n){
int i = 1;
int res = 1;
for (i = 2;i<= n;i++){
res = res * i;
}
printf("the value is %d\n",res);
return(0);
}
}
But somehow there is no result showing up. Could you please explain me how it should be implemented properly?
Thanks in advance!
Please try this:
#include
int faculty( int n )
{
int i = 1;
int res = 1;
for ( i = 2; i <= n; i++ )
{
res = res * i;
}
printf( "the value is %d\n", res );
getchar( );
return ( 0 );
}
int main( )
{
int n = 3;
printf( "Enter your number: " );
scanf( " %d", &n );
faculty( n );
}

Resources