Manipulating random number arrays - c

The question: Given integer values of x and y generate 20 random values within [x, y] interval and put them in an array. Print the array. Determine the index of the largest even negative number in it (ranging from 0 to 19). Account for the possibility that there might be no such number in the array. Calculate the sum of all positive odd numbers. You are only allowed to go through the
array values once. You should define separate functions for generating random numbers and checking even and odd numbers.
What I have written:
#include <stdio.h>
int random(int min, int max, int arr[]){
int i, j = 1;
for(i = 0; i<20; i++){
arr[i] = min + rand() % (max+1 - min);}
for(i = 0; i<20; i++){
printf("%d. %d\n", j, arr[i]);
j++;}
return arr[20];}
int evenodd(int arr[], int size){
int i, holder, sum, index = 1;
holder = arr[i];
for(i = 0; i<20; i++){
if (holder>0){
if (holder%2 == 0){
sum = sum;}
else{
sum += i;}}
else{
sum = sum;}}
printf("\nThe sum of all odd positive numbers is %d.", sum);
for(i = 1; i<20; i++){
int top = arr[0];
if (arr[i]<0){
if(arr[i]<top){
top = arr[i];
index = i;}
else{
top = top;}}
else{
top = top;}}
printf("\nThe index of the largest negative number is %d", index);}
int main()
{
int min, max;
printf("Please input the minimum desired random number: ");
scanf("%d", &min);
printf("\nPlease input the maximum desired random number: ");
scanf("%d", &max);
int a[20];
random(min, max, a);
evenodd(a, 20);
}
It prints out fine, but the sum of positive odd number is wrong, as well as the index of the largest negative number.

In your loop for(i = 1; i<20; i++) when finding negative numbers, you begin the loop by resetting the value of top to be arr[0], and thus you will always be doing your comparisons against the first value of the array. Perhaps you want to move that initialization out of the loop.

I see several issues with your code (especially with respect to your problem statement), but the summation procedure is not working because you are initializing variable "holder" only once, that too, before the for loop. Also, you are using an uninitialized varaible "i" as an index for the array arr. A lot can go wrong here!
By the way, Please use proper indentation to make your code more readable.

Four things
1) You did not initialize your sum to zero for odd positive numbers. So you should do that.
2) In calculating the sum you should do sum+=sum[i] and not sum+=i;
3) You initialized your index to 1 and not 0 for index of the largest negative number. If the first element is your smallest negative your answer should be zero. Right now for both first and second element you will give answer as 1. If you want a range from 1 to 20 you can output i+1 in the prints. I think you also have to do if(arr[i]>top) to find the largest negative integer assuming -10 is larger than -20 which is usually the case
4) Your implementation in three still wont account for the fact that no such number exists. What I recommend doing is initialize your top to largest negative integer. Range of values in C Int and Long 32 - 64 bits . And you can set your index to -1. Compare this to the entire array and if your index is -1 in the end. Then you print that no such element exists. You also have to check if the integer you are comparing is even. You can do the summing and the even negative integer in one loop as the two things are independent of each other

Related

This code is running properly when I use 1 digit numbers. But It's keep lagging on more digit numbers

