Basic While Loop Precedence (C) - c

I'm new to coding and am learning C. I just had a question regarding while loops.
#include <stdio.h>
int main(void) {
int integer1, integer2, number, sum, largest, smallest;
float average;
integer1 = 0;
number = 0;
sum = 0;
largest = integer1;
smallest = integer1;
while (integer1 != -1) {
printf("Enter the number: ");
scanf_s("%d", &integer1);
number++;
sum = sum + integer1;
if (integer1 >= largest) {
largest = integer1;
}
if (integer1 <= smallest) {
smallest = integer1;
}
}
average = (float) sum / number;
printf("The number of user's input: %d.\n", number);
printf("The sum of input numbers: %d.\n", sum);
printf("The average of input numbers: %.2f.\n", average);
printf("The largest number is: %d.\n", largest);
printf("The smallest number is %d.\n", smallest);
return 0;
}
The objective of the code I've written is to:
Read integer values from the user.
Terminate the while loop when the user enters '-1'.
Output the printf statements with their corresponding values.
Here's the problem: All of the integer variables that I've declared should NOT include the value of '-1; inputted by the user. I assume that this has to do with an issue of precedence regarding the while loop, but I can't seem to pinpoint what it is. Any help or insight is greatly appreciated.
Thank you!

Sometimes neither while nor do/while loop fit your needs, because the decision to exit the loop must be made in the middle of loop's body.
Reading values and deciding what to do after the read presents one of such situations. A common solution is to set up an infinite loop, and exit it from the middle on a break:
for (;;) {
printf("Enter the number: ");
scanf_s("%d", &integer1);
if (integer1 == -1) {
break;
}
... // The rest of your code
}

In order to achieve what you want you need to add one line.
//use infinite loop
while (1) {
printf("Enter the number: ");
scanf_s("%d", &integer1);
//jump out of the loop because the loop has already started.
//but the value was -1
if (integer == -1) break;
number++;
sum = sum + integer1;
if (integer1 >= largest) {
largest = integer1;
}
if (integer1 <= smallest) {
smallest = integer1;
}
}

Just add your scanf() statement prior to your while loop.

Related

Printing the number with highest sum of devisors

i have a homework but i cant get the answer
I need to write a program in C...
Here is what is needed: You need to enter "n" natural number as input , and from all the natural numbers smaller than "n" , its needed to print the number which has the highest sum of devisors.
For exp: INPUT 10 , OUTPUT 8
Can anyone help me somehow?
I would really appreciate it !
i tried writing a program for finding the devisor of a number but i cant get far from here
#include <stdio.h>
int main() {
int x, i;
printf("\nInput an integer: ");
scanf("%d", &x);
printf("All the divisor of %d are: ", x);
for(i = 1; i < x; i++) {
if((x%i) == 0){
printf("\n%d", i);
}
}
}
I have implemented using function which will takes input number from user and then return the sum of divisor. hope this is one you looking for
/* function to return of sum of divisor
** input: x: integer number from user input
** return sum: sum of divisor of x
*/
int sum_of_divisor(int x)
{
int sum = 0;
for(int i = 1; i < x; i++)
{
if((x%i) == 0)
{
printf("%d\n", i);
sum = sum+i;
}
}
return sum;
}
int main() {
int x, i;
printf("\nInput an integer: ");
scanf("%d", &x);
printf("All the divisor of %d are: ", x);
printf("the sum of divisor is %d ", sum_of_divisor(x));
return 0;
}
Output:
Input an integer: 10
All the divisor of 10 are: 1
2
5
the sum of divisor is 8
After checking if i is a divisor of x, you should then store that value in another variable, for example m.
Repeat until a new divisor i is higher than that number. Add this new value to m.

Receiving non-zero exit status when filling an array dynamically from user input

#include <stdio.h>
int main(void){
int inputNumber;
int counter=0;
int totalValue;
int arr[counter];
int avg;
puts("Please enter any number of positive whole numbers you would like to be averaged. Enter ' -1 ' when you are finished for your result.\n");
while(scanf("%d\n", &arr[counter])){
if(arr[counter] = -1){
break;
}
if(arr[counter] > 0){
totalValue += arr[counter];
++counter;
}
else if(arr[counter]<=0){
puts("Please enter a positive number.");
}
else{
}
}
avg = totalValue/counter;
printf("The average of your entered values is: %d", avg);
return 0;
}
I have attempted many things to try and stop it, and although this may come from a lack of knowledge is there really any way to do this other than creating an enormously large array?
I tried using a dynamic array with calloc() but i was met with the same errors. I am unsure what else is available as an option in this method.
The code is supposed to take the average of "n" user inputted values.
You do not need an array.
Quick & dirty but easier that you wanted to do
int number = 0;
int counter = 0;
int total = 0;
while (number != -1)
{
total += number;
++counter;
scanf("%d", &number);
}
printf("average = %d\n", total / (counter - 1) );

find the most frequent number in an array

