10 element array - c

My teacher gave an assignment to me. The question is below:=
Write a program that prompts the user to enter 10 double numbers. The program should accomplish the follwing:
a. Store the information in a 10-element array.
b. Display the 10 numbers back to the user.
I could do all of the above in main().
Hint: You should use loops, not hardcode the values 0 through 9. It should be easy to convert your program to accept 1000 numbers instead of 10.
For a bonus mark, do at least one of the tasks (a or b) in a separate function. Pass the array to the function; do NOT use global (extern) variables.
I confused above. I wrote a program in the source code. Am I doing wrong? It is below:=
#include<stdio.h>
int main(void)
{
int number[10];
int i;
for (i = 0; i <10; i++)
printf("%d.\n", i, number[i]);
printf("\n\nPress [Enter] to exit program.\n");
fflush(stdin);
getchar();
return 0;
}
Thanks.

Not too bad so far, I'd like to make the following comments:
if you need to input double numbers, you should probably use double rather than int.
you need a statement (maybe in your current loop but possibly in another loop preceding the current one) which inputs the numbers. Look into scanf for this.
Using %d with printf is for integers, not doubles. You will have hopefully already figured out the format string to used when you looked into scanf above.
Bravo for using the correct int main(void) form and for not including conio.h :-)
Once you've figured those bits out, then you can worry about doing it in a separate function.

Based on the code you have given above, I would suggest reading up on the following:
scanf
functions in C, particularly passing arrays to functions: this link should be good.
Note to OP: If you were able to do (a) and (b) in main(), the code above is not complete. It would be nice the functions you created for getting (a) and (b) above done for getting to the root of your "confusion".
Let me know in case you need more help.
HTH,
Sriram

Try this it may sloves your problem.
#include<stdio.h>
int main(void)
{
double number[10];
int i;
printf("Enter double numbers:");
for (i = 0; i <10; i++)
scanf("%lf",&number[i] );
printf("The numbers you entered are:");
for (i = 0; i <10; i++)
printf("%lf\n",number[i] );
return 0;
}

Related

Infinite array index without any pointer in C

I want to get a variable from user and set it for my array size. But in C I cannot use variable for array size. Also I cannot use pointers and * signs for my project because i'm learning C and my teacher said it's forbidden.
Can someone tell me a way to take array size from user?
At last, I want to do this two projects:
1- Take n from user and get int numbers from user then reverse print entries.
2- Take n from user and get float numbers from user and calculate average.
The lone way is using array with variable size.
<3
EDIT (ANSWER THIS):
Let me tell full of story.
First Question of my teacher is:
Get entries (int) from user until user entered '-1', then type entry numbers from last to first. ( Teacher asked me to solve this project with recursive functions and with NO any array )
Second Question is:
Get n entries (float) from user and calculate their average. ( For this I must use arrays and functions or simple codes with NO any pointer )
Modern C has variable size arrays, as follows:
void example(int size)
{
int myArray[size];
//...
}
The size shouldn't be too large because the aray is allocated on the stack. If it is too large, the stack will overflow. Also, this aray only exists in the function (here: funtion example) and you cannot return it to a caller.
I think your task is to come up with a solution that does not use arrays.
For task 2 that is pretty simple. Just accumulate the input and divide by the number of inputs before printing. Like:
#include <stdio.h>
#include <stdlib.h>
int main()
{
float result = 0;
float f;
int n = 0;
printf("How many numbers?\n");
if (scanf("%d", &n) != 1) exit(1);
for (int i=0; i < n; ++i)
{
if (scanf("%f", &f) != 1) exit(1);
result += f;
}
result /= n;
printf("average is %f\n", result);
return 0;
}
The first task is a bit more complicated but can be solved using recursion. Here is an algorithm in pseudo code.
void foo(int n) // where n is the number of inputs remaining
{
if (n == 0) return; // no input remaining so just return
int input = getInput; // get next user input
foo(n - 1); // call recursive
print input; // print the input received above
}
and call it like
foo(5); // To get 5 inputs and print them in reverse order
I'll leave for OP to turn this pseudo code into real code.
You can actually use variable sized arrays. They are allowed when compiling with -std=c99
Otherwise, you can over-allocate the array with an arbitrary size (like an upper bound of your actual size) then use it the actual n provided by the user.
I don't know if this helps you, if not please provide more info and possibly what you have already achieved.

