I have created a function that is supposed to take the numbers in my linked list and determine which one is the smallest number and which one is the largest number. I created a while loop that is supposed to take each number and compare it to the next. 'newNumber' is the current number and 'next' should be the number next in the list. I am having trouble understanding how to call the current and next number. My while loop is also infinite is it because, I am referring to the numbers again in determine?
double NumberSize(NewNumber *start){
NewNumber *determine = start;
double SecondNumber =0;
double FirstNumber = 0;
while(determine != NULL){
FirstNumber = determine->newNum;
SecondNumber = determine->next;
if(FirstNumber < SecondNumber){
printf("The biggest number is:\n", SecondNumber);
}else{
printf("The smallest number is:\n", FirstNumber);
}
}
You forgot to step through the list. Using on of the solutions for the average:
void NumberSize(NewNumber * start)
{
double num = 0.0;
double biggest;
double smallest;
int flag = 0;
NewNumber *temp = start;
// set start values
if(tmp != NULL){
biggest = temp->newNum;
smallest = temp->newNum;
tmp = tmp->next;
flag = 1;
}
// while temp is not NULL
while (temp) {
// get number from current node
num = temp->newNum;
// if that number is bigger than "biggest"
if (num > biggest) {
// exchange "biggest" with "num"
biggest = num;
}
// do it the same way for the smallest number
else if (num < smallest) {
smallest = num;
}
// here is the forgotten line:
// go to the next node
temp = temp->next;
}
if(flag){
// no returns, just printing
printf("The smallest number is: \n", smallest);
printf("The biggest number is: \n", biggest);
} else {
puts("list empty");
}
}
Related
I'm trying to write a program that reads a maximum of 8 bank account information and store them dynamically in a linked list. I wrote a function to calculate the average of all the entered bank accounts' balances but when I try to call that function no output is produced. can you please help me figure out where the problem is?
#include <stdio.h>
#include <stdlib.h>
//node structure
typedef struct node {
int no;
char name[20];
float total;
struct node * nextptr;
}
account;
//int for division of total to find the average
static int t;
//adding accounts function
account * addaccount(account * temp) {
fflush(stdin);
printf("Enter the account name: \n");
gets(temp -> name);
printf("Enter the account number: \n");
scanf("%d", & temp -> no);
printf("Enter the account balance: \n");
scanf("%f", & temp -> total);
t++; // used for finding the average
return temp;
}
// function for calculating the average
float sum(account * temp) {
float average = 1.0, sum = 0.0;
int i;
account * start;
temp = start;
for (i = 0; i < t; i++) {
sum += temp -> total;
temp = temp -> nextptr;
}
average = sum / t;
return average;
}
int main() {
int selection;
account * start = NULL;
account * save, * temp;
account * ptr;
ptr = (account * ) malloc(sizeof(account) * 8);
do {
//Menu
printf("\n1.Adding account\n");
printf("2.Find the average of the added accounts' balances\n");
printf("3.Exit\n");
scanf("%d", & selection);
switch (selection) {
case 1: {
if (ptr == NULL)
ptr = (account * ) realloc(ptr, sizeof(account));
save = addaccount(ptr);
if (start == NULL) {
start = save;
start -> nextptr = NULL;
} else {
temp = start;
while (temp -> nextptr != NULL)
temp = temp -> nextptr;
temp -> nextptr = save;
save -> nextptr = NULL;
}
break;
}
case 2: {
float avg;
avg = sum(temp);
printf("%f", avg);
break;
}
case 3: {
temp = start;
while (temp != NULL) {
free(temp);
temp = temp -> nextptr;
}
break;
}
}
} while (selection != 4);
return 0;
}
Look here
// function for calculating the average
float sum(account* temp) {
float average = 1.0, sum = 0.0;
int i;
account* start; <<<==== a random value
temp = start; <<<=== over write the parameter of this function with a random value
for (i = 0; i < t; i++) {
sum += temp->total;
temp = temp->nextptr;
}
average = sum / t;
return average;
}
Not sure what you are trying to do here - but that is for sure wrong
There are quite a number of problems with your code:
you say you want a maximum of 8 accounts, but there is no such limit being imposed by the code.
in sum() (which is misnamed, BTW), you are not looping through the nodes correctly, because the temp = start; assignment is backwards. start is uninitialized, and then temp is used inside the loop, thus invoking undefined behavior. You don't actually need the start variable at all, since you can simply increment the account* temp parameter.
in main(), you are initially pointing ptr to an array of 8 accounts, but if the user enters 1 on your menu, and ptr is NULL (which it would not be unless that initial malloc() failed), then you are pointing ptr to a single account. If your goal is to allow the user to enter an arbitrary number of accounts, your list management is all wrong.
Worse, every time the user enters 1 on your menu, you are calling addaccount() on the 1st account in the array, and addaccount() simply populates the specified account with data. So, you are not actually creating a new account and adding it to the list, at all. You are just linking the 1st account back to itself, over and over.
if the user enters 2 on your menu, you are calling sum() on the last account created by 1. If no account has been created yet, your code will crash since temp is uninitialized at that point. You need to call the function on the first account instead, so it can iterate the whole list.
if the user enters 3 on your menu, the code tries to free() individual accounts, but you did not actually malloc() individual accounts to begin with. You are trying to store accounts in an array instead, so you would just need to free() the array instead.
Also, your loop is checking for selection != 4, but your menu doesn't have an option 4. You should be checking for selection != 3 instead.
With that said, try something more like this:
#include <stdio.h>
#include <stdlib.h>
//node structure
typedef struct node {
int no;
char name[20];
float total;
struct node * nextptr;
}
account;
//adding accounts function
account* addaccount() {
account *temp = malloc(sizeof(account));
if (temp == NULL) {
printf("Unable to create new account\n");
return NULL;
}
fflush(stdin);
printf("Enter the account name: \n");
gets(temp->name);
printf("Enter the account number: \n");
scanf("%d", &temp->no);
printf("Enter the account balance: \n");
scanf("%f", &temp->total);
temp->nextptr = NULL;
return temp;
}
// function for calculating the average
float average(account* start) {
if (start == NULL) return 0.0;
float sum = 0.0;
int t = 0;
do {
sum += start->total;
start = start->nextptr;
++t;
}
while (start != NULL);
return sum / t;
}
int main() {
int selection;
account *start = NULL, *last = NULL, *temp;
do {
//Menu
printf("1.Adding account\n");
printf("2.Find the average of the added accounts' balances\n");
printf("3.Exit\n");
scanf("%d", &selection);
switch (selection) {
case 1: {
if ((temp = addaccount()) == NULL) break;
if (start == NULL)
start = temp;
else
last->nextptr = temp;
last = temp;
break;
}
case 2: {
printf("%f\n", average(start));
break;
}
}
} while (selection != 3);
temp = start;
while (temp != NULL) {
free(temp);
temp = temp -> nextptr;
}
return 0;
}
I'm new to coding and am learning C. I just had a question regarding while loops.
#include <stdio.h>
int main(void) {
int integer1, integer2, number, sum, largest, smallest;
float average;
integer1 = 0;
number = 0;
sum = 0;
largest = integer1;
smallest = integer1;
while (integer1 != -1) {
printf("Enter the number: ");
scanf_s("%d", &integer1);
number++;
sum = sum + integer1;
if (integer1 >= largest) {
largest = integer1;
}
if (integer1 <= smallest) {
smallest = integer1;
}
}
average = (float) sum / number;
printf("The number of user's input: %d.\n", number);
printf("The sum of input numbers: %d.\n", sum);
printf("The average of input numbers: %.2f.\n", average);
printf("The largest number is: %d.\n", largest);
printf("The smallest number is %d.\n", smallest);
return 0;
}
The objective of the code I've written is to:
Read integer values from the user.
Terminate the while loop when the user enters '-1'.
Output the printf statements with their corresponding values.
Here's the problem: All of the integer variables that I've declared should NOT include the value of '-1; inputted by the user. I assume that this has to do with an issue of precedence regarding the while loop, but I can't seem to pinpoint what it is. Any help or insight is greatly appreciated.
Thank you!
Sometimes neither while nor do/while loop fit your needs, because the decision to exit the loop must be made in the middle of loop's body.
Reading values and deciding what to do after the read presents one of such situations. A common solution is to set up an infinite loop, and exit it from the middle on a break:
for (;;) {
printf("Enter the number: ");
scanf_s("%d", &integer1);
if (integer1 == -1) {
break;
}
... // The rest of your code
}
In order to achieve what you want you need to add one line.
//use infinite loop
while (1) {
printf("Enter the number: ");
scanf_s("%d", &integer1);
//jump out of the loop because the loop has already started.
//but the value was -1
if (integer == -1) break;
number++;
sum = sum + integer1;
if (integer1 >= largest) {
largest = integer1;
}
if (integer1 <= smallest) {
smallest = integer1;
}
}
Just add your scanf() statement prior to your while loop.
I am completely new to programming and I'm currently taking a Intro to programming course. I need to adjust the below code to allow for an unspecified number of positive integers. I've looked this up and it seems to not take the average correctly. Please help. Thank you.
#include <stdio.h>
int main ()
{
/* variable definition: */
int count, value, sum;
double avg;
/* Initialize variables */
count = 0;
sum = 0;
avg = 0.0;
// Loop through to input values
while (count < 20)
{
printf("Enter a positive Integer\n");
scanf("%d", &value);
if (value >= 0) {
sum = sum + value;
count = count + 1;
}
else {
printf("Value must be positive\n");
}
}
// Calculate avg. Need to type cast since two integers will yield an
// integer
avg = (double) sum/count;
printf("average is %lf\n ", avg );
return 0;
}
You can use infinite loop and check for negative value and the return result of scanf as conditions to break.
Sample code looks like:
for(;;)
{
printf("Enter a positive Integer\n");
if(scanf("%d", &value) == 1 )
{
if (value >= 0) {
sum = sum + value;
count = count + 1;
}
else {
printf("Value must be positive\n");
break;
}
}
else
{
break;
}
}
Also, your initialization code is ok, but can be done cleaner this way (there is no need to separate between declaration and initialization - you can group them into one line):
int count = 0, value = 0, sum = 0;
double avg = 0;
I am really new to coding and I need to create a palindrome test that tests numbers up to a given limit. I understand the algorithm to test whether or not a number is a palindrome. However I'm having trouble looping the code.
The output should look like this:
if the limit is 1000:
limit | # of palindromes | sum of reciprocals
100 18 3.086147 (1/10 of the limit)
200 28 3.157490 (2/10 of the limit)
All the way up to the limit given by the user.
I have started the code however my code loops infinitely. Can you please tell me what I am doing wrong? Here is my code.
#include <stdio.h>
#include <math.h>
int main(void) {
double num;
int upperLimit = 0; //Limit of the program.
int numPalindromes = 0;
double sum = 0;
int tempLim;
int i = 1;
printf("Enter the limit of the program:"); //Asks for the limit you want the program to go to
scanf("%d", &upperLimit);
// We now need to use an algorithm to test whether or not the number is a palindrome.
while(num <= upperLimit) {
int temp;
int rev = 0;
temp = num;
while(temp != 0 ){
rev = rev * 10;
rev = rev + temp%10; // we need to add the remainder when the number is divided by 10 to the reverse.
temp = temp/10;
}
/*A number is a palindrome if its reverse is equal to itself. Now we must add its reciprocal to the sum and increase the amount of palindromes by 1 if the number is a palindrome */
if(num == rev) {
sum = sum + (1/num);
numPalindromes = numPalindromes + 1;
}
while (num <= upperLimit) {
tempLim = upperLimit * (i/10);
if (num == tempLim) {
printf(" %d %d %lf\n", tempLim, numPalindromes, sum);
}
i++;
}
num++;
}
}
You have such a snippet:
while (num <= upperLimit) {
tempLim = upperLimit * (i/10);
if (num == tempLim) {
printf(" %d %d %lf\n", tempLim, numPalindromes, sum);
}
i++;
}
However, neither num nor upperLimit is modified inside the loop. Thus it loops forever.
while (num <= upperLimit) {
tempLim = upperLimit * (i/10);
if (num == tempLim) {
printf(" %d %d %lf\n", tempLim, numPalindromes, sum);
}
i++;
}
num is not changing, upperlimit is not changing. So it runs infinitely.
So the goal of this code is to convert a user number into a palindrome. If the number is not a palindrome, calculate the number+reversed number until it becomes a palindrome. If still not a palindrome, take the sum of the last number and it's reverse and add that together, for a maximum of 10 tries.
int main()
{
int n;
int reverse = 0; //initial value will be 0
int temp; //temporary variable
//Check if number is a palindrome===============================
printf("Enter an integer: ");
scanf_s("%d", &n);
temp = n; //Make input number have a temporary variable
while (temp != 0)
{
reverse = reverse * 10;
reverse = reverse + temp % 10;
temp = temp / 10;
}
//Check if number entered by user and it's reverse number is equal
if (reverse == n)
printf("%d\t1, reverse is %d\n", n, reverse); //Is a palindrome
else
printf("%d\t0, reverse is %d\n", n, reverse); //Not a palindrome
//==========================================================================
//Keep adding numbers until it reaches a palindrome
int sum;
while (n /= reverse)
{
sum = n + reverse;
n++;
}
if (reverse == sum)
printf("%d it works", sum, reverse);
else
("%d didn't work", sum, reverse);
I haven't worked on the limit yet. But my question is how would I go about adding the reverse and user's number, then doing the sum + its reverse? Also what kind of loop is best for this kind of question?
What you can do is write the while loop for generating the reverse of number(consider as loop2) in another while loop(consider as loop 1) which breaks(terminates) when the the number is a palindrome.If the given number is not palindrome then you change the number as number=number+reverse.If you want to try for 10 tries then you can add a another condition for loop 1 by taking a counter. Below is the code that I wrote.
#include<stdio.h>
int main()
{
int n;
int count=0; //taking counter for number of trials
int reverse=0; //initial value will be 0
int temp; //temporary variable
printf("Enter an integer: ");
scanf("%d", &n);
while (count<10)
//count less than 10 condition makes the max. no. of trials equal to 10
{
temp=n; //assigning a temporary variable to n
reverse=0;
//Finding the reverse of the number n===============================
while (temp != 0)
{
reverse = reverse * 10;
reverse = reverse + temp % 10;
temp = temp / 10;
}
//Check if number entered by user and it's reverse number is equal
if (reverse == n){
printf("\n%d\t1, reverse is %d\n", n, reverse);
//Is a palindrome
break;
/*break condition makes the loop 1 to terminate if the number 'n' is palindrome*/
}
else
printf("\n%d\t0, reverse is %d\n", n, reverse);
//Not a palindrome
//================================================================
//Keep adding numbers until it reaches a palindrome
n=n+ reverse;
count++;
}
}