My problem: I do not know how to delete the last element entered inside the array. The program should stop when the user enters a negative number and should not include the negative number inside the array. I tried, but I cant find the solution. This is my Code:
int main () {
float array[20];
float max ,min;
float rem;
int i;
char op;
for (i = 0; i <= 20; i++){
printf("Enter the element inside array[%d]: ",i);
scanf("%f", &array[i]);
if (array[i] < 0)
break;
}
printf("Enter ......: ");
scanf("%s", &op);
switch (op){
case 'h':
max = array[0];
for (i = 0; i < 20; i++){
if (max < array[i]){
max = array[i];
}
}
printf("The biggest number is: %f\n", max);
break;
case 'l':
min = array[0];
for (i = 0; i < 20; i++){
if (min > array[i]){
min = array[i];
}
}
printf("The smallest number is: %f\n", min);
break;
}
return 0;
}
Please help , I run out of ideas.
Thank you very much.
Simply check entered value before storing in array:
int main () {
float array[20]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
float max ,min;
float rem;
int i;
float a;
char op;
for (i = 0; i < 20; i++){
printf("Enter the element inside array[%d]: ",i);
scanf("%f", &a);
if (a < 0)
break;
array[i]=a;
}
i am sorry for my last answer but this is true ;)
#include<stdio.h>
int length(const float *array) {
int count = 0;
while(array[count]) count++;
return count;
}
void main () {
float array[20];
float max ,min;
float rem,input;
int i;
char op;
int length = 0;
for (i = 0; i < 20; i++){
printf("Enter the element inside array[%d]: ",i);
scanf("%f", &input);
if (input < 0)
break;
length++;
array[i] = input;
}
printf("Enter ......: ");
scanf(" %c", &op);
switch (op){
case 'h':
max = array[0];
for (i = 0; i < 20; i++){
if (max < array[i]){
max = array[i];
}
}
printf("The biggest number is: %f\n", max);
break;
case 'l':
min = array[0];
for (i = 0; i < length; ++i){
if (min > array[i]){
min = array[i];
}
}
printf("The smallest number is: %f\n", min);
break;
}
system("pause");
}
Use a temporary variable before , if it is positive store in array , if not take necessary actions.
for (i = 0; i < 20; i++){
printf("Enter the element inside array[%d]: ",i);
scanf("%f", &x) // declare x as float x;
if (x< 0) // if negative break
break;
array[i]=x; // store into array
}
And also some problems in your program -
printf("Enter ......: ");
scanf("%s", &op); // op is char variable use %c specifier
^ use instead %c
Write like this instead-
scanf(" %c", &op);
this first loop access index out of bound causing UB
for (i = 0;i<=20; i++){ // change condition to i<20 (index can go from 0 to 19)
//your code // as array is declared as float array[20]
}
Both the loops for max and min can go like this -
for (i= 0;array[i]; i++){ // no need to keep track of length of array
Click on link to see working code.
Related
I'm creating a program that compares numbers with their respective exponents, and indicates which of the three is the smallest. The problem is that I wouldn't want it to perform the operation, for example:
Let's say the smallest number was $4^{8}$, so it would calculate that value, but I want it to just print "4^8" on the screen, or related things, but without doing that operation (in this case, it prints 65536).
int main()
{
int a, b, c, smaller, x, y, z, for_a, for_b, for_c;
printf("first value: ");
scanf("%d", &a);
printf("Second value: ");
scanf("%d", &b);
printf("Third value: ");
scanf("%d", &c);
printf("Value of x: ");
scanf("%d", &x);
printf("Value of y: ");
scanf("%d", &y);
printf("Value of z: ");
scanf("%d", &z);
for_a= pow(a, x);
for_b= pow(b, y);
for_c= pow(c, z);
if (for_a< for_b && for_a < for_c){
smaller= for_a;
}
else if (for_b < for_c){
smaller = for_b;
}
else {
smaller = for_c;
}
printf("Smaller= %d\n", smaller);
return 0;
}
You need to identify the set of data that corresponds to your result. Storing the result only is not enough.
You could do this as follows:
#include <stdio.h>
#typedef struct values_s{
int base;
int exponent;
int result;
} values_t;
#define NUMBER_OF_VALUES 3
int main(void)
{
values_t values[NUMBER_OF_VALUES];
for (int i = 0; i < NUMBER_OF_VALUES; i++)
{
printf("Base value #%d: ", i+1);
fflush(stdout);
int result = scanf("%d", &values[i].base);
// TODO: Error handling in case result != 1
}
for (int i = 0; i < NUMBER_OF_VALUES; i++)
{
printf("Exponent #%d: ", i+1);
fflush(stdout);
int result = scanf("%d", &values[i].exponent);
// TODO: Error handling in case result != 1
}
for (int i = 0; i < NUMBER_OF_VALUES; i++)
{
values[i].result = pow(values[i].base, values[i].exponent);
}
int smallest = 0;
for (int i = 1; i < NUMBER_OF_VALUES; i++)
{
if (values[i].result < values[smallest].result)
{
smallest = i;
}
}
printf("Smallest: %d^%d = %d\n", values[smallest].base, values[smallest].exponent, values[smallest].result);
return 0;
}
This is based on the assumptions that your variables of type int are large enough to hold the values you are dealing with. Otherwise you need to adjust accordingly.
I'm writing a program where the user enters numbers and the program will find MAX and MIN and the position of these numbers. I want to give the user a choice for the program to fill in the numbers for him using rand().
It's working almost perfectly: the program will find the MAX number with the position but the problem occurs when printing MIN number with position -- it always prints number 8 and position 1.
Where is the problem?
Here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
typedef struct elementposition {
int min;
int max;
int positionMax;
int positionMin;
} elementposition;
int main() {
struct elementposition minmax;
srand(time(NULL));
int a[500], i;
int c = sizeof(a) / sizeof(a[0]);
char y;
printf("How many numbers you want to enter: ");
scanf("%d", &c);
minmax.positionMax = minmax.positionMin = 0;
printf("Want to fill with random numbers? (Y/N)");
scanf(" %c", &y);
if (y == 'Y' || y == 'y') {
for (i = 0; i < c; i++) {
a[i] = rand() % 10000 + 1;
if (minmax.max < a[i]) {
minmax.max = a[i];
minmax.positionMax = i;
}
if (minmax.min > a[i]) {
minmax.min = a[i];
minmax.positionMin = i;
}
}
for (i = 0; i < c; i++) {
printf("Number #%d: %d\n", i + 1, a[i]);
}
} else {
printf("------------------------------------ \n");
printf("Enter (%d) numbers: \n", c);
scanf("%d", &a[0]);
minmax.max = minmax.min = a[0];
for (i = 1; i < c; i++) {
scanf("%d", &a[i]);
if (minmax.max < a[i]) {
minmax.max = a[i];
minmax.positionMax = i;
}
if (minmax.min > a[i]) {
minmax.min = a[i];
minmax.positionMin = i;
}
}
}
printf("\nMax number is %d, number position %d. \n", minmax.max, minmax.positionMax + 1);
printf("Min number is %d, number position %d. \n", minmax.min, minmax.positionMin + 1);
printf("------------------------------------ \n");
getch();
return 0;
}
You never initialize minmax.min nor minmax.max in the random case. The code has undefined behavior because it depends on uninitialized values which may be anything, including trap values on some rare architectures.
You should separate the input/generation phase from the scanning phase and use a common loop for that. Also check that c is positive and does not exceed the length of the array.
Here is a modified version:
#include <stdio.h>
#include <stdlib.h>
typedef struct elementposition {
int min;
int max;
int positionMax;
int positionMin;
} elementposition;
int main() {
struct elementposition minmax;
int a[500];
int i, count, len = sizeof(a) / sizeof(a[0]);
char y = 'y';
printf("How many numbers you want to enter: ");
if (scanf("%d", &count) != 1 || count < 1 || count > len) {
printf("invalid count\n");
return 1;
}
printf("Want to fill with random numbers? (Y/N)");
scanf(" %c", &y);
if (y == 'Y' || y == 'y') {
srand(time(NULL));
for (i = 0; i < count; i++) {
a[i] = rand() % 10000 + 1;
printf("Number #%d: %d\n", i + 1, a[i]);
}
} else {
printf("Enter (%d) numbers:\n", c);
for (i = 0; i < count; i++) {
if (scanf("%d", &a[i]) != 1) {
printf("invalid input\n");
return 1;
}
}
}
minmax.positionMax = minmax.positionMin = 0;
minmax.max = minmax.min = a[0];
for (i = 1; i < count; i++) {
if (minmax.max < a[i]) {
minmax.max = a[i];
minmax.positionMax = i;
}
if (minmax.min > a[i]) {
minmax.min = a[i];
minmax.positionMin = i;
}
}
printf("------------------------------------\n");
printf("Max number is %d, number position %d.\n", minmax.max, minmax.positionMax + 1);
printf("Min number is %d, number position %d.\n", minmax.min, minmax.positionMin + 1);
printf("------------------------------------\n");
getch();
return 0;
}
You use minmax.min and minmax.max before initializing them. Here the problem for finding the min is probably that the minmax.min happens to initialy contain the value 8 and that all the values are greater.
The common way is to initialize the min to the highest possible value and max to the lowest one. As you use int values:
struct elementposition minmax = { INT_MAX, INT_MIN };
should be enough.
The function that is commented out is my function, the other is the one I picked from internet. There are no errors. The code just asks for 5 numbers, then asks to operate one of 4 operations, here (s) being for standard deviation, and then runs that function.
From what I've troubleshooted, it isn't reading the elements of the array. It isn't adding, removing, or doing anything with them. It just prints out a zero when asked to print something else in that function.
I'm a newbie, as is implied by the type of question I'm solving, but it'd be great if somebody could help me out here.
Thanks!
#include<stdio.h>
#include<math.h>
int arr[5];
int curnum, i; i = 0;
char op;
int incount; incount = 5.0;
int main();
int main(){
for (i=0; i<incount; i++)
{
printf("Enter a number : ");
scanf("%d", &arr[i]);
}
printf("What would you like to calculate? Average(a), Max(M), Min(m), Std. Dev.(s) : ");
scanf(" %c", &op);
float average(int arr[]);
float std(int arr[]);
switch (op){
case 'a':
printf("The average is %f \n", average(arr)); break;
case 'M':
printf("The Max number is %d \n", max(arr)); break;
case 'm':
printf("The Min num is %d \n", min(arr)) ; break;
case 's':
printf("the Standard Deviation is %f \n", std(arr)); break;
default:
printf("Invalid function \n"); break;
}
return 0;
}
float average(int arr[]){
float netsum;
netsum = 0;
for (i=0; i<incount; i++)
{
netsum = netsum + arr[i];
}
return (netsum/5);
}
int max(int arr[]){
int maxnum;
maxnum = arr[0];
for (i=0; i<incount; i++)
{
if (arr[i] > maxnum) maxnum = arr[i];
}
return maxnum;
}
int min(int arr[]){
int minnum;
minnum = arr[0];
for (i=0; i<incount; i++)
{
if (arr[i] < minnum) minnum = arr[i];
}
return minnum;
}
// float std(int arr[]){
// float currsq, sqsum, stdeviation; currsq = 0; sqsum = 0;
// for (i=0; i<incount; i++){
// currsq = arr[i] - average(arr);
// currsq = currsq*currsq;
// sqsum = sqsum + currsq;
// }
// stdeviation = pow (sqsum/incount, 0.5);
// return stdeviation;
// }
float std(int arr[]) {
float sum = 0.0, mean, SD = 0.0;
int i;
for (i = 0; i < 10; ++i) {
sum += arr[i];
}
mean = sum / 10;
for (i = 0; i < 5; ++i)
SD += pow(arr[i] - mean, 2);
return sqrt(SD / 10);
}
You are trying to dealing with 10 elements in your function std() while there are only 5.
You should use incount instead of the magic number.
float std(int arr[]) {
float sum = 0.0, mean, SD = 0.0;
int i;
for (i = 0; i < incount; ++i) {
sum += arr[i];
}
mean = sum / incount;
for (i = 0; i < incount; ++i)
SD += pow(arr[i] - mean, 2);
return sqrt(SD / incount);
}
Magic number is also used in the function average, but it didn't cause harm because 5 is used.
Also note that
int incount; incount = 5.0;
is not the right way to set initial value of gloval variables.
It should be
int incount = 5.0;
Same thing applies to the global i.
I'm sorry, absolutely noobie mistake. As I said from my testing, it wasn't taking any values from the array. That was because I didn't create the Variable (i) inside the function that was being used in the for loop.
I just added
int i;
inside the function, and voila.
My array isn't printing out all the data, just whatever was last inputted. The data should print something like this
For the student number, if not enough numbers are inputted, 0's are automaticaly put in.
/*
Name:
Date: 10/06/2016
Workshop 4
*/
#include <stdio.h>
int main(void)
{
int counter;
int marks [40];
float num_grades = 0;
int row = 1;
float sum = 0;
float average = 0;
int pass = 0;
int fail = 0;
float pass_sum = 0;
float fail_sum = 0;
float pass_average = 0;
float fail_average = 0;
float biggest = 0;
float smallest = 0;
//int grade[40];
int student_num[40];
printf(" ---=== IPC mark Analyser V2.0 ===---\n");
printf("Please enter the number of students(between 3 and 40): ");
scanf("%d", &counter);
while (counter >40 || counter <3)
{
printf("Invalid number, enter a number between 3 and 40 inclusive: ");
scanf("%d", &counter);
}
printf("Row Std No Mrk\n");
printf("--- --------- ---\n");
num_grades = counter;
while (counter > 0)
{
printf("%d ", row);
printf("_____________ ___\r%3d ", row);
scanf("%d", &student_num[40]);
scanf("%d", &marks[40]);
row++;
counter--;
sum += marks[40];
}
for (int i = 0; i < num_grades; i++)
{
printf("%03d %09d %3d\n", row, student_num[40], marks[40]);
}
average = sum / num_grades;
printf("-----------------\n");
printf("-----------------\n");
printf("Marks Entered, printing results:\n");
printf("Row Std No Mrk\n");
printf("--- --------- ---\n");
printf("The average of all marks in this group is %.1f.\n", average);
printf("Program Ended.\n");
return 0;
}
You're always reading/writing index 40 in the student_num and marks arrays, so everything goes to the same place.
Actually, the valid indexes of an array of size 40 are 0 to 39, so you're actually reading/writing off the end of the array, causing undefined behavior.
You need to use the proper index in each place. In the printing loop, use i. In the reading loop, use a variable that starts at 0 goes up to counter.
num_grades = counter;
for (int i = 0; i < num_grades; i++)
{
printf("%d ", i + 1);
printf("_____________ ___\r%3d ", i + 1);
scanf("%d", &student_num[i]);
scanf("%d", &marks[i]);
sum += marks[i];
}
for (int i = 0; i < num_grades; i++)
{
printf("%03d %09d %3d\n", row, student_num[i], marks[i]);
}
School project for Computer Science. I need to make a program where the user declares a size for an array, then fills the array in numerical, nondecreasing order, then declares a value, x. X is then assigned to the appropriate spot so the entire array is in numerical, nondecreasing order. The array is then output.
The code builds properly with no errors, but the output is messed up.
#include <stdio.h>
int main (void) {
//Local Declarations
int size;
int ary[100];
int x;
int i;
int j;
//Statements
printf("Enter the size of the array: ");
scanf("%d", &size);
printf("\nEnter digits to fill the array, in numerical order: ");
for (i = 0; i < size; i++) {
scanf("%d", &ary[i]);
}
size++;
printf("\nInput x, the value to add to the array: ");
scanf("%d", &x);
while(i=0 <= x && x > ary[i]){
i++;
j = size - 1;
while(j >= i) {
ary[j++] = ary[j];
j--;
}
}
for(i = 0; i < size; i++) {
printf("%d,", ary[i]);
}
return 0;
} //main
Example Output:
Enter the size of the array: 5
Enter digits to fill the array, in numerical order: 1
2
3
4
5
Input x, the value to add to the array: 6
1,2,3,4,5,1630076519,
Process returned 0 (0x0) execution time : 8.585 s
Press any key to continue.
It's always the last value that messes up to that huge number. I cannot for the life of me figure out why. The project is due by midnight EST.
For the while loop, can you try this instead,
i = 0;
while (i < x && x > ary[i]) {
i++;
j = size - 1;
while (j >= i) {
j++;
ary[j] = ary[j]; // Equivalent to ary[j++] = ary[j];, yet easier to read
j--;
}
}
Try this:
#include <stdio.h>
int main (void) {
//Local Declarations
int size;
int ary[100];
int x;
int i;
int j;
int temp1,temp2;
//Statements
printf("Enter the size of the array: ");
scanf("%d", &size);
printf("\nEnter digits to fill the array, in numerical order: ");
for (i = 0; i < size; i++) {
scanf("%d", &ary[i]);
}
printf("\nInput x, the value to add to the array: ");
scanf("%d", &x);
for(i=0;i<size;i++)
{
if(ary[i]>x)
{
temp1 = ary[i];
ary[i] = x;
break;
}
}
if(i==size)
{
ary[i]= x;
}
else
{
for(j=i+1;j<size+1;j++)
{
if(j==size) //Last element of the new array
{
ary[j] = temp1;
break;
}
temp2 = ary[j];
ary[j] =temp1;
temp1 = temp2;
}
}
for(i = 0; i < size+1; i++) {
printf("%d,", ary[i]);
}
return 0;
} //main