Calendar in c with sum of last row - c

I'm trying to make a one-month calendar that prints the sum of the last row of days.
The output of this is correct for the calendar, but the sum keeps printing out that it's 0. For an input of 3=day_of_week and 30=days_in_month, the sum should be 26+27+28+29+30 = 140
Thanks.
int main() {
int day_of_week, days_in_month, i, row=1, array[31], sum=0, a;
printf("Enter the day of the week 1=sun, 2=mon, 3=tue, 4=wed, 5=thurs, 6=fri, 7=sat\n");
scanf("%d", &day_of_week);
printf("Enter the number of days in this month:\n");
scanf("%d", &days_in_month);
for (i=0; i<3*day_of_week; i++)
printf(" ");
for (i=1; i<=days_in_month; i++) {
printf("%3d", i);
array[i] = i;
day_of_week++;
if (day_of_week%7==0){
printf("\n");
}
}
printf("\n");
for (a=days_in_month; a>=(days_in_month-(7-day_of_week)); a--)
sum+=array[a];
printf("sum of last row is %d\n", sum);
return 0;
}

I don't understand why you are doing ++day_of_week,
something like this should work better:
int main()
{
int day_of_week, days_in_month, i, row=1, array[31], sum=0, a;
printf("Enter the day of the week 1=sun, 2=mon, 3=tue, 4=wed, 5=thurs, 6=fri, 7=sat\n");
scanf("%d", &day_of_week);
printf("Enter the number of days in this month:\n");
scanf("%d", &days_in_month);
for (i = 0; i < 3 * day_of_week; i++)
printf(" ");
for (i = 1; i <= days_in_month; i++)
{
printf("%3d", i);
array[i] = i;
if (i % 7 == 0)
printf("\n");
}
printf("\n");
for (a=days_in_month; a>=(days_in_month-(7-day_of_week)); a--)
sum+=array[a];
printf("sum of last row is %d\n", sum);
return 0;
}

You have
for (a=days_in_month; a>=(days_in_month-(7-day_of_week)); a--)
but day_of_week does not remain constant in your program and changes before with this statement:
day_of_week++;
Use a second variable to increment and do not modify day_of_week after scanf.

One problem is here:
for (i=1; i<=days_in_month; i++) {
printf("%3d", i);
array[i] = i;
day_of_week++;
if (day_of_week%7==0){
printf("\n");
}
}
You are allowing day_of_week to go out of range. Your code expects that value to be no more than 7. This loop will result in that variable being set to the value the user entered plus (days_in_month - 1). In your final for loop, the statement 7 - day_of_week will likely be negative, which will throw the rest of your code off.
You are sort of checking for overflow when you test the variable modulo 7 and print a newline. When you do that, set day_of_week = 0 as well.
Also, calculate (days_in_month-(7-day_of_week)) and store it in a temporary variable as soon as you get the input from the user. Since you're manipulating these variables inside your code, your final for loop probably isn't using the values that you think it's using. Alternatively, don't modify the variables that you use for user input and create other variables to use as temporaries.

Related

Understanding the arrays in C

I'm new to C and need some help to understand how this piece of code works. I know that it reads the values that the user writes, puts them into an array, and then prints them out.
But I don't understand why I need two "counters" (i and j) to do this. Can someone help me to figure it out?
#include<stdio.h>
int main ()
{
int A[5];
int i=0;
int j=0;
while (i < 5)
i++;
printf("Enter your %d number\n", i);
scanf("%d", &A[i]);
}
while (j < 5)
{
j++;
printf ("\n%d\n", A[j]);
}
}
Technically, what you have aren't two counters, but two loops. If you wanted, to, you could just reuse i for the second loop as well, by doing something like this:
while (i < 5)
i++;
printf("Enter your %d number\n", i);
scanf("%d", &A[i]);
}
i = 0;
while (i < 5)
{
i++;
printf ("\n%d\n", A[i]);
}
As for why you have two loops, the reason is simple. The first loop (using i in your code), reads the 5 integers into the array A. After the first loop concludes, your array A holds the 5 int values, which you could've used however you wanted. In your case, you want to print those values. So what you do is use a loop for looping over the array elements and printing the values to the screen, one by one.
You don't need it, you can simply reset the first and reuse it. However you must increment your index only after having using it otherwise you will overflow the limit of the array :
#include<stdio.h>
int main ()
{
int A[5];
int i=0;
while (i < 5) {
printf("Enter your %d number\n", i);
scanf("%d", &A[i]); // the last must be 4 not 5
i++; //<== increment here
}
i=0;
while (i < 5)
{
printf ("\n%d\n", A[i]); //idem
i++;
}
}

