C program \n and while loop - c

guys I have a C program question. My goal is to make a change operation working for taking a price and giving out the current amount remaining. I code in java, so this is my first time in C, Im not looking to have my entire code done for me. I can do the code, however im having trouble getting it to execute the way I want. My problem here is that when I use \n my code seems to work, but my output is really weird, i have to add constant spaces and repeat my lines. not sure why this is happening, Also my while loop does not seem to execute, which is making no sense to me. If anyone could help , I would apprectiate it. Thank you for reading, ps I reply isntantly
/******************************************************************************
Online C Compiler.
Code, Compile, Run and Debug C program online.
Write your code in this editor and press "Run" button to compile and execute it.
*******************************************************************************/
/* Header comment that describes the purpose of the program
* Name Karanvir Dhillon
* Date Jan 12
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main (void) {
double tendered;
double changeDue;
double price;
int hundred=0;
int twenty=0;
int ten=0;
int five=0;
int toonoe=0;
int loonie=0;
int quarter=0;
int dime=0;
int nickle=0;
int penny=0;
/* Statements to be executed */
printf("Total purchase price and tendered amount\n");
scanf("%lf %lf ", &price, &tendered);
printf(" %lf and %lf is \n", tendered,price);
changeDue=tendered-price;
printf("%lf \n", changeDue);
if(tendered<price){
printf("Not enough money recieved as payment \n");
}
if(tendered==price){
printf("Exact payment, no change given \n");
}
if(tendered>price){
printf("%lf Amount to be paid is \n", changeDue);
}
while(changeDue!=0.00){
if(changeDue<=100.00){
changeDue=changeDue-100.00;
hundred=hundred+1;
}
if(changeDue<=20.00){
changeDue=changeDue-20.00;
twenty=twenty+1;
}
if(changeDue<=10){
changeDue=changeDue-10.00;
ten=ten+1;
}
if(changeDue<=5){
changeDue=changeDue-5.00;
five=five+1;
}
if(changeDue<=2){
changeDue=changeDue-2.00;
toonoe=toonoe+1;
}
if(changeDue<=1){
changeDue=changeDue-1.00;
loonie=loonie+1;
}
if(changeDue>1){
for(int i=0;i<changeDue;i++){
if(i==0.25&&changeDue>=0.25){
changeDue=changeDue-0.25;
quarter=quarter+1;
}
if(i==0.10&&changeDue>=0.10){
changeDue=changeDue-0.10;
dime=dime+1;
}
if(i==0.05&&changeDue>=0.05){
changeDue=changeDue-0.05;
nickle=nickle+1;
}
if(i==0.01&&changeDue<0.05){
changeDue=changeDue-0.01;
penny=penny+1;
}
}
}
}
if(hundred!=0){
printf("%d hundred$ bills given as change \n",hundred);
}
if(twenty!=0){
printf("%d twenty$ bills given as change \n",twenty);
}
if(ten!=0){
printf("%d ten$ bills given as change \n",ten);
}
if(five!=0){
printf("%d five$ bills given as change \n",five);
}
if(toonoe!=0){
printf("%d toonie coins given as change \n",toonoe);
}
if(loonie!=0){
printf("%d loonie coins given as change \n",loonie);
}
if(quarter!=0){
printf("%d quarter coins given as change \n",quarter);
}
if(dime!=0){
printf("%d dime coins given as change \n",dime);
}
if(nickle!=0){
printf("%d nicke coins given as change \n",nickle);
}
if(penny!=0){
printf("%d penny coins given as change \n",penny);
}
return 0;
}

In most C compilers, including ours, the newline escape sequence '\n' yields an ASCII line feed character. The C escape sequence for a carriage return is '\r'.
Include a '\r' along with (or perhaps instead of) the '\n' in output strings. For example:
printf("Hello world\r\n");

Related

Why my c program only produce zero answer while using for loop?