Something is wrong. I'm trying to make a cade which can count number count of any natural number. Like number count of 2 is 1, 30 is 2, 456 is 3. My code is running for 1 digit numbers but not for two digit numbers.
#include<stdio.h>
void main(void)
{
int num,count,check;
float div;
printf("Enter a natural number\n");
scanf("%d", &num);
while (num<=0)
{
printf("Error\n");
printf("Enter a number\n");
scanf("%d", &num);
}
while(num>1)
{
count=1;
check=10;
div=num/check;
if(div<=1)
{
printf("Number count is\n%d", count);
break;
}
check = check*10;
count = count+1;
}
}
The problem with your solution is that after check and count are modified at the end of the loop, they are re-declared to 1 and 10 respectively at the beginning of the loop at every passage.
You need to move the declaration just before the while loop.
Also div doesn't need to be a float given that the decimal part of this number is irrelevant.
You could also use less variables by replacing check by 10 and
using num directly instead of temporarily storing results in div.
I think this might be a simpler solution
#include <stdio.h>
int main(){
int num = 0, digits = 0;
while (num <= 0)
{
printf("Enter a natural number\n");
scanf("%d", &num);
num == 0 ? printf("Error\n") : 0;
}
for( ; num > 0; digits++)
num /= 10;
printf("number of digits: %d\n", digits);
}
As num is continuously divided by 10, the decimal of the result gets truncated since num is an int while digits steadily increases.
It is time to learn to use a debugger. Using it would have immediately shown the major problem in your code: you reset the value of count and check inside the loop. So if you enter a number greater or equal to 10, you enter an infinite loop because you will consistently divide that number by 10 and find that the result is >= 1!
There is another less important problem: you use if(div<=1) when it should be if(div<1). Because 10/10 is 1 and has 2 digits...
After those fixes you should have:
...
check = 10;
count = 1;
while (num > 1)
{
div = num / check;
if (div < 1)
{
printf("Number count is\n%d", count);
break;
}
check = check * 10;
count = count + 1;
}
return 0; // main shall return an int value to its environment...
}
Which correctly gives the number of decimal digit on positive integers. But as you were said in comments, you should always test the return value of scanf (what is the user inadvertently types a t instead of 5 for example?).
That being said, this answer intends to show you what the problems were, but Keyne's solution is better...

C program to read 'n' numbers and find out the sum of odd valued digits of each number and print them

i am new to programing, i want to know that how we can find the odd digits in a number.
the condition in this program is we should only use concept of arrays.I tried a code for this as follows:
#include <stdio.h>
int main()
{
int A[50],i,x,y,n,sum=0;
scanf("%d",&n);
printf("the value is %d\n",n);
for(i=0;i<n;i++)
scanf("%d",&A[i]);
for(i=0;i<n;i++){
x=A[i]%10;
if(x%2!=0)
sum=sum+x;
A[i]=A[i]/10;
printf("the sum of odd numbers is %d\n",sum);
}
return 0;
}
but in this the code is checking for only one digit of the first number in the loop and then next time it is going to check the digit of second number.
so, i need to write a code to check all digits in the number and then it goes to next number and check all digits and should continue the same process in the loop.So, for this how should i modify my code?
You were missing a loop that would iterate through every digit of A[i] - the inner while loop below,
#include <stdio.h>
int main()
{
int A[50], i, x, y, n, sum=0;
printf("How many numbers will you input?\n");
scanf("%d",&n);
printf("the value is %d\n",n);
for(i=0; i<n; i++) {
scanf("%d",&A[i]);
}
for(i=0; i<n; i++) {
sum = 0;
while (A[i] > 0) {
x = A[i]%10;
if(x%2 != 0) {
sum = sum + x;
}
A[i] = A[i]/10;
}
printf("the sum of odd numbers is %d\n",sum);
}
return 0;
}
The exact algorithm for iterating through each digit in a nice form can be found in this post - although for a different language. Here, apart from the while loop, you also need to reset the sum each time unless you want a cumulative sum over all provided numbers.
Note that I changed the formatting a bit - more space, extra braces, and a message about what you're prompting the user to input.
int temp;
int sum = 0;
temp = number;
do {
lastDigit = temp % 10;
temp = temp / 10;
sum += (lastDigit %2 != 0) ? lastDigit : 0;
} while(temp > 0);

