This was the question
int num,square;
int array1[100];
int array2[100];
for(int i=0;i<100;i++){
printf("please enter the number %d:",i+1);
scanf("%d",&num);
if(num==-1){
break;
}
else
array1[i]=num;
}
for(int j=0;j<100;j++){
square=array1[j]*array1[j];
array2[j]=square;
}
for(int m=0;m<100;m++){
printf("number %d is %d\n",m,array2[m]);
}
this was the program i made but then the user might input only few int so i want to run the loop which prints the second array only the amount of tym the user inputted how can i do that?
Declare the first loop variable (i) outside the for.
This will remember the point at which the first loop exited.
Then use that for ending second loop instead of a hard-coded value i.e. 100.
int num,square;
int array1[100];
int array2[100];
int i=0;
for( i=0; i < 100; i++ )
{
printf("please enter the number %d:",i+1);
scanf("%d",&num);
if(num==-1)
{
break;
}
else
array1[i]=num;
}
for( int j=0; j < i; j++ )
{
square = array1[j] * array1[j];
array2[j] = square;
}
for(int m=0; m < i; m++)
{
printf("number %d is %d\n", m, array2[m]);
}
Your problem is when the user enters -1 and breaks the input loop. That will leave parts of array1 uninitialized. You are not allowed to access the uninitialized variables. Therefore you need to change the next two for-loops like:
for(int j=0;j<i;j++){
// ^ notice: i instead of 100
square=array1[j]*array1[j];
array2[j]=square;
}
for(int m=0;m<i;m++){
// ^ notice: i instead of 100
printf("number %d is %d\n",m,array2[m]);
}
This requires that the first loop is written like:
int i;
for(i=0;i<100;i++){
so that i is still valid when reaching the next loops.
In this way you avoid accessing uninitialized parts of array1 and you only print the same amount of values as the user did input (before -1).
Beside that... doing:
scanf("%d",&num);
is bad. You shall always check the value returned be scanf to make sure that it scanned the expected number of values, i.e.
if (scanf("%d",&num) != 1)
{
// Illegal input
....
Add error handling here
....
}
Just keep the number of entered numbers in a variable.
To store a product of two objects of the type int it is better to use type long long int.
Also it is not a good idea to use magic numbers as 100 throughout the code.
The program can look the following way
#include <stdio.h>
#define N 100
int main( void )
{
int array1[N];
long long int array2[N];
size_t n = 0;
for ( ; n < N; n++ )
{
int num;
printf("please enter the number %zu: ", n + 1);
if (scanf("%d", &num) != 1 || num == -1) break;
array1[n] = num;
}
for ( size_t i = 0; i < n; i++ )
{
long long int square = (long long int )array1[i] * array1[i];
array2[i] = square;
}
for ( size_t i = 0; i < n; i++ )
{
printf( "number %zu is %lld\n", i, array2[i]);
}
return 0;
}
I have updated your code.
int num,square;
int array1[100];
int array2[100];
int i=0;
for(i=0;i<100;i++){
printf("please enter the number %d:",i+1);
scanf("%d",&num);
if(num==-1){
break;
}
else
array1[i]=num;
}
/* This will only calculate square upto the numbers you have entered
I have changed the condition to <i
*/
for(int j=0;j < i;j++){
square=array1[j]*array1[j];
array2[j]=square;
}
/* This will only print upto the numbers you have entered
I have changed the condition to <i
*/
for(int m=0;m<i;m++){
printf("number %d is %d\n",m,array2[m]);
}
Related
I was given an assignment to write a code which takes in numbers as input from the user and provides the sum of it, specifically by the use of pointer arithmetic i.e. no array subscripting a[i] is allowed.
Below is the code that I wrote, which got compiled and even ran. But almost always it gives the sum of the input numbers as 0. I tried to fix it, but to no avail. Thus, I am asking for help, any help is greatly appreciated.
#include<stdio.h>
#define N 5
int sum_array( const int *p, int n)
{
int sum, a[N];
sum = 0;
for(p=&a[0]; p<&a[N]; p++)
sum += *p;
return sum;
}
int main()
{
int a[N], *i,x;
printf("Enter %d Numbers: ", N);
for(i=a; i<a+N; i++)
scanf("%d", i);
// all the input values get scanned as i or the array a
x= sum_array(i,N);
printf("the sum is %d\n", x);
return 0;
}
Beware, you are declaring array int a[N] in both main and sum_array. They are in different scopes, so they are different arrays (and the one from sum_array is never initialized so reading it invokes Undefined Behaviour).
The correct way is to pass the array along with its used length:
Here is a fixed version:
#include<stdio.h>
#define N 5
int sum_array( const int *a, int n) // a points to a array of at least n elements
{
int sum = 0; // initialize at definition time
for(const int *p=a; p<&a[n]; p++) // have the pointer p take all values from a
sum += *p;
return sum;
}
int main()
{
int a[N], *i,x;
printf("Enter %d Numbers: ", N);
for(i=a; i<a+N; i++)
scanf("%d", i);
// all the input values get scanned as i or the array a
x= sum_array(a,N); // pass the array address, not a pointer past last element
printf("the sum is %d\n", x);
return 0;
}
Finally it is mainly a matter of taste, but I was too often burnt for trying to add an instruction in a for loop without braces, so I strongly recommend using always braces for loops:
for(i=a; i<a+N; i++) {
scanf("%d", i);
}
int sum_array( const int *p, int n)
{
int sum = 0, i = 0;
for(i = 0; i < n ; i++)
sum += *(p+i);
return sum;
}
int main(void)
{
int a[N], i = 0, x = 0;
printf("Enter %d Numbers: ", N);
for(i=0; i<N; i++)
scanf("%d", a+i);
// all the input values get scanned as i or the array a
x= sum_array(a,N);
printf("the sum is %d\n", x);
return 0;
}
In x= sum_array(i,N); i is the iterator of your loop so after the loop has finished it points to the first position after the array.
You should pass the original array instead x= sum_array(a,N);
In the sum function you just throw away the passed pointer and replace it with your local a[].
int sum_array( const int *p, int n)
{
int sum = 0;
int *end = &p[n]; // first element after the array.
for(; p<end; p++) // just use p because you don't need the reference to the start of the array
{
sum += *p;
}
return sum;
}
but as you said that array notation is not allowed you can change it as follows
#include "stdio.h"
#define N 5
int sum_array( const int *p, int n)
{
int sum = 0;
const int *end = p+n; // first element after the array.
for(; p<end; p++)
{
sum += *p;
}
return sum;
}
int main()
{
int *a, *i, x;
a = malloc(N * sizeof(*a));
if (a == NULL)
exit(-1);
printf("Enter %d Numbers: ", N);
for(i=a; i<a+N; i++)
{
scanf("%d", i);
}
// all the input values get scanned as i or the array a
x= sum_array(a,N); // pass the array address, not a pointer past last element
printf("the sum is %d\n", x);
return 0;
}
in general, when programming, the code should be kept as simple as possible while still being complete.
The program criteria shows no need to keep a number after it is applied to the sum of the numbers, So in the proposed code, the input number is only kept long enough to be applied to the sum, then it is discarded.
The following proposed code:
cleanly compiles
performs the desired functionality
is kept very simple
properly checks for; and handles any errors
And now the proposed code:
#include <stdio.h> // scanf(), printf(), fprintf(), stderr
#include <stdlib.h> // exit(), EXIT_FAILURE
#define N 5
int main( void )
{
int num = 0;
int sum = 0;
printf("Enter %d Numbers: ", N);
for(size_t i=0; i<N; i++)
{
if( scanf("%d", &num) != 1 )
{
fprintf( stderr, "failed to read number\n" );
exit( EXIT_FAILURE );
}
// implied else, scanf successful
sum += num;
}
printf( "the sum is %d\n", sum );
return 0;
}
This code is to find the mean, median and mode for a given sequence of number.
#include <stdio.h>
#include <math.h>
int main()
{ /*Inputs*/
int n;
int a[n];
/*Outputs*/
float mean;
int median;
int mode;
printf("Enter the size of array: ");
scanf("%d",&n);
for(int i=0; i<n; i++)
{
printf("\nEnter the values of array: ");
scanf("%d",&a[i]);
}
/*arrange in ascending order */
int i=0;
for(i=0; i<n-1; i++)
{for(i=0; i<n-1; i++)
{
if(a[i]>a[i+1])
{
int temp = a[i+1];
a[i+1] = a[i];
a[i] = temp;
}
}
}
/*Mean of the series*/
for(i=0; i<n; i++)
{
int sum = 0;
sum = sum + a[i];
mean = sum/n;
}
/*Median of the series*/
I hope the syntax of typecasting here is right, right?
int m = floor((double)n/2);
if(n%2==0)
{
median = (a[m]+a[m-1])/2;
}
else
{
median = a[m];
}
/*Mode of the series*/
int count;
int b = 0;
for(i=0; i<n-1; i++)
{
for(int t=0; t<n; t++) //Compare a[i] with all the elements of the array
{if(a[i]==a[t])
{
count = 0;
count++;
}
if(b<count) //Update the new value of mode iff the frequency of one element is greater than that
{ // of its preceding element.
mode = a[i];
}
}
}
printf("The value of mean: %f",mean);
printf("\nThe value of mean: %d",median);
printf("\nThe value of mean: %d",mode);
return 0;
}
There were no errors in the code.
I received the following message on the prompt after "CentralT...... working":
Process returned -1073741571 (0xC00000FD) execution time : 47.686 s
Press any key to continue.
In C you cannot resize an array.
This line
int n;
defines n and leaves its value as garbage, a random value, perhaps 0.
Based on what ever n holds this line
int a[n];
defines a as array to have the number of element as per n now has.
Reading into n in this line
scanf("%d",&n);
does not change the number over a's elements.
To fix this, define a only after n has a well defined, valid value:
scanf("%d",&n);
int a[n];
To really make sure n had been set you want to test the outcome of scanf() like for example:
do {
if (1 != scanf("%d, &n))
{
puts("Bad input or failure reading n!\n");
continue;
}
} while (0);
I am working on a program that will accept user input to fill an array and then quit when the user enters q. Next the array is passed to a function that finds the largest value in the array. My program seems like it would work, but I believe that user input for the array is incorrect and I am not sure how to solve it.
#include <stdio.h>
#define SIZE 30
int maxnum(int userarray[], int maxx);
int main()
{
int i;
int nums[SIZE];
int largest;
printf("Type integer numbers (up to 30), followed by q to quit:\n");
while(scanf("%d", &nums[i]) == 1)
{
for(i = 0; i < SIZE; i++)
{
//blank
}
}
largest = maxnum(nums, SIZE);
printf("The largest number is: %d\n", largest);
return 0;
}
int maxnum(int userarray[], int maxx)
{
int i;
int maxnumber;
maxnumber = userarray[0];
for(i = 1; i < maxx; i++)
{
if(maxnumber < userarray[i])
{
maxnumber = userarray[i];
}
}
return maxnumber;
}
First i is unitialized.
Then your inner for loop is strange (why someone would do that??) and sets i to SIZE in the end, which is not good.
I don't give more details, but the value of i is trash all the time because of those 2 mistakes it should be:
int i = 0;
while((i<SIZE) && (scanf("%d", &nums[i]) == 1))
{
i++;
}
so you read one by one, and protect against array out of bounds by the second condition.
After that you're passing NUMS
largest = maxnum(nums, SIZE);
whereas the array could contain fewer valid values. Just pass
largest = maxnum(nums, i);
Here is another solution for your problem.
In main() function
int n,i=0;
while(scanf("%d",&n) == 1){
nums[i++] = n;
}
n = maxnum(nums, i);
printf("The largest number is: %d\n", n);
Note : Initialize the value of i=0, Then input and update nums[] array
In maxnum() function
for(i = 0; i < maxx; i++) {
if(maxnumber < userarray[i]){
maxnumber = userarray[i];
}
}
Note: Start i=0 and find the max mumber and return the value
Summary:
I want to be able to write a function that can let me store 10 values. I should be able to exit the loop with 0 without storing 0 to the array. I should be able to re-enter the array and keep storing until i get 10 values.
Questions:
I started to write something simple but when I store like 5 values it will print out the 5 values and then some random numbers. Why is that?
And how can I exit the loop without the array storing the 0?
I'm quite new to this stuff so I hope I've followed the rules correctly here.
Code:
#include <stdio.h>
int main(void)
{
int arrayTable[9] = {0};
int i;
for (i=0; i<10; i++)
{
printf("Enter Measurement #%i (or 0): ", i+1);
scanf("%d", &arrayTable[i]);
if (arrayTable[i] == 0)
{
break;
}
}
for (int i=0; i<10; i++)
{
printf("%d\n", arrayTable[i]);
}
return 0;
}
#include <stdio.h>
#define ArraySize 10
int main(void){
unsigned v, arrayTable[ArraySize] = {0};
int n = 0;//number of elements
while(n < ArraySize){
printf("Enter Measurement #%i (or 0): ", n + 1);
if(1 != scanf("%u", &v) || v == 0){//use other variable
break;
}
arrayTable[n++] = v;
}
for (int i = 0; i < n; ++i) {
printf("%u\n", arrayTable[i]);
}
return 0;
}
as long as you want discard 0 from array then use a temporary variable, input it, check whether it is a non-zero and if so store it to the element of array, if it is a zero exit the loop:
#include <stdio.h>
int main(void)
{
int arrayTable[10] = {0};
int iValue = 0;
int i = 0;
while(i < 10)
{
printf("Enter Measurement #%i (or 0): ", i+1);
scanf("%d", &iValue); // input iValue
if (!iValue) // if iValue is zero then exit loop without affecting array with this value
break;
else
{
arrayTable[i] = iValue; // if the value is non-zero store it in array and continue
i++;
}
}
for (int i = 0; i < 10; i++)
{
printf("%d\n", arrayTable[i]);
}
return 0;
}
You probbaly want this:
...
int arrayTable[10] = {0}; // <<< [10] instead of [9]
...
for (i=0; i<10; i++)
{
if (arrayTable[i] == 0) // <<< add this
break; // <<<
printf("%d\n", arrayTable[i]);
}
...
I'm having problems with this code because when I run it i get an infinite loop with the number random generator. What I'm trying to do is to assign to an array , 99 numbers from 1 to 9 and then make some mathematical simple operations.
#include <stdio.h>
#include <stdlib.h>
#define SIZE 99
void mean(const int a[]);
void median( int a[]);
void mode(int freq[] , const int a[]);
int main (void) {
int response[SIZE];
int frequency [10];
int i;
srand(time(NULL));
for (i = 0; i<= SIZE ; i++) {
response[i] = (rand() % 6) +1 ;
printf("%d", response[i]);
}
mean(response);
median( response);
mode(frequency , response);
return 0;
}
void mean(const int a[]){
int j , total = 0;
float mean;
printf("********\n%6s\n********\n\nThe mean is the average value of the data\nitems.", "Mean");
printf("The mean is equal to the total of\n all the data items");
printf("divided by the number\n of data items (%d):", SIZE);
for( j = 0 ; j <= SIZE ; j++){
total += a[j];
}
mean = (float) total / SIZE;
printf("The mean value for\nthis run is %d / %d = %f", total, SIZE, mean);
}
void median( int a[]){
int i, j, n, median, hold;
n=1;
hold = 0;
printf("********\n%7s\n********\n\nThe unsorted array of responses is\n", "Median");
for (i=0;i<=SIZE;i++){
if ((i/10) <= n){
printf("%d", a[i]);
}
else{
printf("\n");
n++;
}
}
printf("The sorted array is\n");
for(i=0;i<=SIZE;i++){
for(j=0;j<=SIZE-1;j++){
if (a[j]>a[(j+1)]){
hold = a[j];
a[j] = a[ (j + 1)];
a[ (j + 1)] = hold;
}
}
if ((i/10) <= n){
printf("%d", a[i]);
}
else{
printf("\n");
n++;
}
}
median = a[SIZE/2];
printf("The median is element %d of\nthe stored %d element array.\n", SIZE/2 , SIZE);
printf("For this run the median is %d", median);
}
void mode ( int freq [] , const int a[]){
int j, o, mode , i, rating;
printf("********\n%6s\n********\n\n%10s%12s%12s", "Mode" ,"Response" ,"Frequency", "Histogram");
for(j=0; j<= SIZE ; j++){
++freq[a[j]];
}
for (i=0 ; i <= 10 ; i++){
printf("%10d%12d ", i, freq[i]);
for (o=0; o<=freq[i];o++){
printf("*");
}
printf("\n");
if (freq[i] > freq[i+1]){
mode = freq[i];
rating = i;
}
}
printf("The mode is the most frequent value.\n");
printf("For this run the mode is %d which occured %d times", rating ,mode);
}
C arrays are zero-based so valid indexes for
int response[SIZE];
are [0..SIZE-1]. Your loop writes to response[SIZE] which is beyond the end of memory assigned for response. This results in undefined behaviour.
If you're getting an infinite loop, it sounds as if the address of response[SIZE] is the same as the address of the loop counter i. (rand() % 6) +1 will be in the range [1..6] so the final iteration of the loop before exit will always reset i to a lower value.
You can fix this by changing your loop to exit one iteration sooner. i.e. Change
for (i = 0; i<= SIZE ; i++) {
to
for (i = 0; i< SIZE ; i++) {
Note that your other functions all have similar bugs. All for loops should replace their <= exit conditions with <
You write past the end of your arrays when you access array[SIZE].
Any array declared
type_t array[SIZE];
doesn't have an element array[SIZE]. So all loops must be from 0 to < SIZE, not <= SIZE.
This is known as an off-by-one error in computer literature. You're not the first and will not be the last, if it's any consolation :-)
Technically this invokes undefined behavior, of which an infinite loop is one way. But see my comment below for a wild-assed guess at what is really happening here.