I tried to use for loop calculate the number of books keyed in and sum up their total price, but at the end i only get zero price in C program. What is my problem ? How to solve it?
#include<stdio.h>
int main(void)
{
int booknum;
float bookfee,bookgst,nogst,totfee,newfee,newfee_nogst;
bookgst=0.0;
nogst=0.0;
int cnt;
char code;
printf("Key in total books purchased >> ");
scanf("%d",&booknum);
for(cnt=1;cnt<=booknum;cnt++)
{
printf("\n\n");
printf("Key in price of the book >> ");
scanf("%f",&bookfee);
printf("Key in type( S=standard gst,Z=zero gst) \n>> ");
scanf("%c",&code);
getchar();
if(code=='S')
{
newfee=bookfee+0.6;
}
else if(code=='Z')
{
newfee_nogst=bookfee;
}
bookgst=bookgst+newfee;
nogst=nogst+newfee_nogst;
printf("\n");
}
totfee=bookgst+nogst;
printf("Book purchased with GST : RM %.2f\n",bookgst);
printf("Book purchased without GST : RM %.2f\n",nogst);
printf("Total payment : RM %.2f\n",totfee);
return 0;
}
There are a few problems with this code, but you're almost there!
First code reading needs to eat the previous \n (see this), otherwise the code is neither Z not S (it's a newline), and that's why the fees are never added.
(Search also for "fgets vs scanf" to see how to use the safer fgets).
scanf(" %c",&code);
then these lines
bookgst=bookgst+newfee;
nogst=nogst+newfee_nogst;
add the newfee / newfee_nogst ; these variables are set to 0 before the loop, but at the next occurence, they're still set to the value of the previous occurrence, thus either set them to 0 at the beginning of the loop, or, add the value directly in the if (see below). And since we're here, print an error if the code is wrong (and maybe subtract one to cnt to do one more loop with a correct code, in this case).
Also, the GST calculation is probably wrong, 6% of x is 0.06 * x, and if you want GST added to the value that's x * 1.06
if(code=='S')
{
bookgst = bookgst + bookfee*1.06; // or bookgst += bookfee*1.06
}
else if(code=='Z')
{
nogst = nogst + bookfee; // or nogst += bookfee
}
else {
printf("Code not understood\n");
}

Run time error C program

I'm trying to run a simple program involving large data sets and analyzing them. The program is quite simple and it gives no error in compilation. however while running it just stops working. I'm an amateur programmer with only basic C knowledge. I'm guessing here that somehow some datatype limit is being exceeded because of the large data. Any help is appreciated !
here's the code:
#include <stdio.h>
#include<math.h>
int main()
{
int i,n;
n=193704;
// original data set arrays
double xcor[193706],ycor[193706],zcor[193706],decibel[193706],frequency[193706],node[193706];
// new data set arrays
double xcor1[193706], ycor1[193706], zcor1[193706], decibel1[193706], frequency1[193706], node1[193706];
// equating all values of modified arrays to zero for future comparison
for(i=0;i<n;i++)
{
xcor1[i]=0;
ycor1[i]=0;
zcor1[i]=0;
decibel1[i]=0;
frequency1[i]=0;
node1[i]=0;
}
//FILE POINTERS DEFINED HERE
FILE *acdb, *freq, *nodes, *xcord, *ycord, *zcord, *hearfreq, *heardb, *hearx, *heary, *hearz ;
acdb=(fopen("acousticdb.txt","r"));
freq=(fopen("frequency.txt","r"));
nodes=(fopen("node.txt","r"));
xcord=(fopen("xcor.txt","r"));
ycord=(fopen("ycor.txt","r"));
zcord=(fopen("zcor.txt","r"));
hearfreq=(fopen("hearingrangefrequency.txt","w"));
heardb=(fopen("hearingrangedecibel.txt","w"));
hearx=(fopen("hearing-x.txt","w"));
heary=(fopen("hearing-y.txt","w"));
hearz=(fopen("hearing-z.txt","w"));
for(i=0;i<n;++i)
{
fscanf(acdb, "%lf", &decibel[i]);
fscanf(freq, "%lf", &frequency[i]);
fscanf(nodes, "%lf", &node[i]);
fscanf(xcord, "%lf", &xcor[i]);
fscanf(ycord, "%lf", &ycor[i]);
fscanf(zcord, "%lf", &zcor[i]);
}
fclose(acdb);
fclose(freq);
fclose(nodes);
fclose(xcord);
fclose(ycord);
fclose(zcord);
// checking frequecy within hearing range
for(i=0;i<n;i++)
{
if(frequency[i]<20000 && frequency[i]>20 )
{
xcor[i]=xcor1[i];
ycor[i]=ycor1[i];
zcor[i]=zcor1[i];
decibel[i]=decibel1[i];
frequency[i]=frequency1[i];
node[i]=node1[i];
}
}
//wiriting values in text file
for(i=0;i<n;i++)
{
fprintf(hearfreq," %lf \n", frequency1[i]);
fprintf(heardb," %lf \n", decibel1[i]);
fprintf(hearx," %lf \n", xcor1[i]);
fprintf(heary," %lf \n", ycor1[i]);
fprintf(hearz," %lf \n", zcor1[i]);
}
return 0;
}
You probably run out of stack space. But if I look at the code then there is no need to first read all the data into arrays: all calculations are on a single index (i) and so you can just read one data item from each file, check if they are within hearing frequency and write them out:
int main()
{
int i, n=193704;
// original data set arrays
double xcor,ycor,zcor,decibel,frequency,node;
// new data set arrays
double xcor1, ycor1, zcor1, decibel1, frequency1, node1;
//FILE POINTERS DEFINED HERE
FILE *acdb, *freq, *nodes, *xcord, *ycord, *zcord, *hearfreq, *heardb, *hearx, *heary, *hearz ;
acdb=(fopen("acousticdb.txt","r"));
freq=(fopen("frequency.txt","r"));
nodes=(fopen("node.txt","r"));
xcord=(fopen("xcor.txt","r"));
ycord=(fopen("ycor.txt","r"));
zcord=(fopen("zcor.txt","r"));
hearfreq=(fopen("hearingrangefrequency.txt","w"));
heardb=(fopen("hearingrangedecibel.txt","w"));
hearx=(fopen("hearing-x.txt","w"));
heary=(fopen("hearing-y.txt","w"));
hearz=(fopen("hearing-z.txt","w"));
for(i=0;i<n;++i)
{
fscanf(acdb, "%lf", &decibel);
fscanf(freq, "%lf", &frequency);
fscanf(nodes, "%lf", &node);
fscanf(xcord, "%lf", &xcor);
fscanf(ycord, "%lf", &ycor);
fscanf(zcord, "%lf", &zcor);
// checking frequecy within hearing range
if(frequency<20000 && frequency>20 )
{
xcor=xcor1;
ycor=ycor1;
zcor=zcor1;
decibel=decibel1;
frequency=frequency1;
node=node1;
}
else xcor1= ycor1= zcor1= decibel1= frequency1= node1= 0.0;
//wiriting values in text file
fprintf(hearfreq," %lf \n", frequency1);
fprintf(heardb," %lf \n", decibel1);
fprintf(hearx," %lf \n", xcor1);
fprintf(heary," %lf \n", ycor1);
fprintf(hearz," %lf \n", zcor1);
}
fclose(acdb);
fclose(freq);
fclose(nodes);
fclose(xcord);
fclose(ycord);
fclose(zcord);
// don't forget to close these
fclose(hearfreq);
fclose(heardb);
fclose(hearx);
fclose(heary);
fclose(hearz);
return 0;
}
If you declare arrays like this
double xcor1[193706];
without dynamic memory allocation using malloc() or similar, you are reserving that space on the stack. Considering you are doing more then 1 million double elements on your stack, it is probably overflowing. You have a literal stack overflow.
Quips aside, use dynamic memory allocation for such big arrays.
It works like this:
double* xcor1 = malloc(sizeof(double) * 193706) ;
And when you're all done with it, don't forget to free it, too.
free(xcor1);
Ofcourse, with your code, you can also just not use arrays alltogether and not save the data in between, and instead use single variables for your operations.

Printing only one combination using nested loops

I have to print combination of different currency notes a man should have to pay to the cashier. Program first ask total amount to be paid and then notes of different denominations that he possesses. The problem is, I have to print only one combination of currency notes, but I am getting all combinations (as usual) by the following code.
#include <stdio.h>
int main(void)
{
int hundred,fifty,ten,total,hund,fif,t;
printf ("Enter amount to be paid:");
scanf ("%d",&total);
printf ("\n\nHow many currency notes do you have?\nEnter 100,50 and 10 Rupee Notes Respectively:\n");
scanf ("%d %d %d",&hund,&fif,&t);
printf ("\t\t\tPossible combination for Rs=%d/- \n",total);
for (hundred=0; hundred<=hund; hundred++)
{
for (fifty=0; fifty<=fif; fifty++)
{
for (ten=0; ten<=t; ten++)
{
if ((hundred*100+fifty*50+ten*10)==total)
{
printf("\n\n Hundred rupees notes=%d, 50 rupees notes=%d, 10 rupees notes=%d",hundred,fifty,ten);
}
}
}
}
getch();
return 0;
}
Add a getch(); and return 0; just after the printf inside the nested loops.
Another way is to use goto. Type
goto exit;
Just after the printf inside the nested loops and type
exit:
Just before the getch();.

One Step from Happiness --all my inputs give correct output but still it says wrong answer

I'm trying to do Timus Online Judge question #1493, "One Step from Happiness":
Vova bought a ticket in a tram of the 13th route and counted the sums of the first three and the last three digits of the ticket's number (the number has six digits). It turned out that the sums differed by one exactly. "I'm one step from happiness," Vova thought, "either the previous or the next ticket is lucky." Is he right?
Input
The input contains the number of the ticket. The number consists of six digits, some of which can be zeros. It is guaranteed that Vova counted correctly, i.e., that the sum of the first three digits differs from the sum of the last three digits by one exactly.
Output
Output "Yes" if Vova is right and "No" otherwise.
Samples
input output
--------------------
715068 Yes
445219 No
012200 Yes
Hint
All tram tickets have exactly six digits. A ticket is considered lucky if the sum of its first three digits equals the sum of its last three digits.
Here is my code in Visual C(2010) format.
#include <stdio.h>
int main()
{
int arr[5],arr1[5],arr2[5],i,a=0,b=0,n,x=0,y=0;
printf("Enter number");
scanf("%d",&n);
x=n+1;
y=n-1;
while(n>0)
{
for(i=5;i>=0;i--)
{
arr[i]=n%10;
n=n/10;
}
}
a=( arr[0]+arr[1]+arr[2]);
b=(arr[3]+arr[4]+arr[5]);
if((a-b==1)||(a-b==-1))
{
while(x>0)
{
for(i=5;i>=0;i--)
{
arr1[i]=x%10;
x=x/10;
}
}
while(y>0)
{
for(i=5;i>=0;i--)
{
arr2[i]=y%10;
y=y/10;
}
}
if ((arr1[0]+arr1[1]+arr1[2]==arr1[3]+arr1[4]+arr1[5]) ||
(arr2[0]+arr2[1]+arr2[2]==arr2[3]+arr2[4]+arr2[5]))
{ printf("Yes");}
else
{ printf("No");}
}
else
{
printf("No");
}
return 0;
}
The above code is the one I submitted and received a wrong answer in Timus Online Judge. The format in which it was submitted was Visual C (2010). I use Dev-C++ on my computer, so the code I run on my computer is the following:
#include <stdio.h>
#include <conio.h>
main()
{
int arr[5],arr1[5],arr2[5],i,a=0,b=0,n,x=0,y=0;
printf("Enter number");
scanf("%d",&n);
x=n+1;
y=n-1;
while(n>0)
{
for(i=5;i>=0;i--)
{
arr[i]=n%10;
n=n/10;
}
}
a=( arr[0]+arr[1]+arr[2]);
b=(arr[3]+arr[4]+arr[5]);
if((a-b==1)||(a-b==-1))
{
while(x>0)
{
for(i=5;i>=0;i--)
{
arr1[i]=x%10;
x=x/10;
}
}
while(y>0)
{
for(i=5;i>=0;i--)
{
arr2[i]=y%10;
y=y/10;
}
}
if ((arr1[0]+arr1[1]+arr1[2]==arr1[3]+arr1[4]+arr1[5]) ||
(arr2[0]+arr2[1]+arr2[2]==arr2[3]+arr2[4]+arr2[5]))
{ printf("Yes");}
else
{ printf("No");}
}
else
{
printf("No");
}
getch();
}
I received no compilation errors. The code ran perfectly on my Dev-C++ compiler and also gave me correct output. The problem is when I submit this code in the Visual C format and they tell me it is a wrong answer.
The exercise states:
Output "Yes" if Vova is right and "No" otherwise.
Your program prints Enter number, which the exercise does not ask for. Try to remove that.
Also, for your own and our sanity, I strongly recommend you format your program better. Finding errors is much easier in a beautiful, well-formatted program. For tips on how to make your code more readable and clean, you can head over to CodeReview.SE.

My program crashes, and I don't understand why

I am coding a record-keeping program in C using binary file handling. I am using Code::Blocks, with gcc to compile my C program on Windows 8.
When the program reaches to the following block, an error-message appears:
My code:
int dispaly(student record[], int count)
{
/*
This is what structure `student` looks like:
int id;
char name[200], phone[20], address[200], cclass[50];
char sec[20], roll[50], guardian_name[200], relation[200] ;
char p2_colg[100], slc_school[200];
float plus2_percent, slc_percent;
struct date dob;
struct date enr_date;
struct date looks like
int day, month, year;
*/
printf("Reached"); /*Program Runs Fine upto here*/
int i = 0;
for(i=0; i<count; i++)
{
printf("\nId: %d\tPhone: %s\nName: %s\nAddress: %s"
"\nClass: %s\tSection: %s\nRoll: %s\nGuardian Name: %s\tRelation:%s"
"\nPlus-Two in: %s\tPercentage:%f\nSLC School: %s\tPercentage: %f"
"\nDate Of Birth(mm/dd/yyyy): %d/%d/%d"
"\nEnrolled in (mm/dd/yyyy): %d/%d/%d\n\n---------------------------------------\n", record[i].id, record[i].name, record[i].address
, record[i].cclass, record[i].sec, record[i].roll, record[i].guardian_name, record[i].relation, record[i].p2_colg
, record[i].plus2_percent, record[i].slc_school, record[i].slc_percent, record[i].dob.month, record[i].dob.day, record[i].dob.year
, record[i].enr_date.month, record[i].enr_date.day, record[i].enr_date.year);
}
getch();
return 0;
}
The program compiles without any errors or warnings.
What's going on?
Hard to tell exactly what crashed without looking at the exact data in your array, but you forgot "phone" in the arguments list to printf, which could certainly result in a crash inside printf.
There's not a terribly good reason to stack those all up into one call. It would have been easier to spot your bug of the missing "phone" if you separated each line out into its own printf. Also, you could cut down on the redundancy if you captured record[i] into a pointer.
Contrast with:
student * r = &record[i];
printf("\n");
printf("Id: %d\tPhone: %s\n", r->id, r->phone);
printf("Name: %s\n", r->name);
printf("Address: %s\n", r->address);
printf("Class: %s\tSection: %s\n", r->cclass, r->sec);
printf("Roll: %s\n", r->roll);
printf("Guardian Name: %s\tRelation:%s\n", r->guardian_name, r->relation);
printf("Plus-Two in: %s\tPercentage:%f\n", r->p2_colg, r->plus2_percent);
printf("SLC School: %s\tPercentage: %f\n", r->slc_school, r->slc_percent);
printf("Date Of Birth(mm/dd/yyyy): %d/%d/%d\n",
r->dob.month, r->dob.day, r->dob.year);
printf("Enrolled in (mm/dd/yyyy): %d/%d/%d\n"
r->enr_date.month, r->enr_date.day, r->enr_date.year);
printf("\n");
printf("---------------------------------------\n");
In a technical sense, making multiple calls to printf will incur some function call overhead. And declaring a pointer variable for the current student in the array will incur some storage space. But it is basically negligible, and of no consequence in a case like this. Under the hood, the output is buffered anyway.

Resources