Computing the average of grades in C - c

I have write a program that allows me to firstly enter a character c followed by an integer n and n float values representing grades. Using array to store the grades I have entered and no more than 100 grades can be introduced. The program allowed me to calculate the sum of the elements in array when I enter 's', compute the production of the elements in array when i enter 'p' and compute the average of the element s when i enter other words. After i enter the grades and character. The program has no response when i hit return to continue. So where is the mistake in my code
#include<stdio.h>
#include<stdio.h>
int main()
{
char c;
int integer_grade [100];
float floting_grade [100];
printf("Enter a grade");
scanf("%i,%f",&integer_grade[100],&floting_grade[100]);
int *a;
a=&integer_grade[100];
int *b;
b=&floting_grade[100];
printf("Enter a character");
getchar();
scanf("%c",&c);
int n;
switch(c)
{
case 's':
for (n=0;n=100;n++)
*a+=*a;
*b+=*b;
printf("Sum is %d",*a+*b);
case 'p':
for (n=0;n=100;n++)
*a*=*a;
*b*=*b;
printf("Sum is %d",*a**b);
default:
for (n=0;n=100;n++)
*a+=*a;
*b+=*b;
printf("average is %d",(*a+*b)/100);
}
return 0;
}
The task is:
Write a program where you first enter a character c followed by an integer n and n float values representing grades. Use an array for storing the grades. You can assume that not more than 100 grades would be introduced. Yours program should compute and print the following: if c is 's' the sum of the grades, if c is 'p' the product of all grades and if another character was introduced then the arithmetic mean of all grades.
*use switch
*you can safely assume thee input will be valid.

Thoughts.
This is undefined behavior. You are assigning the read integer and float to offset 100 in those arrays, which doesn't exist.
int integer_grade[100];
float floting_grade[100];
scanf("%i,%f", &integer_grade[100], &floting_grade[100]);
These pointers point to memory that is outside the bounds of their respective arrays.
int *a = &integer_grade[100];
int *b = &floting_grade[100];
You ask for a character and then you ignore the value of that character:
getchar();
You then follow that up by getting the following character. Which is odd. But you do use the correct type and what not. So that's a win.
scanf("%c",&c);
Your indentation in these for loops implies that you think that both statements will be iterated on as part of the loop. That's incorrect. Use { ... } to accomplish that:
for (n=0;n=100;n++)
*a+=*a;
*b+=*b;
I have no idea what you think you're accomplishing by *a += *a. I do know that the value at *a is going to grow quite quickly (and will likely overflow).
Switch statements use fallthrough on the cases. That means that if your case is 's', it will run all of the code in the switch statement, including all three cases. If you don't want this behavior, you should place break statements at the end of each case.
Please go back to your book / faculty / internet resource and read how a for loop works. This doesn't do what you probably think it does. In fact, this is an infinite loop!
for (n=0; n=100; n++)

Whatever do you try to do here, it's not right at all.
First: You declare 2 arrays of 100 elements, THEN you assign values outside of that array bounds (100 element array start from 0, finishes at 99)
Second: You create 2 pointers that points to outside of those array bounds.
Third: Inside the switch , the for (n=0;n=100;n++) is wrong, it should be something like for(n = 0; n < 100; n++)
Fourth: This
for (n=0;n=100;n++)
*a+=*a;
*b+=*b;
it would increment (if that for would be correct) only the first statement.
Correct way would be
for (n = 0; n < 100; n++)
{
*a += *a;
*b += *b;
}
Proper code would be
#include <stdio.h>
int main()
{
char c;
int integer_grade[100];
float floting_grade[100];
int nr_of_grades;
int i = 0;
printf("Enter number of grades: ");
scanf("%d", &nr_of_grades);
for(i = 0; i < nr_of_grades; i++)
{
printf("Enter a int grade: ");
scanf("%d", &integer_grade[i]);
printf("Enter a float grade: ");
scanf("%f", &floting_grade[i]);
}
int operation_i = 0;
float operation_f = 0;
printf("Enter a character");
scanf(" %c", &c);
int n;
switch(c)
{
case 's':
for (n = 0; n < nr_of_grades; n++)
{
operation_i += integer_grade[n];
operation_f += floting_grade[n];
}
printf("Sums are Int: %d Float: %f", operation_i, operation_f);
case 'p':
operation_i = 1;
operation_f = 1;
for (n = 0; n < nr_of_grades; n++)
{
operation_i *= integer_grade[n];
operation_f *= floting_grade[n];
}
printf("Products are Int: %d Float: %f", operation_i, operation_f);
default:
for (n = 0; n < nr_of_grades; n++)
{
operation_i += integer_grade[n];
operation_f += floting_grade[n];
}
printf("Average is Int: %d Float: %f", operation_i / nr_of_grades, operation_f / nr_of_grades);
}
return 0;
}