I've recently started learning C and I ran into this small test.
Make a code which reads 10 numbers from a user.
Print the Largest & Smallest entered values then print the most frequent number.
Making everything was simple for me but the most-frequent number is driving me crazy, I've searched for awhile and couldn't find any clear answers.
The code I wrote
#include <stdio.h>
#include <stdlib.h>
int main()
{
int hi[10], i=0, largest, smallest;
while(i<10)
{
printf("Enter a number:");
scanf("%d", &hi[i]);
i++;
}
smallest = hi[0];
largest = hi[0];
printf("Entered Numbers: ");
while(i!=0)
{
if(hi[10-i] < smallest) { smallest = hi[10-i]; }
if(hi[10-i] > largest) { largest = hi[10-i]; }
printf("%d | ", hi[10-i]);
i--;
}
printf("\nLargest number is = %d || Smallest number is = %d", largest, smallest);
return 0;
}
The only idea I thought of was:
Making another array.
Getting value of [i] in the original array.
Compare [i] with rest of values of original array (if they are equal or not).
Increment the value of the other array if they are equal.
Check largest value in the other array and that should be most frequent number.
Now, I know the order of most frequent element and how many times that element was entered.
Using a hashmap would be more efficient. There you can use the input number as key and set the value to 1. When a new number was given by the user, you just have to check wether the new number is already in the map. If so, you set the value to two, otherwise you add the new number with the value 1.
Piggy backing on what Markus said, a hash map really is ideal for a universal solution so you can keep the asymptotic time down, but since you're only doing an array of 10, using a 2D array to store the frequency will work just fine.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int hi[10][2], i=0,j=0,largest, smallest;
while(i<10)
{
printf("Enter a number:");
scanf("%d", &hi[i][0]);
i++;
}
smallest = hi[0][0];
largest = hi[0][0];
printf("Entered Numbers: ");
while(i!=0)
{
hi[10-i][1] = 0;
if(hi[10-i][0] < smallest) { smallest = hi[10-i][0]; }
if(hi[10-i][0] > largest) { largest = hi[10-i][0]; }
printf("%d | ", hi[10-i][0]);
i--;
}
int most_freq = 0;
for (i = 0; i < 10; i++){
for (j = 0; j < 10; j++){
if(hi[i][0] == hi[j][0]){
hi[i][1]++;
if (hi[i][1] > most_freq){
most_freq = hi[i][0];
}
}
}
}
printf("\nLargest number is = %d || Smallest number is = %d", largest, smallest);
printf("\nMost frequent is = %d\n", most_freq);
return 0;
}

C Program to list Armstrong Numbers upto 1000

#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int i , n , sum=0, rem;
clrscr();
for(i=1;i<=1000;i++)
{
while(i!=0)
{
rem = i%10;
sum = sum + pow(rem,3);
i = i / 10;
}
if(i == sum)
printf("\n %d", i);
}
getch();
}
I tried the above code for printing Armstrong Numbers upto 1000 . The output that I got was a list of zeros. I am not able to find the error in the code. Thanks in advance :)
You should keep a copy of i, so that it could be kept for comparison with the sum variable.
As of now, you compare sum and i, at every step when i has become 0.
You should use a temp variable to store value of i(before performing i/=10).
Also, you can't keep i in the while-loop as it would always be 0, and hence post increment will have no effect on it. You should need another temporary variable, say div.
And, you should finally print temp.
Also, an Armstrong number is an n-digit number that is equal to the sum of the nth powers of its digits.
So, for 1000, you need to caclculate the 4th power.
int temp,div;
for(i=1;i<=1000;i++)
{
temp = i;
div = i;
while(div!=0)
{
rem = div%10;
sum = sum + pow(rem,3);
div = div / 10;
}
if(temp == sum)
printf("\n %d", temp);
}
NOTE :- Probably you're using Turbo C compiler(check that header <conio.h>), which you shouldn't(you should avoid it). You should use GCC(on Linux system), CodeBlocks IDE(on Windows).
You can also use this code to print Armstrong number in given range.
#include<stdio.h>
int main()
{
int num,r,sum,temp;
int min,max;
printf("Enter the minimum range: ");
scanf("%d",&min);
printf("Enter the maximum range: ");
scanf("%d",&max);
printf("Armstrong numbers in given range are: ");
for(num=min;num<=max;num++)
{
temp=num;
sum = 0;
while(temp!=0)
{
r=temp%10;
temp=temp/10;
sum=sum+(r*r*r);
}
if(sum==num)
printf("%d ",num);
}
return 0;
}

Writing a program to find the largest in a series of numbers.

I am very new to C. I am using A modern Approach to C programming by King 2nd Edition.
I am stuck on chapter 6. Question 1: Write a program that finds the largest in a series of numbers entered by the user. The program must prompt the user to enter the numbers one by one. When the user enters 0 or a negative number, the program must display the largest non negative number entered.
So far I have:
#include <stdio.h>
int main(void)
{
float a, max, b;
for (a == max; a != 0; a++) {
printf("Enter number:");
scanf("%f", &a);
}
printf("Largest non negative number: %f", max);
return 0;
}
I do not understand the last part of the question, which is how to see which non-negative number is the greatest at the end of user input of the loop.
max = a > a ???
Thanks for your help!
So you want to update max if a is greater than it each iteration thru the loop, like so:
#include <stdio.h>
int main(void)
{
float max = 0, a;
do{
printf("Enter number:");
/* the space in front of the %f causes scanf to skip
* any whitespace. We check the return value to see
* whether something was *actually* read before we
* continue.
*/
if(scanf(" %f", &a) == 1) {
if(a > max){
max = a;
}
}
/* We could have combined the two if's above like this */
/* if((scanf(" %f", &a) == 1) && (a > max)) {
* max = a;
* }
*/
}
while(a > 0);
printf("Largest non negative number: %f", max);
return 0;
}
Then you simply print max at the end.
A do while loop is a better choice here because it needs to run at least once.
#include<stdio.h>
int main()
{
float enter_num,proc=0;
for(;;)
{
printf("Enter the number:");
scanf("%f",&enter_num);
if(enter_num == 0)
{
break;
}
if(enter_num < 0)
{
proc>enter_num;
proc=enter_num;
}
if(proc < enter_num)
{
proc = enter_num;
}
}
printf("Largest number from the above is:%.1f",proc);
return 0;
}

Resources