This is what i get This code needs to print out 2 maximum numbers, when -999 is entered the code needs to stop.
I tried every thing but most of the times i get the maximum number but not the second maximum number.
#include <stdio.h>
int main ()
{
int x = 0;
int max = 0;
int max2 = 0;
int y = 0;
int flag = 0;
do
{
printf("Enter the number -999 to stop: ");
scanf("%d", &x);
if (x != -999)
{
if (x > max)
{
max = x;
max2 = y;
}
printf("Enter the number -999 to stop: ");
scanf("%d", &y);
if (y != -999)
{
if (y > max)
{
max = y;
max2 = x;
}
}
else
{
flag = 1;
}
}
else
{
flag = 1;
}
}
while (flag == 0);
printf("The max number is: %d\n", max);
printf("The second max number is: %d\n", max2);
return 0;
}
#include <stdio.h>
int main ()
{
int x = 0;
int max = 0;
int max2 = 0;
int flag = 0;
do
{
printf("Enter the number -999 to stop: ");
scanf("%d", &x);
if (x != -999)
{ // bigger than max?
if (x > max)
{
// since the new max is x and the old max is bigger than max2
max2 = max;
max = x;
}
// bigger than max2?
else if (x > max2)
{
max2 = x;
}
}
else // exit loop
{
flag = 1;
}
}
while (flag == 0);
printf("The max number is: %d\n", max);
printf("The second max number is: %d\n", max2);
return 0;
}
There are more problems in your code.
You have unnecessary two inputs (x and y), then you wrongly assume, when x > max, then y contains second max, and when y > max then x contains second max.
Correct code should look like this:
int main()
{
int x = 0;
int max = 0;
int max2 = 0;
while (true)
{
printf("Enter the number (-999 to stop): ");
scanf("%d", &x);
if (x == -999)
{
break;
}
if (x > max)
{
max2 = max;
max = x;
}
else if (x > max2)
{
max2 = x;
}
}
printf("\n\nThe max number is: %d\n", max);
printf("The second max number is: %d\n", max2);
return 0;
}
Related
I'm writing a program where the user enters numbers and the program will find MAX and MIN and the position of these numbers. I want to give the user a choice for the program to fill in the numbers for him using rand().
It's working almost perfectly: the program will find the MAX number with the position but the problem occurs when printing MIN number with position -- it always prints number 8 and position 1.
Where is the problem?
Here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
typedef struct elementposition {
int min;
int max;
int positionMax;
int positionMin;
} elementposition;
int main() {
struct elementposition minmax;
srand(time(NULL));
int a[500], i;
int c = sizeof(a) / sizeof(a[0]);
char y;
printf("How many numbers you want to enter: ");
scanf("%d", &c);
minmax.positionMax = minmax.positionMin = 0;
printf("Want to fill with random numbers? (Y/N)");
scanf(" %c", &y);
if (y == 'Y' || y == 'y') {
for (i = 0; i < c; i++) {
a[i] = rand() % 10000 + 1;
if (minmax.max < a[i]) {
minmax.max = a[i];
minmax.positionMax = i;
}
if (minmax.min > a[i]) {
minmax.min = a[i];
minmax.positionMin = i;
}
}
for (i = 0; i < c; i++) {
printf("Number #%d: %d\n", i + 1, a[i]);
}
} else {
printf("------------------------------------ \n");
printf("Enter (%d) numbers: \n", c);
scanf("%d", &a[0]);
minmax.max = minmax.min = a[0];
for (i = 1; i < c; i++) {
scanf("%d", &a[i]);
if (minmax.max < a[i]) {
minmax.max = a[i];
minmax.positionMax = i;
}
if (minmax.min > a[i]) {
minmax.min = a[i];
minmax.positionMin = i;
}
}
}
printf("\nMax number is %d, number position %d. \n", minmax.max, minmax.positionMax + 1);
printf("Min number is %d, number position %d. \n", minmax.min, minmax.positionMin + 1);
printf("------------------------------------ \n");
getch();
return 0;
}
You never initialize minmax.min nor minmax.max in the random case. The code has undefined behavior because it depends on uninitialized values which may be anything, including trap values on some rare architectures.
You should separate the input/generation phase from the scanning phase and use a common loop for that. Also check that c is positive and does not exceed the length of the array.
Here is a modified version:
#include <stdio.h>
#include <stdlib.h>
typedef struct elementposition {
int min;
int max;
int positionMax;
int positionMin;
} elementposition;
int main() {
struct elementposition minmax;
int a[500];
int i, count, len = sizeof(a) / sizeof(a[0]);
char y = 'y';
printf("How many numbers you want to enter: ");
if (scanf("%d", &count) != 1 || count < 1 || count > len) {
printf("invalid count\n");
return 1;
}
printf("Want to fill with random numbers? (Y/N)");
scanf(" %c", &y);
if (y == 'Y' || y == 'y') {
srand(time(NULL));
for (i = 0; i < count; i++) {
a[i] = rand() % 10000 + 1;
printf("Number #%d: %d\n", i + 1, a[i]);
}
} else {
printf("Enter (%d) numbers:\n", c);
for (i = 0; i < count; i++) {
if (scanf("%d", &a[i]) != 1) {
printf("invalid input\n");
return 1;
}
}
}
minmax.positionMax = minmax.positionMin = 0;
minmax.max = minmax.min = a[0];
for (i = 1; i < count; i++) {
if (minmax.max < a[i]) {
minmax.max = a[i];
minmax.positionMax = i;
}
if (minmax.min > a[i]) {
minmax.min = a[i];
minmax.positionMin = i;
}
}
printf("------------------------------------\n");
printf("Max number is %d, number position %d.\n", minmax.max, minmax.positionMax + 1);
printf("Min number is %d, number position %d.\n", minmax.min, minmax.positionMin + 1);
printf("------------------------------------\n");
getch();
return 0;
}
You use minmax.min and minmax.max before initializing them. Here the problem for finding the min is probably that the minmax.min happens to initialy contain the value 8 and that all the values are greater.
The common way is to initialize the min to the highest possible value and max to the lowest one. As you use int values:
struct elementposition minmax = { INT_MAX, INT_MIN };
should be enough.
So I've tried to calculate the average of the positive and negative entries made in the while loop but I can't seem to enter any type of number into the console. So I need to enter numbers as long as it's not zero and add the positive numbers as well as negative numbers. I'm required to count how many positive and negative entries were entered. I need also to print the average of the positive and negatives entries.
Here is my code:
int num;
int positivenum = 0, negativenum = 0;
int cpositive = 0, cnegative = 0;
float average = 0;
printf("Enter a positive and negative integer:");
while (num!=0)
{
scanf("%d", &num);
if (num > 0){
positivenum += num;
cpositive++;
}
else if (num < 0){
negativenum += num;
cnegative++;
}
This is exactly when do while is judicious:
int num;
int positivenum = 0, negativenum = 0;
int cpositive = 0, cnegative = 0;
printf("Enter a positive and negative integer:");
do
{
scanf("%d", &num);
if (num > 0){
positivenum += num;
cpositive++;
}
else if (num < 0){
negativenum += num;
cnegative++;
}
} while (num!=0);
if (cpositive > 0)
printf("Average of positive numbers: %f\n", (double)positivenum / (double)cpositive);
if (cnegative > 0)
printf("Average of negative numbers: %f\n", (double)negativenum / (double)cnegative);
Changed the type of your counts from int to unsigned (negative counts doesn't make sense). Also moved the prompt inside the loop and and wrote a function to calculate the average:
#include <stdio.h>
void average(const char *what, int value, unsigned count) {
if(!count) return;
printf("average of %s numbers: %f\n", what, (float) value / count);
}
int main() {
int num;
int positivenum = 0, negativenum = 0;
unsigned cpositive = 0, cnegative = 0;
for(;;) {
printf("Enter a positive and negative integer: ");
scanf("%d", &num);
if(!num) break;
if(num < 0) {
negativenum += num;
cnegative++;
continue;
}
positivenum += num;
cpositive++;
}
average("positive", positivenum, cpositive);
average("negative", negativenum, cnegative);
}
#include <stdio.h>
int main() {
int num;
int positivenum = 0, negativenum = 0;
int cpositive = 0, cnegative = 0;
int range = 0;
int i = 0;
printf("Enter the range.\n");
scanf("%d", &range);
printf("Enter a positive and negative integer:\n");
do
{
scanf("%d", &num);
if (num > 0){
positivenum += num;
cpositive++;
}
else if (num < 0){
negativenum += num;
cnegative++;
}
i++;
} while ( (num!=0) && (i < range));
if (cpositive > 0)
printf("Average of positive numbers: %f\n", (float)positivenum / (float)cpositive);
if (cnegative > 0)
printf("Average of negative numbers: %f\n", (float)negativenum / (float)cnegative);
}
I have also added a range to break the loop.
I am trying to show the sum of the prime factors of a given number and
I'm having difficulties displaying the prime factors in my output.
Sample Output:
Input number: 6
Factors are: 1 2 3
Sum of its factor: 1 +2 +3 =6
I am able to show the sum but I want to show the 1+2+3=6 like in the sample above where the factors are 1 2 3.
Can you help me correct my syntax to achieve this? Thanks in advance.
Here's my code:
#include <stdio.h>
int main() {
int i, j, num, isPrime, sum;
printf("Input number: ");
scanf("%d", &num);
printf("Factors are: ", num);
for (i = 1; i <= num; i++) {
if (num % i == 0) {
isPrime = 1;
for (j = 2; j <= i / 2; j++) {
if (i % j == 0) {
isPrime = 0;
break;
}
}
if (isPrime == 1) {
printf("%d ", i);
sum += i;
}
}
}
printf("\nSum of its factor : %d", sum);
return 0;
}
Your code actually has undefined behavior because sum is not initialized to 0. It produces the correct sum only by chance.
You can store the factors in an array, or even construct the expression as you go with sprintf. The maximum length of the expression is not very large as there can be at most 9 different prime factors (29!! > 232)
Here is a modified version:
#include <stdio.h>
int main() {
char expr[9 * 11 + 1];
int i, j, pos, num, isPrime, sum;
printf("Input number: ");
if (scanf("%d", &num) != 1)
return 1;
printf("Factors are: 1"); // always include 1
pos = 0;
expr[pos] = '\0';
sum = 1;
for (i = 2; i <= num; i++) {
if (num % i == 0) {
isPrime = 1;
for (j = 2; j * j <= i; j++) {
if (i % j == 0) {
isPrime = 0;
break;
}
}
if (isPrime == 1) {
pos += sprintf(expr + pos, "+%d", i);
printf(" %d", i);
sum += i;
}
}
}
printf("\nSum of its factors: 1%s = %d\n", expr, sum);
return 0;
}
Output:
Input number: 6
Factors are: 1 2 3
Sum of its factors: 1+2+3 = 6
Here is a more robust and much faster version that does not have undefined behavior for very large values of num:
#include <stdio.h>
int main() {
char expr[9 * 11 + 1];
int i, pos, num;
unsigned sum;
printf("Input number: ");
if (scanf("%i", &num) != 1)
return 1;
printf("Factors are: 1"); // always include 1
pos = 0;
expr[pos] = '\0';
sum = 1;
for (i = 2; num / i >= i; i++) {
if (num % i == 0) {
pos += sprintf(expr + pos, "+%d", i);
printf(" %d", i);
sum += i;
do { num /= i; } while (num % i == 0);
}
}
if (num != 1) {
pos += sprintf(expr + pos, "+%d", num);
printf(" %d", num);
sum += num;
}
printf("\nSum of its factors: 1%s = %u\n", expr, sum);
return 0;
}
Test:
Input number: 0x7fffffff
Factors are: 1 2147483647
Sum of its factors: 1+2147483647 = 2147483648
Since you want to print all the prime factors twice, you should do that in a way so that you can avoid duplicated code. Here is an idea:
#include <stdio.h>
/* Return the smallest prime that is smaller than or equal to n */
/* Assumes that the argument is greater than 1 */
int getFirst(int n)
{
int i;
for(i = 2; i <= n; i++)
if(n % i == 0)
return i;
}
int main()
{
int num, x, tmp, sum=0;
scanf("%d", &num);
tmp = num;
printf("Factors are: ");
while(1) {
x = getFirst(tmp);
printf("%d ", x);
if (x == tmp) /* If we are at the last prime */
break;
tmp /= x;
}
printf("\n");
printf("Sum of factors is: ");
tmp = num;
while(1) {
x = getFirst(tmp);
printf("%d ", x);
sum += x;
if(x == tmp) /* If we are at the last prime */
break;
printf("+ ");
tmp /= x;
}
printf("= %d\n", sum);
}
But as has been pointed out in the comments. 1 is not a prime, and that's why I excluded it.
This program uses an array and three functions to read inputs, sum up the ones and tens place of inputted integers, and compute the average of input integers. Why can't I get more than one input that is a positive integer? The program runs after one input that is within the limits of integers that are valid.
#include <stdio.h>
int read_data(int Ar[]);
void comp_sums(int Ar[], int size); // prototypes
double comp_avg(int Ar[], int size);
int main()
{
int Ar[100];
int size;
double avg;
size = read_data(Ar);
comp_sums(Ar, size);
avg = comp_avg(Ar, size);
printf("The average of the integers in the array: %lf\n", avg);
}
int read_data(int Ar[]) // reads inputted integers, stores in array
{
int flag;
char ch;
int i,j, num;
flag = 1;
i = 0;
while (flag == 1) {
printf("Please enter an integer:\n");
j = scanf("%d", &num);
if (j != 1) {
break;
}
if (num < 0) {
continue;
} else if (num >= 100) {
flag = 0;
} else {
Ar[i] = num;
i++;
}
return i;
}
}
void comp_sums(int Ar[], int size) /* computes sum of ones and tens place of the inputted integers into the array*/
{
int i, j;
int sum_ones, sum_tens;
sum_ones = 0;
sum_tens = 0;
for (i = 0; i < size; i++) {
sum_ones += Ar[i] % 10;
j = Ar[i] / 10;
sum_tens += j % 10;
}
printf("The sum of the ones is: %d\n", sum_ones);
printf("The sum of the tens is: %d\n", sum_tens);
}
double comp_avg(int Ar[], int size) // computes average of integers
{
int i, sum;
double avg;
sum = 0;
for (i = 0; i < size; i++) {
sum += Ar[i];
}
avg = (double)size / sum;
return avg;
}
When you take an array as an argument, you have to take the length as well,
because you have to check if you are reading/writing out of bounds. Forget for a
second that the return is at that incorrect position, the user can input more
values than the array can hold and you are doing nothing to prevent the buffer overflow.
So to fix your read_data function:
int read_data(int Ar[], size_t len)
{
if(Ar == NULL || len == 0)
return 0;
int i = 0, j, num;
// imortant to check the bounds
while (i < len) {
printf("Please enter an integer:\n");
j = scanf("%d", &num);
if (j != 1) {
break;
}
if (num < 0) {
continue;
} else if (num >= 100) {
break;
} else {
Ar[i] = num;
i++;
}
}
return i;
}
I removed the flag bit because if num >=100, you would be ending the loop
anyway, so it's much simpler to do a break. Also the intention is more clearer.
Now you can call it:
int main()
{
int Ar[100];
int size;
double avg;
size = read_data(Ar, sizeof Ar / sizeof *Ar);
...
}
The problem is that you call return inside the whileloop. So as soon as you get a valid number, you'll return from the function.
Move it outside the loop. Like:
while (flag == 1) {
printf("Please enter an integer:\n");
j = scanf("%d", &num);
if (j != 1) {
break;
}
if (num < 0) {
continue;
} else if (num >= 100) {
flag = 0;
} else {
Ar[i] = num;
i++;
}
// return i; Incorrect
}
return i; // Correct
The function "strike" has to return the number of times that the user's input are equivalent.
Assume, the random number is 1234.
if the user's input has one of the random's numbers, then strike1++.
e.g., if my input is 5152 then strike1 will be 2.
if my input is, 1112, then strike will be again 2.
I'm getting wrong output in strike1. Any ideas how to solve it?
(I don't want to solve it with arrays)
Solution:
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
int hit(int num);
int strike(int num);
int rndNum(int num);
void main()
{
int num = 0;
int chosenNum;
int saveHits, saveStrikes;
srand(time(NULL));
printf("The Random number: %d", chosenNum = rndNum(num));
printf("\nPlease enter a 4 digit number: ");
scanf("%d", &num);
saveHits = hit(num, chosenNum);
saveStrikes = strike(num, chosenNum);
printf("\nThe number of hits: %d", saveHits);
printf("\nThe number of strikes: %d", saveStrikes);
getch();
}
int rndNum(int num)
{
int rndNum = rand() % 9000 + 1000;
return rndNum;
}
int hit(int num1, int chosenNum1)
{
int i, hit1 = 0;
for (i = 0; i < 4; i++)
{
if (num1 % 10 == chosenNum1 % 10)
hit1++;
num1 /= 10;
chosenNum1 /= 10;
}
return hit1;
}
int strike(int num1, int chosenNum1)
{
int i, strike1 = 0, n = 1;
int temp = num1, temp2 = chosenNum1;
for (i = 0;i < 4;i++)
{
while (n > 0)
{
if (temp > 0)
{
if ((temp % 10 == temp2 % 10))
{
strike1++; n--;
}
else
temp /= 10;
}
else
n--;
}
temp2 /= 10;
n = 1;
temp = num1;
}
return strike1;
}
int strike(int num1, int chosenNum1)
{
int i, strike1 = 0, n = 1;
int temp = num1, temp2 = chosenNum1;
for (i = 0;i < 4;i++)
{
while (n > 0)
{
if (temp > 0)
{
if ((temp % 10 == temp2 % 10))
{
strike1++; n--;
}
else
temp /= 10;
}
else
n--;
}
temp2 /= 10;
n = 1;
temp = num1;
}
return strike1;
}