Why is my code not executing?

Currently learning C - and I have no clue where I'm going wrong in this code:
#include <stdio.h>
int main()
{
char alphabet[20];
int i;
for (int i = 0; i > 20; i++)
{
printf("Enter in a letter:\n");
scanf("%s", alphabet[i]);
if (alphabet[i] == alphabet[i+1])
{
printf("Duplicate Letters");
};
return 0;
}
}
The program that I am asked to make for class — I'm required to create a 1D array, add validation for alphabetical letters and duplicate letters, as well as creating a function for sorting the letters and specifying the number of times each letter was put in.
As much as I've been able to attempt coding is:
Create a 1D array to read 20 alphabetical letters
Add validation for duplicate letters and printf 'Duplicate Letters'
but every time I try, the program terminates at 'Enter in a letter:' or it won't execute.
Where did I go wrong?
For background: I work mainly on Windows 7 because that's what the school has — using MinGW as my compiler — but for working at home I use MacOS using Terminal as the compiler.
for (int i = 0; i > 20; i++)
You're telling the computer here to initialize i to 0, and then, while i is greater than 20, do the loop. However, since i starts at 0, it will never be greater than 20.
for (int i = 0; i < 20; i++)
And, yes, as comments have pointed out, your use of scanf is incorrect. Lacking a better C reference for it, check out http://www.cplusplus.com/reference/cstdio/scanf/ for descriptions of its arguments.

C minimum function always returning 2686916