Passing struct array to function and calculating average in C?

Beginner here, I've been trying this for hours and can't get it to work, searched online too and couldn't find an answer.
I'm trying to write a program where you input people by putting their age and height then calculate the average of each, and the average ratio of age to height. Whenever I pass the struct to my getAverage function, it returns the address (I think) instead of the averages.
#include <stdio.h>
#include <stdlib.h>
typedef struct person
{
int age;
double height;
} Person;
double getAv (Person people[50], int max)
{
int i;
double total, retval;
total = 0;
for (i=0; i<=max; i++)
{
total = total + people[i].age;
}
retval = total / max;
return retval;
}
int main (void)
{
Person people[50];
int i;
while (i++, people[i].age>=0)
{
printf ("Person #%d\n", i);
printf ("enter an age: ");
scanf ("%d", &people[i].age);
if (people[i].age<0)
break;
printf ("enter a height: ");
scanf ("%lf", &people[i].height);
printf ("\n");
}
double averageAge;
averageAge = getAv (&people[50], i);
printf ("%.1lf\n", averageAge);
}
Haven't implemented average height or ratio yet, just trying to get average of ages to work for now. When I try taking the & out of averageAge = getAv(&people[50], I); I get a compile error that tells me it needs the &. Any help would be appreciated.
There are serveral issues in you code, the first one:
Person people[50];
int i;
while (i++, people[i].age>=0)
You are using i uninitialized, thus, incrementing a variable containing garbage (or 0 as intended, but it is impossible to guarantee)
To avoid such problems in the future enable warnings on your compiler, the compiler would have told you something like:
ā€˜iā€™ is used uninitialized in this function [-Wuninitialized]
So switch to
Person people[50] = {0};
int i = 0;
It seems (based on the pre-increment operator ++i) that you want to use arrays with base 1, there is nothing wrong with that, but in your average function you are starting from 0, so use a for:
for (i = 0; ; i++)
{
...
if (people[i].age <= 0) break;
...
}
Another issue:
double averageAge;
averageAge = getAv (&people[50], i);
In this way you are passing only element 50 which is not part of your array (remember arrays are base 0 in C), to pass the entire array:
averageAge = getAv (people, i);
or
averageAge = getAv (&people[0], i);
The last one:
for (i=0; i<=max; i++)
You are including the element discarded when you was checking for age > 0, switch to:
for (i=0; i<max; i++)
A minor issue:
Iif the user enters 0 for the first element of people you end up dividing by 0
double averageAge;
averageAge = getAv (&people[50], i);
printf ("%.1lf\n", averageAge);
should be
if (i > 0)
{
double averageAge;
averageAge = getAv (people, i);
printf ("%.1f\n", averageAge); // No need to use lf (long double)
}
If you do it this way, you need to receive in your function (Person& people[], int n)
Where n is the length of the array.
We use the '&' to not do copies of the array and also you are passing only the element with index 50 in the function, simply do only (people, n)
there are mistakes in this code ,first you should initialize int i to int i=0 in mian function.
how are using this condition while (i++, people[i].age>=0) when you haven't scanned any input it's like using an uninitialized variable. you need a do-while like this
do
{
printf("Person #%d\n", i);
printf("enter an age: ");
scanf("%d", &people[i].age);
if (people[i].age < 0)
break;
printf("enter a height: ");
scanf("%lf", &people[i].height);
printf("\n");
i++;
} while (people[i-1].age >= 0);
also you are sending wrong arguments to your getAv function you should use averageAge = getAv (people, i);.
and in your function you have to remove = in this loop for (i=0; i<=max; i++) .this should be for (i=0; i<max; i++) ,otherwise the negative entered age will also be add to total and will affect the average.

