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.
Related
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.
I have a code that works perfectly, its finding average of all numbers that were put in the array and its finding average of a section of array. I just need to make second function that is working with the array with its indexes.
Code:
#include <stdio.h>
#include <stdlib.h>
double priemer(double *pole, int dlzka);
int main()
{
int i, dlzka;
printf("Zadaj velkost pola: ");
scanf("%d", &dlzka);
while (dlzka < 1)
{
printf("Chyba! Cislo musi byt viac, ako 0.\n");
printf("Zadaj pocet prvkov znova: ");
scanf("%d", &dlzka);
}
double *pole = malloc(dlzka * sizeof(double));
for(i = 0; i < dlzka; i++)
{
printf("cislo %d: ", i + 1);
scanf("%lf", &pole[i]);
}
printf("Priemer vsetkych prvkov v poli je: %.3lf\n", priemer(pole, dlzka));
int zaciatok, koniec;
printf("Zadaj zaciatok useku: \n");
scanf("%d", &zaciatok);
printf("Zadaj koniec useku: \n");
scanf("%d", &koniec);
if(koniec > dlzka || zaciatok > koniec || zaciatok < 1)
{
printf("Zly vstup");
return 1;
}
printf("Priemer od %d. do %d. prvku je: %.3lf\n", zaciatok, koniec, priemer(pole + (zaciatok - 1), koniec - (zaciatok - 1)));
return 0;
}
double priemer(double *pole, int dlzka)
{
double sum = 0;
int i;
for(i = 0; i < dlzka; i++)
{
sum += pole[i];
}
return sum/dlzka;
}
I have a certain exercise I must do. Hopefully someone understands what I have failed to do.
whenever a user presses enter, types in less than 10 integers, presses q to exit the option and then comes back, all of his input values will be gone. I want to input values to be left there until the total elements stored are 10. How do I do this?
Note! The user is not supposed to exit the application (which in this case is CMD), rather they should only be able to leave the "enter" option and still have their input values "stored".
#include <math.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#define L 10
void view(int a[])
{
int i;
printf("\n Here are the currently stored values\n");
printf("[");
for(i=0; i<L; i++)
{
printf(" %d ",a[i]);
}
printf("]");
}
int enter(int a[], int n)
{
printf("\n Note! You can press any letter if you want to return to the main menu. \n");
for(int i=0; i<L; i++)
{
int mesa;
printf(" Enter measurement #%d (or q to quit): ", n+1);
int check = scanf("%d",&mesa);
if(check)
{
a[i] = mesa;
n++;
}
else
{
char temp;
scanf(" %c",&temp);
return n;
}
}
return n;
}
void compute(int a[], int n)
{
printf(" Computing...\n");
//Min value
{
int i;
int min = 10000;
for (i = 0; i < L; i++)
if(a[i] < min)
min = a[i];
printf("\n The min value is: %d \n", min);
}
//Max value
{
int i;
int max = a[0];
for (i = 0; i < L; i++)
if (a[i] > max)
max = a[i];
printf(" The max value is: %d \n", max);
}
// Average & Normalization
{
float average;
int i;
int norm;
int sum;
for(i = 0; i < L; ++i)
{
sum = sum + a[i];
average = (float)sum / 10; //typecast - Ge en interger en tillfällig roll. På så sätt kan du säga åt programmet att du faktiskt vill ha float som svar och inte ett heltal som svar.
}
printf(" Average value: %.2f \n", average);
printf(" Normalized array: [");
for(i = 0; i < L; i++)
{
norm = a[i] - average; //average - every a[]
printf(" %d", (int)round(norm));
}
printf(" ]");
}
}
void reset(int a[])
{
printf(" You have chosen to reset the array. All the elements in the array will now be deleted. \n");
//memset( a, 0, 10*sizeof(a)); <--- Kan ej användas då sizeof() funktionen läser av en variabel och inte hela arrayens storlek.
memset( a, 0, 10*sizeof(int*));
}
int main()
{
char command;
int a[L];
printf(" Hello and welcome to this measurement tool. In this program you will be able to type in and analyze data.\n");
printf(" In the section below, you can choose a letter v,e,c,r or q to do certain things. More information will be provided down below.\n");
printf("\n v(View) - Displays currently stored values.");
printf("\n e(Enter) - Allows you to store values. ");
printf("\n c(Compute) - Displays the maxiumum, minimum, normalized and average value of those which are stored.");
printf("\n r(Reset) - Deletes all stored values.");
printf("\n q(Quit) - Exits the program. \n");
printf("\n Please choose one of the commands above: ");
do
{
int n = 0;
scanf(" %c",&command);
switch(command)
{
case 'v' : view(a);break;
case 'e' : enter(a,n);break;
case 'c' : compute(a,n);break;
case 'r' : reset(a);break;
default : printf("\n Please choose one of the options given.\n");break;
case 'q' :
{
printf(" Want to exit? Confirmation needed. Press q again to exit.");
scanf(" %c",&command);
}
}
printf("\n VECRQ?: ");
} while(command != 'q');
return 0;
}
In main(), move the declaration of n outside the loop:
int n = 0;
do
{
...
Update n when you call enter():
n = enter(a,n);
In the enter function, start your loop from n:
for(int i=n; i<L; i++)
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]);
}
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.