Adding 3 basic features to my existing code [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I have a gradebook program that I've been building, which works fine, but now I want to slot 3 new functions into the existing code. I can't wrap my brain around the logical path I need to take to make it work. I need a SIMPLE way to also get the highest, lowest, and average grades printed at the end. Here's my program...
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define MAX_GRADE_COUNT 200
int main() {
int grade[MAX_GRADE_COUNT];
int i;
int count = 0;
char continueResponse;
printf("Welcome to Gradebooker!\n\n");
for(i = 0; i < MAX_GRADE_COUNT; i++) {
printf("Please enter grade (0-100): ");
scanf(" %d", &grade[i]);
count++;
printf("Do you have more grades to enter?(Y/N): ");
scanf(" %c", &continueResponse);
if(toupper(continueResponse) != 'Y') {
printf("\n >> Thank you for using Gradebooker! <<\n");
break;
}
}
printf("\n\nCurrent Gradebooker listings: \n\n");
for(i = 0; i < count; i++) {
printf("\t%5d\n", grade[i]);
}
return 0;
}
The program would need to calculate the max, min and average in the second loop, like this:
int sum = 0;
int minimum = INT_MAX;
int maximum = 0;
for(i = 0; i < count; i++) {
printf("\t%5d\n", grade[i]);
sum += grade[i];
if(grade[i] < minimum) minimum = grade[i];
if(grade[i] > maximum) maximum = grade[i];
}
float average = (float)sum / count;
printf("min grade: %d\n", minimum);
printf("max grade: %d\n", maximum);
printf("average: %f\n", average);
The minimum starts with a value that is larger than all values in the list (INT_MAX for example is the largest possible value an int can take). Then, for each grade in the array, it replaces it with that grade, if it is smaller than the one currently in the minimum variable. That way minimum will in the end contain the smallest grade.
Same for maximum, but reversed.
For the average, it accumulates the sum of all grades (sum needs to be initialized to 0 at the beginning), and the divides it by the number of grades in the end. This gives an arithmetic mean in average.
Using float, it calculates the average as a floating point number (so the average can be non-integer). The (float)sum / count is needed so that it will first cast (convert) sum to a float, and so a floating point division on it. Otherwise, with sum / count is would do an integer division (which returns a rounded down integer), and store that as float in the average variable afterwards.
The idea for finding maximum value is: first declare a variable (lets say, MAXX) to store maximum value and initial it with as minimum value as possible and then iterate through the array and if any value in the array found greater then the current value of MAXX variable than update the value of MAXX with the value.
The idea for finding minimum value is: first declare a variable (lets say, MINN) to store minimum value and initial it with as maximum value as possible and then iterate through the array and if any value in the array found greater then the current value of MINN variable than update the value of MINN with the value.
Idea for finding avarage: Sum all the grade and then divide the sum with the number of grade.
See the implementation below for better understanding:
int max_grade = 0;//for storing maximum grade
/*
Minimum possible value should be initialize here.
Best option to write here is:
int max_grade = INT_MIN;
But to use INT_MIN <limits.h> file must be included.
*/
int min_grade = 10000000;//for storing maximum grade
/*
Maximum possible value should be initialize here.
Best option to write here is:
int min_grade = INT_MAX;
But to use INT_MAX <limits.h> file must be included.
*/
int total_grade = 0;//for counting all the grade
for(i = 0; i < count; i++) {
if(grade[i] > max_grade){
max_grade = grade[i];
}
if(grade[i] < min_grade){
min_grade = grade[i];
}
total_grade += grade[i];
}
printf("Max grade = %d\n" max_grade);
printf("Min grade = %d\n" min_grade);
printf("Avg grade = %d\n" total_grade/count);
I could not see all your code (it seemed to be cut off at the bottom), however the basically procedure to get an average, max and min in C is as follows:
int running_total = 0;
int count_grades = 0;
int max_so_far = 0;
int min_so_far = 999;
while( -1 ){ // infinite loop
// get input (a grade)
// if input is done, break
count_grades++;
running_total += iCurrentGrade; // (iCurrentGrade should be defined during input phase)
if( iCurrentGrade > max_so_far ) max_so_far = iCurrentGrade;
if( iCurrentGrade < min_so_far ) min_so_far = iCurrentGrade;
}
printf( "avg: %d min: %d max: %d\n", (int)(running_total / count_grades), min_so_far, max_so_far );

Finding the average of 5 numbers and N numbers using only While and do while loop in C

i am really stuck with this been trying to solve it for quite a time now.
i have to write a program where i should input 5 numbers between 1 to 10 and then calculate the average, USING ONLY WHILE LOOP, but it does not have to exit when the number does not meet the requirement. then, i have to write a variation of the same code but this time you can enter all the numbers you want, and when 0 is entered it has to calculate the average and exit
this is where i have gotten so far
#include <stdio.h>
int main(void)
{
int n, i = 1;
float add;
float avg;
do
{
printf("enter the number %d:\n", i++);
scanf("%d", &n);
add = add + n;
} while(n > 0 && n < 11);
avg= (add / 5);
printf("%.1f", avg);
return 0;
}
it will keep asking for numbers after 5 have been entered. and the average is not right anyways
First, you're using nas your while condition variable, but also as the variable to scan the input. If I start your program by scanning 20, for example, your while loop will exit on the first interaction. Use your i variable instead and also increment it every time your loop executes.
do{
...
}while(i <= 5);
Second, if you want only numbers between 1 and 10, then you should write a condition for it. For example:
printf("enter the number %d:\n", i); //do not increment it here!
scanf("%d",&n); //assuming "n" as your variable to scan
if(n > 0 && n < 11){
add += n;
i++; //increment it here instead!
}
Third, initialize your variables in order to not get thrash values
float add = 0;
float avg = 0;
int i = 1;
Finally, assign your result (not mandatory, but since you're using it I'll keep it):
avg = add/5.0f
and display:
printf("%.1f", avg);

find the smallest number of n integers

C Programming Beginner.
I don't understand why this code doesn't work. The numbers I get as answers for min and max are 2686672 and 4525824. Can anyone explain please? Thank you.
#include <stdio.h>
int main(void) {
int array[20], i, x, y;
int max, min;
printf("Please enter number of integers to be checked\n");
scanf("%d", &x);
for (y = 0; y <= x; y++) {
printf("Please enter your numbers\n");
scanf("%d", &i);
}
min = array[0];
max = array[0];
for (y = 0; y <= x; y++) {
if (array[i] < min) {
min = array[i];
} else if (array[i] > max) {
max = array[i];
}
}
printf("%d is the min and %d is the max", min, max);
}
Your section at
for (y=0;y<=x;y++){
printf ("Please enter your numbers\n");
scanf ("%d",&i);
}
Has several issues. First, you're storing the value in i each time; that will get overwritten the next time through the loop. Second, you want < instead of <= as you will otherwise ask for too many numbers. (You should also check that the user asked for <= 20 numbers).
I think you want:
for (y=0;y< x;y++){
printf ("Please enter your numbers\n");
scanf ("%d",&array[y]);
}
You aren't storing the values that you read into i in your array when you have the loop asking for the numbers to be entered.
Later, your are indexing array with i, but the loop counter is y - so i is never changing (nor is it necessarily a valid index, since it holds the last value that was read via scanf).
Check your code again to make sure you actually store the values you read into an array, and then check what you are using for array indices when computing the max and min.
you are never storing the numbers into the array. You overwrite the number the user enters on each pass. You therefore end up with garbage data at the end, whatever happened to be initialized into max and min.
for (y=0;y<=x;y++){
printf ("Please enter your numbers\n");
scanf ("%d",&i);
array[y] = i;
}
at least this way there will be something in the array locations to compare with in your Max/Min Logic later on.
cheers.
write a loop to dump out the array after its entered - just so you can be sure you get the right stuff
for(i = 0 ; i < x; i++)
{
printf("%d\n", array[i];
}
Also (as others have said) your loop boundaries need to be < not <=. A 10 element array has elements numbered 0 - 9

Resources