I'm trying to get the counter to work, how many months have a higher income than the same month from last year

The line of code I'm having trouble with has to do with counting a number of months, I'm passing a value up from a function that I thought would work but I'm not getting a proper readout from it. I'm sure I'm missing something stupid or the mistake I made is very basic but I can't seem to get it right. I would greatly appreciate any help I can get. please excuse the many printf statements, I was trying to find where the error was.
#include <stdio.h>
#include <stdlib.h>
void DisplayInstructions();//function 1
void HigherSales(float yearOne, float yearTwo, int k);//fuction 2
int months (float yearOne, float yearTwo);//function 3
void main()
{
float yearOne[12];//variables
float yearTwo[12];
int i = 0;
int j = 0;
int k = 0;
int count = 0;
DisplayInstructions();//calling first function
printf(" \n");
for (i = 0; i<12; i++)//scanf for entering sales values
{
j= i+1;
printf("enter the sales figures for month %d in year one \n",j);
scanf_s("%f",&yearOne[i]);
}
for (i = 0; i<12; i++)
{
j= i+1;
printf("enter the sales figures for month %d in year two \n",j);
scanf_s("%f",&yearTwo[i]);
} //end of entering sales
k=0;
for (i = 0; i<12; i++)//populating function 2
{
k++;
HigherSales(yearOne[i], yearTwo[i], k);
}
printf("\n count before going into the for loop is %d \n",count);
for (i = 0; i<12; i++)
{
months(yearOne[i], yearTwo[i]);//populating function 3
printf("before going into count calculation months is reading %f",months(yearOne[12], yearTwo[12]));
count = count + months(yearOne[12], yearTwo[12]); //calling function 3 so that i get the sum of times y1 < y2
printf(" \n after calc count is %d \n after calc monts is returning %f", count, months(yearOne[12], yearTwo[12]));
}
printf(" \n the number of months in year two where sales have increased is %d \n", count);
system("pause");
}
void DisplayInstructions() //function 1 printf's
{
printf("\n");
printf("this program consists of one function called 'DisplayInstructions' \n");
printf("the function takes no arguments and simply dispays this message \n");
printf("it is innitalised above main, called inside main and described below main \n");
}
void HigherSales(float yOne, float yTwo, int g)
{
if(yOne < yTwo) //function 2 comparing logic
{
printf("month %d in year two had higher sales than the same month the year prior \n", g);
}
}
int months(float monthOne, float monthTwo)
{
int m = 0;
if(monthOne < monthTwo )
{
m = m + 1;
printf("\n in the mothhs function, m loop, m is %d \n", m);
return m;
}
}
The function int months(float monthOne, float monthTwo) does not work as you probably expect.
With int m = 0; the variable m always is initialized with 0 every time this function is called, therefore m = m + 1 won't count up how often the condition is true - its either 0 or 1
To make the function remember the value of m from its last call you need to declare it static int m = 0;
But in your case this wouldn't be the best idea either because you would only want to know the last return value (when all months are iterated).
Furthermore function months only has a return value if the condition is true - your compiler should have complained about that.
So if you want to make this simple comparison within a function which is called within a loop:
int months(float monthOne, float monthTwo)
{
if (monthOne < monthTwo)
return 1;
else
return 0;
}
for (i = 0; i<12; i++)
{
count += months(yearOne[i], yearTwo[i]);
}
In your context I cant figure out the purpose of count = count + months(yearOne[12], yearTwo[12]); - beside the fact that you are accessing the 13th element of your array which is invalid, it makes no sense to increment your counter by the same comparison every loop.
The modified code below addresses the errors I commented under your post as well as some others (see comments in code.) I automated inputs using rand() to speed up testing, but left all your original code. Comment out the auto populate sections for your purposes.
Note: Not all logic errors are addressed, but enough to get you started. Read the comments left in the code.:
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
void DisplayInstructions();//function 1
void HigherSales(float yearOne, float yearTwo, int k);//fuction 2
int months (float yearOne, float yearTwo);//function 3
const char month[][4] = {"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"};
void main()
{
float yearOne[12];//variables
float yearTwo[12];
int i = 0;
int j = 0;
int k = 0;
int count = 0;
srand(clock());//seed pseudo random number generator
DisplayInstructions();//calling first function
printf(" \n");
for (i = 0; i<12; i++)//scanf for entering sales values
{
j= i+1;
printf("enter the sales figures for month %d in year one \n",j);
yearOne[i] = rand();//Added to automate populating monthly sales numbers...
while(yearOne[i] < 500)
{
yearOne[i] = rand()%10000;//Added to automate populating monthly sales numbers...
Sleep(100);//pause execution for 0.1 seconds
}
printf("YearOne - %s: %lf\n", month[i], yearOne[i]);
//scanf("%f",&yearOne[i]);
}
for (i = 0; i<12; i++)
{
j= i+1;
printf("enter the sales figures for month %d in year two \n",j);
yearTwo[i] = rand();//Added to automate populating monthly sales numbers...
while(yearTwo[i] < 500)
{
yearOne[i] = rand()%10000;//Added to automate populating monthly sales numbers...
Sleep(100);//pause execution for 0.1 seconds
}
printf("YearTwo - %s: %lf\n", month[i], yearOne[i]);
//scanf("%f",&yearTwo[i]);
} //end of entering sales
k=0;
for (i = 0; i<12; i++)//populating function 2
{
k++;
HigherSales(yearOne[i], yearTwo[i], k);
}
printf("\n count before going into the for loop is %d \n",count);
for (i = 0; i<12; i++)
{ //Hint: In this for loop, you are calling months function more
//than you want to. Consider assigning a variable to read it's
//output, then use that variable in the printf statements.
months(yearOne[i], yearTwo[i]);//populating function 3
// printf("before going into count calculation months is reading %f",months(yearOne[i], yearTwo[i]));
printf("before going into count calculation months is reading %d",months(yearOne[i], yearTwo[i]));//changed format type to match variable type
count = count + months(yearOne[i], yearTwo[i]); //calling function 3 so that i get the sum of times y1 < y2
//printf(" \n after calc count is %d \n after calc monts is returning %f", count, months(yearOne[i], yearTwo[i]));
printf(" \n after calc count is %d \n after calc monts is returning %d", count, months(yearOne[i], yearTwo[i]));//changed format type to match variable type
}
printf(" \n the number of months in year two where sales have increased is %d \n", count);
// system("pause");
printf("hit any key to continue.");
getchar(); //this method is more idomatic and portable to pause code
}
void DisplayInstructions() //function 1 printf's
{
printf("\n");
printf("this program consists of one function called 'DisplayInstructions' \n");
printf("the function takes no arguments and simply dispays this message \n");
printf("it is innitalised above main, called inside main and described below main \n");
}
void HigherSales(float yOne, float yTwo, int g)
{
if(yOne < yTwo) //function 2 comparing logic
{
printf("month %d in year two had higher sales than the same month the year prior \n", g);
}
}
int months(float monthOne, float monthTwo)
{
static int m = 0;//use static here to allow m to keep value from call to call.
//static extends life of variable until program ends.
if(monthOne < monthTwo )
{
m = m + 1;
printf("\n in the mothhs function, m loop, m is %d \n", m);
}
return m;//moved from inside loop, otherwise return will not occur
//for some evaluations.
//Perhaps you would prefer an else statement
}