Related

What's the problem with my code? In the third last line in score[i], the program said that i is undeclared

I just started learning C language. So, I am running into a lot of problems. I thought declaring i under for loop is enough, and I can use the value of i for outside too. But I think, that was not the case. Can someone explain the situation, please.
# include <stdio.h>
int main(void)
{
int x;
printf("Enter how many numbers in arrays you want to input : ");
scanf("%i", &x);
int score[x];
for(int i= 0; i <= x; i++)
{
printf("Enter the score : ");
scanf("%i", &score[i]);
}
// in the below line the output said "i" is undeclared.
float average = score[i] / x;
printf("The average score is : %f", average);
}
The answer is fairly simple
because of where you decalred i it is only visable to the for loop.
To make i visable to the whole function all you need to do is:
int i = 0;
for (; i <=x; i++){
printf("Enter the score : ");
scanf("%i", &score[i]);
}
this makes i avaliable throughout the function
i is declared in the initialization section of a for statement. That means the scope and lifetime of that variable is the expressions in the for statement itself as well as the block statement it contains. Once the loop is done, the variable no longer exists.
You need to declare i outside of the loop if you want to use it outside of the loop.
int i;
for(i= 0; i <= x; i++)
That being said, you don't actually need to use i outside of the loop.
There are security issues associated with using scanf so don't use it for anything serious. That said, I tried to re-write your program properly, and it still has pretty rubbish input validation.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define INPUTTEXTLEN 20
#define MAXINPUTINT 1000
int inputint() {
char inputtext[INPUTTEXTLEN + 1] = {0};
long inputval;
while (1) {
fgets(inputtext, INPUTTEXTLEN, stdin);
if (strlen(inputtext) > 0) {
inputval = atoi(inputtext);
if ((inputval < MAXINPUTINT) && (inputval >= 0)) break;
}
}
return (int)inputval;
}
int main(void)
{
int x = 0;
printf("Enter how many numbers in arrays you want to input : ");
//scanf("%i", &x);
while (x <= 0) {
x = inputint();
}
int score[x];
float average = 0;
for(int i= 0; i < x; i++)
{
printf("Enter the score : ");
//scanf("%i", &score[i]);
score[i] = inputint();
average += score[i];
}
average /= x;
printf("The average score is : %f\n", average);
}

How do I get the proper output for the color bands of a 3 band resistor?

