I have the main code I want to use written out. All I need to do is get the user to input five numbers. Then once they insert the numbers I need them to be inputted into the array so that they can be calculated. I have tried to understand how to successfully get user input and use it, but have been unable to figure it out.
int
main (int argc, char **argv)
{
int number1;
int number2;
int number3;
int number4;
int number5;
int a[5];
printf("Enter a number\n");
scanf ("%d, number1");
printf("Enter a number\n");
scanf ("%d, number2");
printf("Enter a number\n");
scanf ("%d, number3");
printf("Enter a number\n");
scanf ("%d, number4");
printf("Enter a number\n");
scanf ("%d, number5");
a[0] = number1;
a[1] = number2;
a[2] = number3;
a[3] = number4;
a[4] = number5;
int mean = (a[0] + a[1] + a[2] + a[3] + a[4]) / 5;
int difference0 = a[0] - mean;
int difference1 = a[1] - mean;
int difference2 = a[2] - mean;
int difference3 = a[3] - mean;
int difference4 = a[4] - mean;
int variance = ((difference0 * difference0) + (difference1 * difference1) + (difference2 * difference2) + (difference3 * difference3) + (difference4 * difference4)) / 5;
double sdeviation = sqrt(variance);
printf("the mean of the array is %d\n",mean);
printf("the variance of the array is %d\n",variance);
printf("the standard deviation of the array is %f\n",sdeviation);
return 0;
}
First of all, you don't need the numberN local variables. You can define the array and read the numbers into it directly.
That said, do not repeat the same code over and over again.
Change the code like
#define ARRSIZE 5
int a[ARRSIZE] = {0};
for (int i = 0; i < ARRSIZE ; i++) {
printf("Enter a number\n");
scanf ("%d", &a[i]);
}
Also, it's always a good practice to check the return value of scanf() function to ensure that the scanning was successful.
Suggestion: Always enable compiler warnings and try to resolve the warnings.
Just to add to the other answer by #Sourav, there are principles you have to learn as a programmer. One of which is, if you have to repeat any task with minor variations, you're most likely going to use a loop. Also, to quote Sinan Ünür
When you find yourself adding an integer suffix to variable names, think I should have used an array.
If you wish to create 5 int variables and you're just naming each one: number1 ... number 5, then you should just create an array to hold them all. It is a lot easier and enables you to refer to each one dynamically because of how arrays work.
int numbers[5]; //Now you can refer to each one by numbers[X]
...
for (int i = 0; i < 5; ++i) {
numbers[i] = a[i] - mean;
}
Those are just two very small modifications I would have added to your code so that it is a lot smaller and easier on the eyes. You'll learn this a lot better as you go along.
You need & operator before the variable you want to assign the upcoming value. On that way, you are saying that num1 = 4, where for is the user's value.
When you declare same type variables, just put then in row separated by comma. You don't need a new line for each one.It makes your code more legible
int argc and char **argv params, are not being used in this function and instead are consuming unnecessary ram memory
Try this:
#include <stdio.h>
#include <math.h>
int main()
{
int num1,num2, num3, num4, num5;
printf("Enter #1:\n");
scanf ("%d", &num1);
printf("Enter #2:\n");
scanf ("%d", &num2);
printf("Enter #3:\n");
scanf ("%d", &num3);
printf("Enter #4:\n");
scanf ("%d", &num4);
printf("Enter #5:\n");
scanf ("%d", &num5);
int mean = (num1 + num2 + num3 + num4 + num5) / 5;
int difference0 = num1 - mean;
int difference1 = num2 - mean;
int difference2 = num3 - mean;
int difference3 = num4 - mean;
int difference4 = num5 - mean;
int variance = ((difference0 * difference0) + (difference1 * difference1) + (difference2 * difference2) + (difference3 * difference3) + (difference4 * difference4)) / 5;
double sdeviation = sqrt(variance);
printf("the mean of the array is %d\n",mean);
printf("the variance of the array is %d\n",variance);
printf("the standard deviation of the array is %f\n",sdeviation);
return(0);
}
Related
I wanted to fix my code to create random operation here, what should I fix here?
#include <stdio.h>
int main()
{
int x,y,z,a;
char o;
while(1)
{
printf("give your three numbers: ");
scanf("%d %d %d",&x,&y,&z);
printf("(%d*%d-%d) what is the correct among following answers? \n 1. %d\n 2. %d\n 3. %d\n ",
x,y,z,x*y-z,x*y*z,x-y*z);
printf("what is answer? \n: ");
scanf("%d",&a);
if(a == 1)
{
printf("you are right!\n");
}
else
{
printf("you are false!\n\n");
}
getchar();
printf("Would you like to exit programm? (y/n) : ");
scanf("%c",&o);
if (o=='Y' || o=='y')
{
break;
}
else if(o=='N' || o=='n')
{
continue;
}
else
{
printf("Wrong input!!!!");
}
return 0;
}
}
What I mean is I want to try change operation such as * + - randomly when I run code, and also along with this question, the answer should be changed...
thank you!
Your question is mainly focused on shuffling the answers. By studying from couple of sites I have found an solution for this. This is little bit difficult but studying the code few times you can get it
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
void randomize(int arr[], int n) {
srand(time(NULL));
int i;
for(i = n-1; i > 0; i--) {
int j = rand() % (i+1);
swap(&arr[i], &arr[j]);
}
}
int main() {
int x,y,z,a;
int i;
int a1, a2, a3;
int arr[] = {1, 2, 3};
int n = sizeof(arr)/ sizeof(arr[0]);
printf("give your three numbers: ");
scanf("%d %d %d",&x,&y,&z);
a1 = x*y-z;
a2 = x*y*z;
a3 = x-y*z;
printf("Before shuffle = %d %d %d\n\n", a1, a2, a3);
char answers[] = {a1, a2, a3};
printf("(%d*%d-%d)what is the correct among following answers?\n", x, y, z);
randomize (arr, n);
for(i=0; i<n; i++) {
int index = arr[i];
printf("%2d - %d\n", i+1, answers[index]);
}
return 0;
}
This is the outputs
First time run
give your three numbers: 2
2
2
Before shuffle = 2 8 -2
(2*2-2)what is the correct among following answers?
1 - 8
2 - 2
3 - -2
Second time run
give your three numbers: 2
2
2
Before shuffle = 2 8 -2
(2*2-2)what is the correct among following answers?
1 - -2
2 - 8
3 - 2
You can try this multiple times. Every time answers will be shuffle. This is the Source I have referred.
Just provide one of examples here. There are many kinds way to implement. In the random operation generation part. I would like to write a random number generator function, which purpose is to generate the given range of random number.
int gen_random(int min, int max)
{
srand( time(NULL) );
return rand() % (max - min + 1) + min;
}
In order to represent four operator (+, -, *, /), The number (let's call the operation number) 1 to 4 is used for represent four operator respectively. The calculation function map the operation number to operation and get the result.
int calculation(int number1, int number2, int op)
{
switch(op)
{
case 1:
return number1 + number2;
case 2:
return number1 - number2;
case 3:
return number1 * number2;
case 4:
return number1 / number2;
}
}
You can use the gen_random and the calculation function above to change operation randomly. The usage of the gen_random and the calculation function is something like:
int op = gen_random(1, 4); // Generate operation randomly
printf("%d\n", op);
printf("%d\n", calculation(x, y, op)); // Pass x, y, and operation number into calculation function to get answer
I am currently doing a project from my university and I came up with logic, that if possible, can help me make my project much faster.
Here is what I want to do,
Suppose
int a=2302; //user input(Now is there any way to do the following?)
int b=23 //First two-digit of a
int c=02; //Last two-digit of a
int b = a / 100;
int c = a - b * 100;
Assuming that value is an int of at least 10, then:
char fdigs[3], ldigs[3];
int first2 = value / (int)(pow(10.0, (int)(log10(value) + 1.0e-9 - 1.0)) + 0.5);
int last2 = value % 100;
sprintf(fdigs, "%02d", first2);
sprintf(ldigs, "%02d", last2);
Will give the digits in the two wee strings (including leading zeros, if required)!
Test code:
#include <stdio.h>
#include <math.h>
int main()
{
int value;
int first2, last2;
char fdigs[3], ldigs[3];
printf("\nEnter number: ");
scanf("%d", &value);
while (value >= 10) {
first2 = value / (int)(pow(10.0, (int)(log10(value) + 1.0e-9 - 1.0)) + 0.5);
last2 = value % 100;
sprintf(fdigs, "%02d", first2);
sprintf(ldigs, "%02d", last2);
printf("First Two: %s; Last Two: %s", fdigs, ldigs);
printf("\n\nEnter another number: ");
scanf("%d", &value);
}
printf("\n");
return 0;
}
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);
}
When the first number is 1 and second number is 2, and the length is 5, it should be 1 2 3 5 8. But then my output is always 1 2 1 3 4. I can't seem to find the problem.
Another input is 2 and 5. Output is 2 5 1 6 7. The 3rd number which is 1 shouldn't be there. What should I change or add?
*This is already a submitted HW and yes its wrong I got the deductions already. Now I just want to fix this so I can study this.
int main()
{
int i, lenght = 0, fib, sum, sum1, sum2, a, b, c;
printf("\nFirst number: ");
scanf("%d", &a);
printf("\nSecond number: ");
scanf("%d", &b);
printf("\nHow long?: ");
scanf("%d", &lenght);
{
while ((a > b) || ((lenght < 2) || (lenght > 100)))
{
printf("\nFirst number: ");
scanf("%d", &a);
printf("\nSecond number: ");
scanf("%d", &b);
printf("\nHow long?: ");
scanf("%d", &lenght);
}
}
printf("%d\t%d\t", a, b);
printf("%d\t", fib);
for (i = 3; i < lenght; i++) {
if (i <= 1) fib = i;
else {
a = b;
b = fib;
fib = a + b;
}
printf("%d\t", fib);
}
}
The first time you print fib (before the for loop), you haven't assigned it anything yet.
Since this is for study, issues with your code: you don't need to duplicate the calls to scanf(), simply initialize one of the variables to fail (which you did: lenght = 0) and let the loop do its thing; pick one indentation style and stick with it; if you're new to C, always include the curly braces, even when the language says they're optional; you (correctly) allow for a length of 2, but then print three numbers; your if (i <= 1) clause is a no-op as the loop starts with for (i = 3; so i is never less than 3.
Putting it all together, we get something like:
#include <stdio.h>
int main() {
int length = 0, a, b;
while (length < 2 || length > 100 || a > b ) {
printf("\nFirst number: ");
(void) scanf("%d", &a);
printf("\nSecond number: ");
(void) scanf("%d", &b);
printf("\nHow long?: ");
(void) scanf("%d", &length);
}
printf("%d\t%d\t", a, b);
for (int i = 2; i < length; i++) {
int fib = a + b;
printf("%d\t", fib);
a = b;
b = fib;
}
printf("\n");
return 0;
}
Note that the input error checking isn't sufficient to prevent problems. E.g. b can be greater than a, but still mess up the sequence if you input random numbers. You're assuming the user knows to put in two adjacent items from fibonacci sequence which is tricky to test.
just add fib=a+b; before printing fib value.
Its a good coding habit to initialize all variable before using it(especially in C).
Your code seems strange to me. I tried to simplify your code a bit. See this once:
int main()
{
int a,b,next,last,i;
printf("Enter the first Value:");
scanf("%d",&a);
printf("Enter the second Value:");
scanf("%d",&b);
printf("Enter the length of Fab. series:");
scanf("%d",&last);
printf("%d,%d,",a,b);
for (i=3; i<= last; i++)
{
next = a + b;
if(i<last)
printf("%d,",next);
else
printf("%d",next);
a = b;
b = next;
}
return 0;
}
Hope it's Helpful!!
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;
}