Can for loop change value of variables explicitly in c?

Why does the value of sum changes after for loop in the following code even after I have initialised it as 0 in CodeBlocks?
int main()
{
int a[5], i, sum;
sum= 0; // value of sum is not changed after this.
printf("\nSum=%d", sum);
for( i=1; i<6; i++)
{
printf("\n\nInput %d: ", i);
scanf("%d", &a[i]);
printf("Sum test=%d", sum);
}
printf("\n\nSum=%d", sum); // why does it changes?
return 0;
}
sum never changes because you never modify it.
Furthermore, you have undefined behavior because the loop index is off by one, so you make scanf() write beyond the end of the array arr, which might by coincidence be the location where sum is stored, this would explain why you get Sum=4, the value of the last input.
C arrays are 0 based: use this:
for (i = 0; i < 5; i++)
You must also include the required standard header files and test the return value of scanf() to avoid undefined behavior on invalid input.
Here is a corrected version:
#include <stdio.h>
int main() {
int a[5], i, sum;
sum = 0;
printf("Sum=%d\n", sum);
for (i = 0; i < 5; i++) {
printf("\nInput %d: ", i);
if (scanf("%d", &a[i]) != 1)
break;
sum += a[i];
printf("Sum test=%d\n", sum);
}
printf("\nSum=%d\n", sum);
return 0;
}
Because you are looping over 1 to 6! And rewrite the value of sum here. To avoid this, you should iterate over the scope of the array, from index 0 to 4.
You should be aware that as the memory of sum is adjacent to the allocated memory of the array such a thing is happened, and it is not a rule!
array index starts with 0 so arr[5] is not allocated and the value you entered is given to sum
if atlast you give it as input 6 then the sum value is 6