I am taking a programming class as an elective. Our current lab is to create a program that accepts a number from the user that represents a resistor band. The max would be two digits followed by 9 zeros; 11 total digits. After accepting the number I have a few functions that find the first two digits, then the modulus for the second band and divide by 10 for the first. My issue lies in using a logarithm 10 function and even trying a loop with a counter to find the number of zeros. I have gotten it to be able to count 8 zeros, but once the ninth gets added it messes everything up including the first number. In my code I have some instruction or information and some functions stagnant as I hid them to try different options. I currently have just been trying to be able to enter 99000000000 and get "White" in return for all three numbers. Any ideas where I am going wrong?
#define _CRT_SECURE_NO_WARNINGS
#include "stdio.h"
#include "stdlib.h"
#include "math.h"
long int inputValue();
void outputColor(int);
int bandCalc(long int);
int loop(long int);
int divideResistor(int);
// function prototypes // '''
int main()
{
int resistor, x, y, z, a, b, c, f;
resistor = inputValue();
//printf("\n\tThe resistor value is %d", resistor);//
c = resistor;
b = divideResistor(resistor);
f = loop(b);
//printf("\t\nThe number is %d", b);//
if (f <= 10)
{
f = log10(c) - 1;
}
else
{
f = log10(c) - 2;
}
//Here we are finding out how many zeros there are in the number//
printf("\n\tThe character x equals %d", x);
y = bandCalc(b); //Here we are getting the first two digits of the resistor value//
printf("\n\tThe character y equals %d", y);
z = fmod(y, 10); //Here we are finding the second digit of the resistor//
printf("\n\tThe character z equals %d", z);
a = (y / 10); //Here we are finding the first digit of the resistor//
printf("\n\tThe character a equals %d", a);
x = bandCalc(resistor);
printf("\n\tThe returned number is %d", x);
printf("\n\n\tThe color of the resistor bands are: \n\n");
printf("\n\t");
outputColor(a);
printf("\t ");
outputColor(z);
printf("\t ");
outputColor(f);
system("pause>nul");
return 0;
}
int divideResistor(int s)
{
s = s / 10;
return (s);
}
int loop(long int j)
{
int k;
k = 0;
if (j >= 100)
}
}
j /= 10;
k++;
for (j > 100; j /= 10; k++)
k <= 9;
printf("%d ", k);
return (k);
}
long int inputValue()
{
long int band = 0;
printf("\nPlease enter the value of the resistor band: ");
scanf("%d", &band);
return (band);
}
int bandCalc(long int z)
{
long n = z;
long n1 = n, n2 = n;
while (n)
{
n2 = n1;
n1 = n;
n /= 10;
}
return (n2);
}
void outputColor(int i)
{
switch (i)
{
case 0:
printf(" Black");
break;
case 1:
printf(" Brown");
break;
case 2:
printf(" Red");
break;
case 3:
printf(" Orange");
break;
case 4:
printf(" Yellow");
break;
case 5:
printf(" Green");
break;
case 6:
printf(" Blue");
break;
case 7:
printf(" Violet");
break;
case 8:
printf(" Grey");
break;
case 9:
printf(" White");
break;
//return (band);//
}
}
Take a look at your inputValue function:
long int inputValue()
{
long int band = 0;
printf("\nPlease enter the value of the resistor band: ");
scanf("%d", &band); // format-specifier for a "long int" is "%ld"
return (band);
}
You are using a long to store the input, but you are telling scanf that band is only an int, so it will only be able to store values as high as INT_MAX (2147483647 for 32-bit two's complement ints). Assuming long is a 64-bit type on your system, it will be able to handle much larger values (9223372036854775807).
Try fixing your scanf call there to use the %ld format-specifier: scanf("%ld", &band);
Similarly, look at the type of resistor which takes the return of inputValue. It is of type int, so it won't be able to handle values that are outside of that INT_MAX range. That should also be type long. You'll also need to modify the input of functions such as divideResistor to take a long.
Beyond the issues of not using large enough integer types, you are also using floating-point operations on integer-type data. which can create rounding errors. log10, for example, is meant to handle double types. fmod is also intended for double types (the % operator is used do perform 'modulo' operations on integer types)
There may be further errors beyond these. If you find yourself having more trouble, please give this link a look-over and see if it helps you to help yourself, or at least help you construct a Minimal Complete Verifiable Example of specific issues rather than a scavenger hunt to find all the errors in your full program.

Fibonacci Sequence C program error

I am trying to write a program which takes the first 2 numbers of the Fibonacci sequence as input and also the value of n. Then the program gives the output of the nth digit of the Fibonacci sequence.
#include <stdio.h>
#include <stdlib.h>
int main () {
int n, i;
int s[n - 1];
int a, b;
printf("Enter two first two numbers:");
scanf("%d %d", &a, &b);
printf("Enter the value of n(3-100):");
scanf("%d", &n);
for (i = 2; i <= n - 1; i++) {
s[i] = s[i - 1] + s[i - 2];
}
printf("The nth digit is %d", s[n - 1]);
return(0);
}
I am getting the answer number which is followed by some additional arbitrary numbers
Actually to implement your code there is no need of an array s[] .
This can be simply implemented as :-
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n, i;
int a, b;
printf("Enter two first two numbers:");
scanf("%d%d", &a, &b); // not scanf("%d %d", &a, &b);
printf("Enter the value of n(3-100):");
scanf("%d", &n);
for (i = 1; i < n; i++)
{
b += a;
a = b - a;
}
printf("The nth digit is %d\n", a);
return (0);
}
Output:
Enter two first two numbers:0 1
Enter the value of n(3-100):5
The nth digit is 3 // 0 1 1 2 3
Here you define an array of unknown size, being lucky that n does not happen to be 0 or 1 or negative.
int s[n-1];
Here you ignore the return value of scanf, which you really should check to verify success of scanning.
scanf("%d %d",&a,&b);
scanf("%d",&n);
Even assuming a meaningfully defined array, you set a loop up to produce indexes beyond the array here:
for (i=2 ; i<=n-1 ; i++)
And then you write beyond the array (during the last iteration in the loop) here:
s[i]=
With this code all bets are off, you have guaranteed undefined behaviour and therefor any explanation of what exactly goes wrong is futile.
A few things. As mentioned, you are trying to use n before it has been given a value. Also, you should use malloc() when using a variable to determine the array size.
Next, if you are computing the nth sum, then you need the array to have n elements, not n-1
Third, you read in the two starting values, a and b, but you never use them to initialize the first two elements of your array.
And finally, you need to fix your loop indexing. (actually, your indexing is ok once you change the array to have n elements instead of n-1 elements, however, it is certainly preferred to use i < n rather than i <= n-1)
int main() {
int n, i;
int a, b;
printf("Enter two first two numbers:");
scanf("%d %d", &a, &b);
printf("Enter the value of n(3-100):");
scanf("%d", &n);
int *s = malloc(n * sizeof(*s));
s[0] = a;
s[1] = b;
for (i = 2; i < n; i++) {
s[i] = s[i - 1] + s[i - 2];
}
printf("The nth digit is %d", s[n - 1]);
return(0);
}