I am doing a simple function that returns the minimum integer from numbers given from the user(array).
However, it always print 2686916 at the end. Here is my code:
int function()
{
int ar[100];
int i;
int smallest = INT_MAX;
int nums;
int num;
int sum=0;
printf("\nenter array size\n");
scanf("%d",&num);
for(i=0;i<num;i++)
{
scanf("%d",&ar[i]);
sum=sum+ar[i];
}
if (nums <smallest){
smallest=nums;
printf("the smallest %d\n,smallest);
return 0;
}
}
I'm not sure what I'm doing wrong.
My friend, it seems you are new to C, and before you ask questions like this one you should try to follow some tutorials for C. You might try something like this.
If the question you ask is not clear or the code you post won't compile anyway it is very hard to help you out. For now this is all I can do:
int function()
{
int ar[100];
int i;
int smallest = INT_MAX;
int nums = 0; //Always Initialize your variables!
int num = 0;
int sum= 0;
printf("\nenter array size\n");
scanf("%d",&num);
for(i=0;i<num;i++)
{
scanf("%d",&ar[i]);
sum=sum+ar[i];
}
if (nums <smallest)
{
smallest=nums;
printf("the smallest %d\n",smallest);
}
return 0; //Don't put this in a place that might not be executed!
}
Now it should at least compile, it still doesn't do anything useful as far as I can see. You compare "nums", a variable you didn't use before, with the biggest value of an int, set it to the never used "nums" and print it.
You might want use "sums" or "ar[i]" in the if statement instead, and printing one of these values.(still not 100% sure what you want to do).
Some tips for next time (before you ask a question!):
Variables should always be initialized
In your code you try to use the value of "nums" before it gets a value, this might cause errors or strange results in your code.
Don't put a return in a place that might be skipped,
In your code, "nums" would be bigger than "smallest" (unlikely, bit for example), the code would skip the if statement and never reach the return.
Read your compiler warnings
The code you posted can't compile, read your errors and warnings, and fix them.
(tip) Use better variable names, using names like nums, num and sum make it easy to overlook a mistake.

Pascal's Triangle returning nonsense values

This is a homework project I was assigned some time ago... I've been successful in getting this far on my own, and the only hiccup I have left is (I believe) an issue with data types and overflow.
I've tried changing over to unsigned and double, and the code complies and still accepts input in the terminal, but it seems to hang up after that... nothing is printed and it looks like it's caught in a loop.
Here is the code...
/* pascaltri.c
* A program that takes a single integer as input and returns the nth line of
* Pascal's Triangle. Uses factorial() function to help find items of
* individual entries on a given row.
*/
#include <stdio.h>
#include <stdlib.h>
long factorial(long i)
{
long fact = 1;
while(i > 1)
{
fact = fact * i;
i = i - 1;
}
return fact;
}
main(void)
{
long n;
long *nPtr;
nPtr = &n;
scanf(" %i", nPtr);
if (n >= 0)
{
long k;
long *kPtr;
kPtr = &k;
for(k = 0; k <= n; k++)
{
long ans;
long *ansPtr;
ansPtr = &ans;
ans = factorial(n) / (factorial(k) * factorial(n - k));
printf("\n %i", ans);
}
return 0;
}
return 0;
}
It's not perfect or pretty, but it works up to an input of 13 (that is, row 14) of the triangle. Beyond that I start getting gibberish and even negative values sprinkled throughout the returns... much larger values break the code and return nothing but an exit error message.
Any ideas on how I can correct this problem? I've been staring at the screen for much to long to really see anything myself. Also, it's not essential, but I would like to print my return values on one line, rather than having them separated by a newline character.
1 5 10 10 5 1
Would the easiest way be to load the values into an array as they are computed, and then print the array? Or is there a built-in way I can tell the print statement to occur on only one line?
You are suffering from integer overflow. You may need to find a different approach to the algorithm to avoid having to calculate the large numbers.
In answer to your other point about the newline, you are explicitly printing the newline with the \n in your print statement. Remove it, and you will get answers printed on one line. You probably want to inlucde a final printf("\n"); at the end so the whole line is terminated in a newline.
Some other observations:
You don't need the first return 0; - the control will drop out of
the bottom of the if block and on to the second (should be only)
return 0; and not cause any problems.
You're declaring kPtr but not using it anywhere
You don't need to declare a separate variable nPtr to pass to scanf; you can pass &n directly.
For the garbage, you are most likely running into an integer overflow, that is, your calculated values become too large for the long data type. You should correct it by calculating your factorial function without explicitely calculating n!.
Change scanf(" %i", nPtr); to
scanf(" %ld", nPtr);
and printf("\n %i", ans); to
printf("\n %ld", ans);
to get printout on one line, use:
printf(" %ld", ans);
If you are using gcc, turn on warnings, i.e. use -Wall.

Simply C loop is driving me nuts

So I have only ever programmed in c++, but I have to do a small homework that requires the use of c. The problem I encountered is where I need a loop to read in numbers separated by spaces from the user (like: 1 5 6 7 3 42 5) and then take those numbers and fill an array.
the code I wrote is this:
int i, input, array[10];
for(i = 0; i < 10; i++){
scanf("%d", &input);
array[i] = input;
}
EDIT: added array definition.
any suggestions or hints would be very highly appreciated.
Irrespective of whatever is wrong here, you should quickly learn to NEVER write code that does not check the return value from any API call that you make. scanf returns a value, and you have to be interested in what it says. If the call fails, your logic is different, yes?
Perhaps in this case it would tell you what's going wrong. The docs are here.
Returns the number of fields
successfully converted and assigned;
the return value does not include
fields that were read but not
assigned. A return value of 0
indicates that no fields were
assigned.
This code working good.
If your numbers is less than 10, then you must know how many numbers is before you start reading this numbers, or last number must be something like 0 to terminate output then you can do while(true) loop, but for dynamically solution you must read all line into string and then using sscanf to reading numbers from this string.
You need the right #include and a proper main. The following works for me
#include <stdio.h>
int main(void) {
/* YOUR CODE begin */
int i, input, array[10];
for (i = 0; i < 10; i++) {
scanf("%d", &input);
array[i] = input;
}
/* end of YOUR CODE */
return 0;
}
i'm not a c programmer but i can suggest an algorithm which is to use scanf("%s",&str) to read all the input into a char[] array then loop over it and test using an if statment if the current char is a space, if it is then add the preceeding number to the array

Resources