How to get the value of the last element of an array?

Observe the following code. I want to divide the amount by the value of the last element in the array. I have tried in the following way but it is not working. Can anyone tell me what is the proper way to do it?
#include<stdio.h>
int main()
{
int i, j, k, noteNumber, array[100], amount, result;
printf("Enter the number of the notes: \n");
scanf("%d", &noteNumber);
printf("Enter the value of %d notes: \n", noteNumber);
for(i = 0; i < noteNumber; i++){
scanf("%d", &array[i]);
}
printf("Enter the amount: \n");
scanf("%d", &amount);
i = j;
if(amount / array[j] == 0){
printf("Minimum %d number of is needed", (amount/array[j]));
printf("The value of each note is %d", array[j]);
}
}
As I can see
i = j;
is wrong as you're using the value of an uninitialized variable to assign to another. This does not make any sense and can lead to undefined behavior.
C arrays use 0-based indexing, so for an array of size n, the last index would be n-1.
That said, never use an unbound index for a statically defined array, always perform the bound checking before using the index.
If noteNumber is the size of the array, then the last Element will be
array[noteNumber - 1]
As far as I can see, j isn't even initialized?
You are having a line
i = j;
j is not even initialized so you are doing a mistake here , maybe what
you wanted was
j = i - 1
As i would have incremented to noteNumber in your for loop and array with number of elements n has last element index n-1 because index starts from 0 rather than 1.
So Proper Code Would Be
#include<stdio.h>
int main(){
int i, j, k, noteNumber, array[100], amount, result;
printf("Enter the number of the notes: \n");
scanf("%d", &noteNumber);
printf("Enter the value of %d notes: \n", noteNumber);
for(i = 0; i < noteNumber; i++){
scanf("%d", &array[i]);
}
printf("Enter the amount: \n");
scanf("%d", &amount);
j = i - 1; // Line Changed
if(amount / array[j] == 0){
printf("Minimum %d number of is needed", (amount/array[j]));
printf("The value of each note is %d", array[j]);
}
}

Resources