Retaining input values in C?

I have asked for the user to enter in several values to calculate an average, however I'd like to also calculate a gradient which uses the inputted values. How do I name these values so I can use them again? Thank you.
Here is what I have thus far:
#include <stdio.h>
int main () {
int n, i;
float num[1000], total=0, mean;
printf("Enter the amount of x-values:");
scanf("%d", &n);
while (n <= 0 || n > 1000) {
printf("Print error. The number should in range of 0 to 1000.\n");
printf("Please try to enter the amount again: ");
scanf("%d", &n);
}
for (i = 0; i < n; ++i) {
printf("%d. Input x-value:", i+1);
scanf("%f", &num[i]);
total += num[i];
}
mean=total/n;
printf("The mean of all the x-values entered is %.2f to 2 decimal places", mean);
{
float num[1000], total=0, mean;
printf("Enter the amount of y-values:");
scanf("%d", &n);
while (n <= 0 || n > 1000) {
printf("Print error. The number should in range of 0 to 1000.\n");
printf("Please try to enter the amount again: ");
scanf("%d",&n);
}
for (i = 0; i < n; ++i) {
printf("%d. Input y-value:", i+1);
scanf("%f", &num[i]);
total += num[i];
}
mean = total / n;
printf("The mean of all the y-values entered is %.2f to 2 decimal places", mean);
return 0;
}
}
Naming the variable is really up to you, but `int gradient[NUM_ELEMENTS]; seems appropriate. It is an array, which also seems appropriate if it's purpose is to assist in finding the gradient from a series of numbers.
Steps could be:
1) use printf to ask user for values, specify spaces or commas between values. You can also specify a limit of values. Example printf("enter 5 numbers separated by commas\n:");
2) use scanf or similar to read values from standard input (the terminal) into the array: scanf("%d,%d,%d,%d,%d", &gradient[0], &gradient[1], &gradient[2], &gradient[3], &gradient[4]);
3) use the array an a function that will compute the gradient.
Simple example:
(where gradient computation, error checking, bounds checking etc. is all left to you)
int get_gradient(int a[5]);
int main(void) {
int gradient[5];
int iGradient=0;
printf("enter 5 numbers separated by commas");
scanf("%d,%d,%d,%d,%d", &gradient[0], &gradient[1], &gradient[2], &gradient[3], &gradient[4]);
iGradient = get_gradient(gradient);
return 0;
}
int get_gradient(int a[5])
{
return [do computation here using array a];
}
Edit:
The above example works only if you know the number of elements at compile time. It uses an int array that has been created on the stack. If you do not know how big of an array you will need until run-time, for example if user input determines the size, then the array size needs to be determined at run-time. One options is to create the variable needed on the heap. (read about stack and heap here) The following uses some techniques different from the simpler version above to get user input, including a function I called get_int(), which uses scanf() in conjunction with strtol(). Here's the example:
int main(void) {
char input[80]={0};
char **dummy={0};
long *gradient = {0};
int iGradient=0;
int arraysize;
int i;
char* fmt = "%[^\n]%*c";
printf("how many numbers will be entered?");
scanf(fmt, input);
arraysize = strtol(input, dummy, 10);
gradient = calloc(arraysize, sizeof(long));
if(gradient)
{
for(i=0;i<arraysize;i++)
{
gradient[i] = get_int();
}
iGradient = get_gradient(gradient, arraysize);
//free gradient when done getting result
free(gradient);
}
return 0;
}
int get_gradient(int *a, int num)
{
int grad = 0, i;
//do something here to compute gradient
return grad;
}
long get_int(void)
{
char input[80]={0};
char **dummy={0};
char* fmt = "%[^\n]%*c";
printf("Enter integer number and hit return:\n");
scanf(fmt, input);
return strtol(input, dummy, 10);
}

C skip a "while" loop?

I have a problem, I tried to write a program to show the whole sum from 1 to 22 and after that, to do 2 while loops. The first one is supposed to perform the sum of some numbers given by the user, as an example: you type 10, 30 and 40 then as you enter a 0 the program sums the first three numbers. Unfortunetly the first while loop is not working. It goes directly to the last while loop where it is supposed to type a decimal numbers like (10.20 30.50 40.55) and after you type 0 again it sum those numbers and add and multipli every entry with 1.19. So far the last loop is working properly, unfortunately the second loop does not, if I move printf and scanf over the while it let me write but just start writing w/o stopping the number I wrote . Thank You in advance!
Here is the code :
#include <stdio.h>
int main()
{
int sum = 0;
int a;
int b;
double i;
double sum1 = 0;
for (a= 0; a <= 22; a++) {
sum = sum + a;
printf("the sum from 1 till 22 : %i\n ", sum);
}
while (b != 0) {
printf("type a number:");
scanf("%i", &b);
sum += b;
printf("%i\n", b);
}
printf("the sum is : %i\n", sum);
while(i !=0) {
printf ("Type a decimal number:");
scanf ("%lf",&i);
sum1 += i*1.19;
printf("%lf\n", i);
}
printf("The decimal summ is: %lf\n",sum1);
return 0;
}
You don't initialise i to any value before entering the loop with
while(i != 0)
i might very well be zero at this point, so your loop won't be entered even once. Initialising i to a non-zero value should fix this particular problem. The same holds for the variable b.
You should turn on warnings in your compiler, so it can show you problems like this one.
The first time the condition of the second while is evaluated, b has undefined value, since it wasn't initialized. The same applies to the third while.
Whether or not both loops are executed is only a question of chance.
Initialize both variables with non-zero values to ensure both whiles are entering. Or use a do-while:
do {
printf("type a number:");
scanf("%i", &b);
sum += b;
printf("%i\n", b);
} while (b != 0);
Don't test b with while, test it after the user enters the number. Then you can use break to exit the loop.
while (1) {
printf("type a number:");
scanf("%i", &b);
if (b == 0) {
break;
}
sum += b;
printf("%i\n", b);
}
while(1) {
printf ("Type a decimal number:");
scanf ("%lf",&i);
if (i == 0.0) {
break;
}
sum1 += i*1.19;
printf("%lf\n", i);
}
Your only issues are initialization: see edits in the code below. (it compiles and runs)
Did you get any compiler warnings for these? If not, you should change your settings so you do.
#include <stdio.h>
int main()
{
int sum = 0;
int a;
int b=-1; //initialize (any non-zero value will work)
double i;
double sum1 = 0;
for (a= 0; a <= 22; a++) {//a initialized in for(...) statement, (this is good)
sum = sum + a;
printf("the sum from 1 till 22 : %i\n ", sum);
}
while (b != 0) { //b Needs to be initialized before using (done above)
printf("type a number:");
scanf("%i", &b);
sum += b;
printf("%i\n", b);
}
printf("the sum is : %i\n", sum);
i=-1; //initialize i to any non-zero value
while(i !=0) {
printf ("Type a decimal number:");
scanf ("%lf",&i);
sum1 += i*1.19;
printf("%lf\n", i);
}
printf("The decimal summ is: %lf\n",sum1);
getchar();
return 0;
}

Resources