I'm trying to make a program that accepts 4 numbers, regardless if it is a whole or non-whole number. It will determine the largest non-whole number found in the inputs. If there are no non-whole numbers present, then it will print a message that there are none.
Here is my code:
#include <stdio.h>
int main()
{
float num1, num2, num3, num4;
//Enter Numbers
printf("Enter 4 Numbers : ");
scanf("%f %f %f %f", &num1, &num2, &num3, &num4);
//Numbers are Integer
if ((num1 - (int) num1) == 0
&& (num2 - (int) num2) == 0
&& (num3 - (int) num3) == 0
&& (num4 - (int) num4) == 0) {
printf("Output : No Non-Whole Numbers found\n");
} else {
//Numbers are Float
if (num1 > num2 && num1 > num3 && num1 > num4) {
printf("Output : %.1f\n", num1);
} else if (num2 > num1 && num2 > num3 && num2 > num4) {
printf("Output : %.1f\n", num2);
} else if (num3 > num1 && num3 > num2 && num3 > num4) {
printf("Output : %.1f\n", num3);
} else {
printf("Output : %.1f\n", num4);
}
}
}
But I have some problems with it, for example when a user inputs:
Enter 4 Numbers : 12.5 15 2 1
Output: 15
Instead it should be 12.5
Enter 4 Numbers : 10.5 10.5 7 8
Output: 8.0
Instead it should be 10.5
As Nils Martel pointed out this should be coded as a loop over an array.
The only difference from his implementation is that I think mine is easier to understand, because it's closer to the original code
#include <stdio.h>
#include <stdlib.h>
#define FALSE (0 != 0)
#define TRUE (!FALSE)
#define ABS(x) ((x >= 0) ? (x) : (-x))
#define NUMS 4
int is_whole(float num)
{
return (ABS(num) - (int)ABS(num)) == 0;
}
int main()
{
float nums[NUMS];
int contains_float = FALSE;
int largest = 0; // Initialized with the first element
//Enter Numbers
printf("Enter 4 Numbers : ");
scanf("%f %f %f %f", &nums[0], &nums[1], &nums[2], &nums[3]);
//Numbers are Integer
for (int i = 0; i < NUMS; ++i) {
if (is_whole(nums[i]) == FALSE) {
contains_float = TRUE;
// The additional condition here accounts for the case when
// nums[0] is the largest element in the array
if (nums[i] > nums[largest] || is_whole(nums[largest]))
largest = i;
}
}
if (contains_float)
printf("Output : %.1f\n", nums[largest]);
else
printf("Output : No Non-Whole Numbers found\n");
}
You can run it here https://onlinegdb.com/rkVwPZaZu
I think the best check for determining, if a number is non while would be
floor(n) != n
Now, In your code you repeat yourself quite often and your logic gets quite complex and hard to understand by just looking at it.
You might find this exercise a great moment, to learn more about arrays and loops!
I've tried to rewrite your code using the floor(n) != n check, and by using arrays and loops. Mind, my C is a little rusty, but I hope you can reason with my code:
#include <stdio.h>
#include <math.h>
void print_largest_non_while(float *numbers, int length) {
int is_set = 0;
float greatest;
for (int i = 0; i < length; i++) {
float n = numbers[i];
if (floor(n) != n) {
// n is a non while number
if (!is_set) {
is_set = 1;
greatest = n;
continue;
}
if (greatest < n) greatest = n;
}
}
if (is_set) printf("%f\n", greatest);
}
int main() {
float num[4];
// Enter Numbers
printf("Enter 4 Numbers : ");
scanf("%f %f %f %f", num, num + 1, num + 2, num + 3);
print_largest_non_while(num, 4);
}
Your test consider that all your numbers are not integers, or that they are all integers. Also consider that the test num1 - (int)num1) == 0 could give false results. Better: compare the abs of the difference to a threshold.
#define N 4
#include <stdio.h>
#include <math.h>
int main(){
float num[N];
//Enter Numbers
printf("Enter %d Numbers : ", N);
for (int i = 0; i < N; ++i) {
int t = scanf ("%f", &num[i]);
if (t != 1) return 1;
}
float eps = 1.0e-5;
int found = 0;
float vmax;
for (int i = 0; i < N; ++i) {
int check = fabs(num[i] - rint(num[i])) > eps;
found += check;
if (check) {
if (found == 1) {
vmax = num[i];
} else {
if (num[i] > vmax) {
vmax = num[i];
}
}
}
}
//Numbers are all Integer if found == 0
if(found == 0) {
printf("Output : No Non-Whole Numbers found\n");
} else {
printf("Output : %.1f\n", vmax);
}
return 0;
}
Related
I've made a program that checks if a given positive integer is a prime or perfect number.The problem I'm facing is I created a function "readNumber" that works as a check loop to ensure that input is a positive integer.But if I enter a negative value and then an acceptable one it shows previous values aswell.I attach a screenshot of the command prompt text to make myself more clear.
Below is my code
#include<stdio.h>
int checkperfectnumber(int);
int checkprimenumber(int);
int readNumber(int);
int main(){
int num, x, y, result;
printf("\nGive a positive integer number: \n");
scanf("%d",&num);
y = readNumber(num);
x = checkperfectnumber(num);
result = checkprimenumber(num);
if (num == 1)
printf("1 is nor a prime neither a perfect number");
else if (x == num)
printf("%d is a perfect number\n",num);
else if ( result == 1 )
printf("%d is a prime number.\n", num);
else
printf("%d is nor prime neither a perfect number.\n", num);
return 0;
}
//perfect number function
int checkperfectnumber(int numbr){
int a=1, sum=0;
while(a < numbr){
if(numbr % a == 0)
sum=sum+a;
a++;
}
return(sum);
}
//prime number function
int checkprimenumber(int a)
{
int c;
for ( c = 2 ; c <= a - 1 ; c++ )
{
if ( a%c == 0 )
return 0;
}
return 1;
}
//input check function
int readNumber(int b){
while (b < 0)
{
printf("Wrong input.\nPlease insert a positive integer.");
main();
break;
}
}
Quick fix is have the program exit after executing main() from readNumber().
To do this, Add #include <stdlib.h> and replace break; in the function readNumber() to exit(0);.
Better solution is having the function readNumber(), not main(), read numbers and stop calling main() recursively.
It will be like this:
#include<stdio.h>
int checkperfectnumber(int);
int checkprimenumber(int);
int readNumber(void);
int main(){
int num, x, y, result;
printf("\nGive a positive integer number: \n");
num = readNumber();
x = checkperfectnumber(num);
result = checkprimenumber(num);
if (num == 1)
printf("1 is nor a prime neither a perfect number");
else if (x == num)
printf("%d is a perfect number\n",num);
else if ( result == 1 )
printf("%d is a prime number.\n", num);
else
printf("%d is nor prime neither a perfect number.\n", num);
return 0;
}
//perfect number function
int checkperfectnumber(int numbr){
int a=1, sum=0;
while(a < numbr){
if(numbr % a == 0)
sum=sum+a;
a++;
}
return(sum);
}
//prime number function
int checkprimenumber(int a)
{
int c;
for ( c = 2 ; c <= a - 1 ; c++ )
{
if ( a%c == 0 )
return 0;
}
return 1;
}
//input check function
int readNumber(void){
for (;;)
{
int b;
scanf("%d",&b);
if (b >= 0) return b; /* 0 is not positive, but this condition is !(b < 0) */
printf("Wrong input.\nPlease insert a positive integer.");
}
}
This is my homework and i am stuck with how should i identify that the smallest/largest number is even or odd.
#include <stdio.h>
void main()
{
int num1,num2,num3;
printf("Enter three numbers\n");
scanf("%d %d %d",&num1,&num2,&num3);
if(num1<num2 && num1<num3){
printf("\n%d is the smallest",num1);
}
else if(num2<num3){
printf("\n%d is the smallest",num2);
}
else{
printf("\n%d is the smallest",num3);
}
if(num1>num2 && num1>num3){
printf("\n%d is largest",num1);
}
else if(num2>num3){
printf("\n%d is largest",num2);
}
else{
printf("\n%d is largest",num3);
}
getch();
return 0;
}
Use 2 variables, one to store the smallest, one to store the largest.
int min, max;
Then, assign the variable :
if (num1 < num2)
min = num1;
if (num3 < min)
min = num3;
printf("%d is the largest number", min);
To know if a number is odd or even, the remainder (also called modulo) of its division by 2 will be 0 (for even) or 1 (for odd) :
int modulo = min % 2;
if (modulo == 0)
printf("%d is even", min);
else
printf("%d is odd", min);
/*Write a program to find the largest and smallest among three entered numbers and
also display whether the identified largest/smallest number is even or odd*/
#include <stdio.h>
#include <conio.h>
void main()
{
// start the programme
int a, b, c, large, small;
printf("Enter three numbers : \n");
scanf("%d%d%d", &a, &b, &c);
if (a > b && a > c)
{
printf("\n%d is largest", a);
large = a;
}
else if (b > c)
{
printf("\n%d is largest", b);
large = b;
}
else
{
printf("\n%d is largest", c);
large = c;
}
if (a < b && a < c)
{
printf("\n%d is smallest", a);
small = a;
}
else if (b < c)
{
printf("\n%d is smallest", b);
small = b;
}
else
{
printf("\n%d is smallest", c);
small = b;
}
if (large % 2 == 0)
{
printf("\n %d is even", large);
}
else
{
printf("\n %d is odd", large);
}
if (small % 2 == 0)
{
printf("\n %d is even", small);
}
else
{
printf("\n %d is odd", small);
}
getch();
// end the programme
}
Here I am trying to find lowest common multiple of an array of numbers. I used the following formula to find the value which uses greatest common divisor to find out LCM.
My program calculates GCD correctly, but when it comes to find out LCM using GCD it gives wrong LCM value. What might be wrong in my logic. Any help would be much appreciated.
#include <stdio.h>
int main() {
int arr[10] = { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 };
int GCD = findGCD(arr[0], arr[1]);
int LCM = (arr[0] * arr[1]) / GCD;
int i;
for (i = 2; i < sizeof(arr) / sizeof(arr[0]); i++) {
int temp = GCD;
GCD = findGCD(temp, arr[i]);
LCM = (temp * arr[i]) / GCD;
}
printf("GCD IS %d AND LCM IS %d", GCD, LCM);
}
int findGCD(int num1, int num2) {
if (num2 == 0) {
return num1;
}
if (num1 % num2 == 0) {
return num2;
}
return findGCD(num2, num1 % num2);
}
Does this help? Or was your aim to calculate GCD and LCM while calling findGCD as few times as possible?
int main(){
int arr[10]={10,20,30,40,50,60,70,80,90,100};
int GCD=arr[0];
int LCM=arr[0];
int i;
for(i=1;i<sizeof(arr)/sizeof(arr[0]);i++){
GCD = findGCD(GCD,arr[i]);
LCM = (LCM * arr[i]) / findGCD(LCM, arr[i]);
}
printf("GCD IS %d AND LCM IS %d",GCD,LCM);
}
The above formula mentioned by you is true only for two numbers not multiple numbers(in your case 10). The correct formula say for 3 numbers is:
lcm(a,b,c)=abc/gcd(ab,bc,ca)
For more info refer this https://math.stackexchange.com/questions/319297/gcd-to-lcm-of-multiple-numbers
There are multiple problems in your code:
you compute the LCM for all elements of the array, but the GCD only for the 2 initial values.
multiplication formula might overflow before you divide by the GCD. You should perform the operation in the opposite order and still check for potential overflow.
the prototype for findGCD is incorrect: it returns an int.
Here is a corrected version:
#include <limits.h>
#include <stdio.h>
int findGCD(int num1, int num2) {
if (num2 == 0) {
return num1;
}
if (num1 % num2 == 0) {
return num2;
}
return findGCD(num2, num1 % num2);
}
int main() {
int arr[10] = { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 };
int GCD = arr[0];
int LCM = arr[0];
size_t i;
for (i = 1; i < sizeof(arr) / sizeof(arr[0]); i++) {
if (LCM == 0 || arr[i] == 0) {
LCM = 0;
break;
}
GCD = findGCD(GCD, arr[i]);
LCM = LCM / findGCD(LCM, arr[i]);
if (arr[i] > INT_MAX / LCM) {
printf("integer overflow: the LCM exceeds the range of type int\n");
return 1;
}
LCM = LCM * arr[i];
}
printf("GCD IS %d AND LCM IS %d", GCD, LCM);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#define VSTUP "cisla.txt"
#define VYSTUP "vystup.txt"
int nsd(int x,int y){
int delitel = (x < y) ? x : y;
while(x % delitel != 0 || y % delitel != 0)
delitel--;
return delitel;
}
int nsn(int x,int y){
int nasobek = (x > y) ? x : y;
while(nasobek % x != 0 || nasobek % y != 0)
nasobek += (x > y) ? x : y;
return nasobek;
}
int main(int argc, char** argv) {
FILE * vstup;
FILE * vystup;
int c1, c2;
int i = 1, j = 1;
vstup = fopen (VSTUP,"r");
if (vstup == NULL){
printf("Soubor %s nebyl otevren.\n",VSTUP);
return (EXIT_FAILURE);
}
vystup = fopen (VYSTUP,"w");
printf("Vypis cisel ze souboru %s\n-------------------------------- \n",VSTUP);
fprintf(vystup,"Vypis delitelnych cisel ze souboru %s\n--------------------------------------------\n",VYSTUP);
printf("%7s%7s%7s%7s%7s\n","poradi","cislo1","cislo2","nsn","nsd");
fprintf(vystup,"%7s%7s%7s%7s%7s\n","poradi","cislo1","cislo2","nsn","nsd");
while (fscanf(vstup,"%d %d",&c1,&c2) == 2){
printf("%6d.%7d%7d%7d%7d\n",i,c1,c2,nsn(c1,c2),nsd(c1,c2));
if (nsd(c1,c2) != 1){
fprintf(vystup,"%6d.%7d%7d%7d%7d\n",j,c1,c2,nsn(c1,c2),nsd(c1,c2));
j++;
}
i++;
}
printf("\nSoubor %s obsahuje %d dvojic cisel.\n\n",VSTUP,i-1);
fprintf(vystup,"\nSoubor %s obsahuje %d dvojic cisel.\n",VYSTUP,j-1);
if (fclose (vstup) == EOF)
printf("Soubor %s nebyl uzavren.\n",VSTUP);
if (fclose (vystup) == EOF)
printf("Soubor %s se nepovedlo vytvorit.\n",VYSTUP);
else
printf("Byl vytvoren soubor delitelnych cisel %s.\n\n",VYSTUP);
return (EXIT_SUCCESS);
}
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define VSTUP "cisla.txt"
#define VYSTUP "vystup.txt"
int mocnina (int z, int e){
int v = 1;
for(;e > 0;e--)
v *= z;
return v;
}
int prvocislo(int n){
int i;
for(i = 2; i <= sqrt(n); ++i) {
if (n % i == 0)
return 0;
}
return 1;
}
int main(int argc, char** argv) {
FILE * vstup;
FILE * vystup;
int z,e;
int i = 1, j = 1;
vstup = fopen (VSTUP,"r");
if (vstup == NULL){
printf("Soubor %s nebyl otevren.\n",VSTUP);
return (EXIT_FAILURE);
}
vystup = fopen (VYSTUP,"w");
printf("Vystup cisel ze souboru %s\n",VSTUP);
printf("---------------------------------\n");
printf("%6s%9s%9s%9s\n","poradi","zaklad","exponent","mocnina");
fprintf(vystup,"Vystup cisel s prvociselnym zakladem ze souboru %s\n",VYSTUP);
fprintf(vystup,"---------------------------------------------------------\n");
while( fscanf (vstup,"%d %d",&z,&e) == 2){
printf("%5d.%9d%9d%9d\n",i,z,e,mocnina(z,e));
if (prvocislo(z)){
fprintf(vystup,"%5d.%8d%8d%8d\n",j,z,e,mocnina(z,e));
j++;
}
i++;
}
fprintf(vystup,"Soubor %s obsahuje %d dvojic cisel.\n",VYSTUP,j-1);
if (fclose (vstup) == EOF)
printf("Soubor %s nebyl uzavren.\n",VSTUP);
if (fclose (vystup) == EOF)
printf("Soubor %s se nepovedlo vytvorit.\n\n",VYSTUP);
else
printf("\nByl vytvoren soubor cisel %s s poctem dvojic cisel rovnym %d.\n\n",VYSTUP,j-1);
return (EXIT_SUCCESS);
}
Well I have been assigned to do the prime factorisation for composite numbers, but the problem is I have hard-coded it till prime numbers:2,3,5,7,11,13,19 and I want to make it general.
#include <stdio.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void prime(int flag,int num);
int main()
{
int num, flag, i, div;
printf("Enter your number: ");
scanf("%d", &num);
flag = 1;
prime(flag, num);
printf("Press any key to exit.");
getchar();
return 0;
}
void prime(int flag, int num)
{
void factor(int num, int i);
int sq, i, square;
sq = abs(sqrt(num));
if (num == 2)
flag = 1;
else
for (i = 2; i <= sq; i++)
{
if (num % i == 0)
{
flag = 0;
break;
}
else
flag = 1;
}
if (flag == 1)
printf("\n%d is a prime number", num);
else
{
printf("\n%d is not a prime number\n", num);
factor(num, i);
}
}
void factor(int num, int i)
{
for (i = 2; i <= num; i++)
{
again:
if(num % i == 0)
{
num = num / i;
printf("%d x", i);
if (num != (2||3||5||7||11||17||19))
goto again;
}
}
printf("1\n\n");
}
P.S.:Try to make it as simpler as possible.
The problem is after dividing it with smallest prime. i.e. 2 the next step should be check the number whether it is a prime or not. If not, then factorise it but I dont know how to do it.
Plz help.
Thx in advance.
#include <stdio.h>
void factor(int num);
int main(void){
int num;
printf("Enter positive number(more than 1): ");
if(1 != scanf("%d", &num) || num < 2){
printf("invalid input!\n");
return -1;
}
scanf("%*[^\n]");scanf("%*c");//clear upto line end
factor(num);
printf("Press any key to exit...");
getchar();
return 0;
}
void factor(int num){
int i, flag = 0;
if(num == 2){
printf("\n%d is a prime number\n", num);
return ;
}
while(!(num & 1)){
if(!flag)
printf("\n%d is not a prime number\n", num);
flag = 1;
printf("2 x ");
num >>= 1;
}
for (i = 3; i*i <= num; i += 2){
while(num % i == 0){
if(!flag)
printf("\n%d is not a prime number\n", num);
flag = 1;
printf("%d x ", i);
num /= i;
}
}
if(!flag)
printf("\n%d is a prime number\n", num);
else if(num != 1)
printf("%d x 1\n\n", num);
else
printf("1\n\n");
}
Replace line,
if (num!=2&& num!=3 && num!=5 && num!=7 && num!=11 && num!=17 && num!=19)
instead of,
if (num!=2||3||5||7||11||17||19)
In function factor, first try dividing by 2 repeatedly, then try every odd number while said odd number squared is less or equal to num. This simple method is a bit redundant as you try and divide by composite numbers, but since you will already have removed all smaller prime factors, num will not be divisible by such composite numbers. Iterating while i * i <= num will stop much earlier than with your current i <= num test.
Try and write code to implement the above algorithm and post it as an edit.
This question already has answers here:
How to convert a string to integer in C?
(13 answers)
Closed 6 years ago.
I was working on a class project and I wanted to do a little bit extra and make validation on my data. The problem seems to happen at num1 = num1Input (and num2 = num2Input) where it is getting the location (I assume) instead of the actual input value
int main(void) {
//variables
char num1input[10];
char num2input[10];
int length, i;
int num1 = 0;
int num2 = 0;
int countErrors1 = 0;
int countErrors2 = 0;
bool correct1 = false;
bool correct2 = false;
//--end of variable declarations--//
do {
printf("Please enter a number: ");
scanf("%s", num1input);
length = strlen(num1input);
for (i = 0; i < length; i++) {
if (!isdigit(num1input[i])) {
countErrors1++;
}
}
if (countErrors1 > 0) {
printf("Input is not a number \n");
} else {
correct1 = true;
}
} while (correct1 == false);
num1 = num1input;
do {
printf("Please enter second number: ");
scanf("%s", num2input);
length = strlen(num2input);
for (i = 0; i < length; i++) {
if (!isdigit(num2input[i])) {
countErrors2++;
}
}
if (countErrors2 > 0) {
printf("Input is not a number \n");
} else {
correct2 = true;
}
} while (correct2 == false);
num2 = (int)num2input;
printf("%d %d \n", num1, num2);
int addition = num1 + num2;
int substraction = num1 - num2;
int multiplication = num1 * num2;
float division = num1 / num2;
printf("Addition: %d Subtraction: %d Multiplication: %d Division: %.1e", addition, substraction, multiplication, division);
getch();
}
You cannot convert a string to a number with a cast such as num1 = num1input;. You need to call a library function from <stdlib.h>:
#include <stdlib.h>
...
num1 = atoi(num1input);
But atoi ignores parsing errors. To ensure that overflows are detected, you can use strtol() as follows:
#include <errno.h>
#include <limits.h>
#include <stdlib.h>
...
errno = 0;
char *endp;
long lval = strtol(num1input, &endp, 10);
if (endp == num1input || errno != 0 || lval < INT_MIN || lval > INT_MAX) {
/* parse error detected:
* you could print an error message.
*/
if (lval < INT_MIN) lval = INT_MIN; /* clamp lval as an int value. */
if (lval > INT_MAX) lval = INT_MAX;
}
num1 = lval;
Or if you want to recognize hexadecimal syntax such as 0x10:
num1 = strtol(num1input, NULL, 0);
The same is applicable for num2input.
Note that isdigit(num1input[i]) is potentially incorrect if char is signed and num1input[i] has a negative value. You should write:
isdigit((unsigned char)num1input[i])
Also note that float division = num1 / num2; will compute the integer division and convert the result to a float. If you want the floating point division, you should write:
float division = (float)num1 / num2;
Note finally that it is recommended to use double instead of float for better accuracy.
Here is a corrected and simplified version:
#include <errno.h>
#include <limits.h>
#include <stdlib.h>
#include <stdio.h>
/* simple implementation of strtoi(), inspired by elegant code from chux */
int strtoi(const char *s, char **endptr, int base) {
long y = strtol(s, endptr, base);
#if INT_MAX != LONG_MAX
if (y > INT_MAX) {
errno = ERANGE;
return INT_MAX;
}
#endif
#if INT_MIN != LONG_MIN
if (y < INT_MIN) {
errno = ERANGE;
return INT_MIN;
}
#endif
return (int)y;
}
int main(void) {
char num1input[20];
char num2input[20];
char *endp;
int num1, num2;
for (;;) {
printf("Please enter a number: ");
if (scanf("%19s", num1input) != 1)
return 1;
errno = 0;
num1 = strtoi(num1input, &endp, 10);
if (errno == 0 && *endp == '\0')
break;
printf("Input is not a number\n");
}
for (;;) {
printf("Please enter a second number: ");
if (scanf("%19s", num2input) != 1)
return 1;
errno = 0;
num2 = strtoi(num2input, &endp, 10);
if (errno == 0 && *endp == '\0')
break;
printf("Input is not a number\n");
}
printf("%d %d\n", num1, num2);
int addition = num1 + num2;
int subtraction = num1 - num2;
int multiplication = num1 * num2;
double division = (double)num1 / num2;
printf("Addition: %d Subtraction: %d Multiplication: %d Division: %g\n",
addition, subtraction, multiplication, division);
getch();
}