After inputting a specific time, my minutes and seconds start from 0. Can anyone point out the mistakes in my coding please?
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int main ()
{
int h=0,m=0,s=0,i;
system("cls");
printf("Please enter a time format in HH:MM:SS\n ");
scanf("%d%d%d",&h,&m,&s);
start:
for(h;h<24;h++)
{
for(m;m<60;m++)
{
for(s;s<60;s++)
{
system("cls");
printf("\n\n\n\t\t\t%d:%d:%d",h,m,s);
if(h<12){printf("AM");}
else {printf("PM"); }
for(double i=0;i<99999999;i++)
{i++;
i--;}
}
s=0;
}
m=0;
}
h=0;
goto start;
getch();
return 0;
}
If I input 22:23:32, it will show to start from 22:0:0.
The colon separators in your input are causing the scanf call to fail (after reading the h value), as they cannot be interpreted as integers (as expected by the %d format specifiers).
If you know that your time input will always have the two : characters separating the hours, minutes and seconds values, then you can include those in the format string you pass to scanf – which will then look for (and skip) exactly those characters between the integer inputs.
Also, you should get into the habit of always checking the return value of scanf, to see if it successfully read the required number of fields:
//...
int check = scanf("%d:%d:%d", &h, &m, &s);
if (check != 3) { // Failed to read three integers
printf("Invalid input!\n");
return 1;
}
//...
You want to fix your format string to match your input, and check the return value from scanf() to ensure you actually read the data you expected. You probably want to print h % 12 as you use AM/PM. I suggest you use sleep instead of the busy loop:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main () {
printf("Please enter a time format in HH:MM:SS\n ");
int h, m, s;
if(scanf("%d:%d:%d",&h,&m,&s) != 3) {
printf("scanf failed\n");
return 1;
}
for(;;) {
for(;h<24;h++) {
for(;m<60;m++) {
for(;s<60;s++) {
printf("\n\n\n\t\t\t%02d:%02d:%02d %s",
h % 12,m,s,h < 12 ? "AM" : "PM");
sleep(1);
}
s=0;
}
m=0;
}
h=0;
}
}
and example run:
Please enter a time format in HH:MM:SS
13:2:3
01:02:03 PM
01:02:04 PM
The next step would be to setup a timer at regular intervals as sleep() will skew when it's run sufficiently long. Use strptime() and strftie() if they are available to you.
With thanks to #AllanWind for the correct user input code, there's the following that doesn't have quite the same level of indent and has been adapted to a Windows environment.
#include <stdio.h>
#include <windows.h>
int main () {
printf( "Enter a time (format HH:MM:SS)\n ");
int h, m, s;
if( scanf( "%d:%d:%d", &h, &m, &s ) != 3 ) {
printf("scanf failed\n");
return 1;
}
for( int ds = ((h*60)+m)*60+s; ;ds = (ds+1)%(24*60*60) ) {
printf( "%02d:%02d:%02d\n", ds/(60*60), (ds/60)%60, ds%60 );
Sleep( 1000 ); // NB: Uppercase func name and time in mS...
}
return 0;
}
23:59:57
23:59:58
23:59:59
00:00:00
00:00:01
00:00:02
The program should give the processor some exercise through calculating the quotients and modulo remainders from 86400 seconds per day... With a tiny tweak to the hours value, the counter could be left to simply count up, up for the next 136 years (as an unsigned 4byte integer.)
Related
Made a digital clock using C program :
This is a simple digital clock i made and the issue i am having is that every time the time gets incremented the printf gets printed . Since i am on mac i cant use <conio.h> .
My expectation : I want the program to display a single printf and the increment happens in a single printf instead of new printf every time the time changes.
#include<stdio.h>
#include <unistd.h>
#include <stdlib.h >
int main()
{
int h, m , ;
int d=1;
printf("Enter the time : ");
scanf("%d%d%d", &h,&m,&s);
if(h>12 || m>60 || s>60){
printf("ERROR!!");
exit(0);
}
while(1){
s++;
if(s>59){
m++;
s=0;
}
if(m>59){
h++;
m=0;
}
if(h>12){
h=1;
}
printf("\n Clock ");
printf(" %02d:%02d:%02d",h, m ,s);
sleep(1);
}
return 0;
}
Update : I did change in printf and i got what i was looking for
Before update :
printf("\n Clock ");
fflush(stdout);
printf(" %02d:%02d:%02d\r", h,m,s);
printf("\r");
sleep(1);
After update :
printf("\r Clock %2u:%02u:%02u", h, m ,s);
fflush(stdout);
sleep(1);
}
You need more thorough error checking on the time entered (what if the user enters negative values, or minutes or seconds equal to 60); and to get the time to print on a single line, you need to replace the \n with a \r, and to flush stdout.
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int main(void)
{
unsigned h, m, s;
printf("Enter the time : ");
scanf("%u:%u:%u", &h,&m,&s);
if(h > 12 || h < 1 || m > 59 || m < 0 || s > 59 || s < 0) {
printf("ERROR!!");
exit(0);
}
while (1) {
if (++s > 59) {
s = 0;
if (++m > 59) {
m = 0;
if(++h > 12)
h = 1;
}
}
printf("\r Clock %2u:%02u:%02u", h, m ,s);
fflush(stdout);
sleep(1);
}
return 0;
}
To get a clock that is more robust and with more precise timing, based on your system's real-time clock, try this:
#include <stdio.h>
#include <time.h>
int main(void)
{
time_t now;
time_t last_now = -1;
struct tm *tod;
char outbuf[32];
while (1) {
now = time(NULL);
if (now != last_now) {
last_now = now;
tod = localtime(&now);
strftime(outbuf,sizeof outbuf,"%l:%M:%S %P",tod);
printf("\r Clock %s", outbuf);
fflush(stdout);
}
}
return 0;
}
Look at the man pages for time, localtime, and strftime to see how this works, but basically it gets the time from the system clock, and if it has changed since the last time it was printed, format it and print it.
#include <stdio.h>
int main(int argc, char** argv)
{
int n;
int numbers;
int i=0;
int sum=0;
double average;
printf("\nPlease Enter the elements one by one\n");
while(i<n)
{
scanf("%d",&numbers);
sum = sum +numbers;
i++;
}
average = sum/n;
printf("\nSum of the %d Numbers = %d",n, sum);
printf("\nAverage of the %d Numbers = %.2f",n, average);
return 0;
}
i get the output "exited, floating point exception"
im not sure how to fix it.
i found online to add before the while loop
printf("\nPlease Enter How many Number you want?\n");
scanf("%d",&n);
but i dont want that there
Hint: you want the user to be able to signal to your application that they finished entering the elements. So you'd start with n=0 and then increment it each time the user provides a new element, and exit the loop when the user does "something" that you can detect.
For starters, let's say that the user closes the input by pressing Ctrl-Z on Windows, or Ctrl-D on Unix. The input will fail with EOF then - scanf() won't return 1 anymore. So you can check for this:
#include <stdio.h>
int main(int argc, char** argv)
{
int n = 0;
int sum = 0;
printf("\nPlease Enter the elements one by one. ");
#ifdef _WIN32
printf("Press Ctrl-Z to finish.\n");
#else
printf("Press Ctrl-D to finish.\n");
#endif
for (;;)
{
int number;
int result = scanf("%d", &number);
if (result == 1) break;
sum = sum + number;
n ++;
}
double average = (double)sum / n;
printf("\nSum of %d number(s) = %d\n",n, sum);
printf("Average of %d number(s) = %.2f\n",n, average);
return 0;
}
But this also ends the input when anything non-numeric is entered. Due to how scanf() is designed, you need to do something else to skip invalid input - usually by consuming input character-by-character until an end of line is reached. Thus, the variant that would not stop with invalid input, but allow the user another chance, needs to differentiate between scanf() returning EOF vs it returning 0 (invalid input):
#include <stdio.h>
void skip_input_till_next_line(void)
{
for (;;) {
char c;
if (scanf("%c", &c) != 1) break;
if (c == '\n') break;
}
}
int main(int argc, char** argv)
{
int n = 0;
int sum = 0;
printf("\nPlease Enter the elements one by one. ");
#ifdef _WIN32
printf("Press Ctrl-Z to finish.\n");
#else
printf("Press Ctrl-D to finish.\n");
#endif
for (;;)
{
int number;
int result = scanf(" %d", &number);
if (result == EOF) break;
if (result != 1) {
// We've got something that is not a number
fprintf(stderr, "Invalid input. Please try again.\n");
skip_input_till_next_line();
continue;
}
sum = sum + number;
n ++;
}
double average = (double)sum / n;
printf("\nSum of %d number(s) = %d\n",n, sum);
printf("Average of %d number(s) = %.2f\n",n, average);
return 0;
}
As a learner I'd recommend you to think about the pseudo code rather than the actual code.
Answers above are really good. I just want to add few things:
As a programmer you've to teach the hardware what you want it to do. Think:
Have you told your program how many numbers it takes as input? Is it limited or unlimited?
How will your program knows when to stop taking inputs?
I hope you agree that (sum n)/n would throw an error if user
doesn't enter anything or only enters 0?
What will happen if User enters characters instead?
Another important thing is that you need to clearly specify why you don't want to do certain thing in your code? This might help us understand better what are the limitations.
If you think about these things before and ask questions you'll learn better. Community is here to help you.
I tried going beyond just guessing random numbers. The conditions were these:
use input() numbers used from 1 to100 and if inserted numbers that are out of this range, to show a line to re-enter a number
use output() to show the output(but show the last line```You got it right on your Nth try!" on the main())
make the inserted number keep showing on the next line.
Basically, the program should be made to show like this :
insert a number : 70
bigger than 0 smaller than 70.
insert a number : 35
bigger than 35 smaller than 70.
insert a number : 55
bigger than 55 smaller than 70.
insert a number : 60
bigger than 55 smaller than 60.
insert a number : 57
You got it right on your 5th try!
I've been working on this already for 6 hours now...(since I'm a beginner)... and thankfully I've been able to manage to get the basic structure so that the program would at least be able to show whether the number is bigger than the inserted number of smaller than the inserted number.
The problem is, I am unable to get the numbers to be keep showing on the line. For example, I can't the inserted number 70 keep showing on smaller than 70.
Also, I am unable to find out how to get the number of how many tries have been made. I first tried to put it in the input() as count = 0 ... count++; but failed in the output. Then I tried to put in in the output(), but the output wouldn't return the count so I failed again.
I hope to get advice on this problem.
The following is the code that I wrote that has no errors, but problems in that it doesn't match the conditions of the final outcome.
(By the way, I'm currently using Visual Studio 2017 which is why there is a line of #pragma warning (disable : 4996), and myflush instead of fflush.)
#include <stdlib.h>
#include <time.h>
#include <stdio.h>
#pragma warning (disable : 4996)
int input();
int random(int);
void myflush();
void output(int, int);
int main()
{
int num;
int i;
int ran;
srand((unsigned int)time(NULL));
i = 0;
while (i < 1) {
ran = 1 + random(101);
++i;
}
num = input();
output(ran, num);
printf("You got it right on your th try!");a
return 0;
}
int input()
{
int num;
printf("insert a number : ");
scanf("%d", &num);
while (num < 1 || num > 100 || getchar() != '\n') {
myflush();
printf("insert a number : ");
scanf("%d", &num);
}
return num;
}
int random(int n)
{
int res;
res = rand() % n;
return res;
}
void myflush()
{
while (getchar() != '\n') {
;
}
return;
}
void output(int ran, int num) {
while (1) {
if (num != ran){
if (num < ran) {
printf("bigger than %d \n", num); //
}
else if (num > ran) {
printf("smaller than %d.\n", num);
}
printf("insert a number : ");
scanf("%d", &num);
}
else {
break;
}
}
return;
}
There are many problem and possible simplifications in this code.
use fgets to read a line then scanf the line content. This avoids the need of myflush which doesn’t work properly.
the function random is not needed since picking a random number is a simple expression.
if the range of the random number is [1,100], you should use 1+rand()%100.
there is no real need for the function output since it’s the core of the main program. The input function is however good to keep to encapsulate input.
you should test the return value of scanf because the input may not always contain a number.
Here is a simplified code that provides the desired output.
#include <stdlib.h>
#include <time.h>
#include <stdio.h>
#pragma warning (disable : 4996)
int input() {
char line[100];
int num, nVal;
printf("insert a number : ");
fgets(line, sizeof line, stdin);
nVal = sscanf(line, "%d", &num);
while (nVal != 1 || num < 1 || num > 100) {
printf("insert a number : ");
fgets(line, sizeof line, stdin);
nVal = sscanf(line, "%d", &num);
}
return num;
}
int main()
{
int cnt = 0, lowerLimit = 0, upperLimit = 101;
srand((unsigned int)time(NULL));
// pick a random number in the range [1,100]
int ran = 1 + rand()%100;
while(1) {
cnt++;
int num = input();
if (num == ran)
break;
if (num > lowerLimit && num < upperLimit) {
if (num < ran)
lowerLimit = num;
else
upperLimit = num;
}
printf("bigger than %d and smaller than %d\n", lowerLimit, upperLimit);
}
printf("You got it right on your %dth try!\n", cnt);
return 0;
}
I am unable to find out how to get the number of how many tries have been made.
Change the output function from void to int so it can return a value for count, and note comments for other changes:
int output(int ran, int num) {//changed from void to int
int count = 0;//create a variable to track tries
while (1) {
if (num != ran){
count++;//increment tries here and...
if (num < ran) {
printf("bigger than %d \n", num); //
}
else if (num > ran) {
printf("smaller than %d.\n", num);
}
printf("insert a number : ");
scanf("%d", &num);
}
else {
count++;//... here
break;
}
}
return count;//return value for accumulated tries
}
Then in main:
//declare count
int count = 0;
...
count = output(ran, num);
printf("You got it right on your %dth try!", count);
With these modifications, your code ran as you described above.
(However, th doesn't work so well though for the 1st, 2nd or 3rd tries)
If you want the program to always display the highest entered number that is lower than the random number ("bigger than") and the lowest entered number that is higher then the random number ("smaller than"), then your program must remember these two numbers so it can update and print them as necessary.
In the function main, you could declare the following two ints:
int bigger_than, smaller_than;
These variables must go into the function main, because these numbers must be remembered for the entire duration of the program. The function main is the only function which runs for the entire program, all other functions only run for a short time. An alternative would be to declare these two variables as global. However, that is considered bad programming style.
These variables will of course have to be updated when the user enters a new number.
These two ints would have to be passed to the function output every time it is called, increasing the number of parameters of this function from 2 to 4.
If you want a counter to count the number of numbers entered, you will also have to remember this value in the function main (or as a global variable) and pass it to the function output. This will increase the number of parameters for the function to 5.
If you don't want to pass so many parameters to output, you could merge the contents of the functions output and input into the function main.
However, either way, you will have to move most of the "smaller than" and "bigger than" logic from the function output into the function main, because that logic is required for changing the new "bigger_than" and "smaller_than" int variables which belong to the function main. The function output should only contain the actual printing logic.
Although it is technically possible to change these two variables that belong to the function main from inside the function output, I don't recommend it, because that would get messy. It would require you to pass several pointers to the function output, which would allow that function to change the variables that belong to the function main.
I have now written my own solution and I found that it is much easier to write by merging the function output into main. I also merged all the other functions into main, but that wasn't as important as merging the function output.
Here is my code:
#include <stdlib.h>
#include <time.h>
#include <stdio.h>
#pragma warning (disable : 4996)
int main()
{
const char *ordinals[4] = { "st", "nd", "rd", "th" };
int num_tries = 0;
int bigger_than = 0, smaller_than = 101;
int input_num;
int random_num;
srand( (unsigned int)time( NULL ) );
random_num = 1 + rand() % 101;
for (;;) //infinite loop, equivalent to while(1)
{
printf( "Bigger than: %d, Smaller than: %d\n", bigger_than, smaller_than );
printf( "enter a number: " );
scanf( "%d", &input_num );
printf( "You entered: %d\n", input_num );
num_tries++;
if ( input_num == random_num ) break;
if ( input_num < random_num )
{
if ( bigger_than < input_num )
{
bigger_than = input_num;
}
}
else
{
if ( smaller_than > input_num )
{
smaller_than = input_num;
}
}
}
printf( "You got it right on your %d%s try!", num_tries, ordinals[num_tries<3?num_tries:3] );
return 0;
}
Also, I made sure that the program would print "1st", "2nd" and "3rd", whereas all the other solutions simply print "1th", "2th", "3th". I used the c++ conditional operator for this.
I've trying to do it for about an hour, but I can't seem to get it right. How is it done?
The code I have at the moment is:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(){
int j=-1;
while(j<0){
printf("Enter a number: \n");
scanf("%d", &j);
}
int i=j;
for(i=j; i<=100; i++){
printf("%d \n", i);
}
return 0;
}
The original specification (before code was added) was a little vague but, in terms of the process to follow, that's irrelevant. Let's assume they're as follows:
get two numbers from the user.
if their product is greater than a thousand, print it and stop.
otherwise, print product and go back to first bullet point.
(if that's not quite what you're after, the process is still the same, you just have to adjust the individual steps).
Translating that in to pseudo-code is often a first good step when developing. That would give you something like:
def program:
set product to -1
while product <= 1000:
print prompt asking for numbers
get num1 and num2 from user
set product to num1 * num2
print product
print "target reached"
From that point, it's a matter of converting the pseudo-code into a formal computer language, which is generally close to a one-to-one mapping operation.
A good first attempt would be along the lines of:
#include <stdio.h>
int main (void) {
int num1, num2, product = -1;
while (product < 1000) {
printf ("Please enter two whole numbers, separated by a space: ");
scanf ("%d %d", &num1, &num2);
product = num1 * num2;
printf ("Product is %d\n", product);
}
puts ("Target reached");
return 0;
}
although there will no doubt be problems with this since it doesn't robustly handle invalid input. However, at the level you're operating, it would be a good start.
In terms of the code you've supplied (which probably should have been in the original question, though I've added it now):
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(){
int j=-1;
while(j<0){
printf("Enter a number: \n");
scanf("%d", &j);
}
int i=j;
for(i=j; i<=100; i++){
printf("%d \n", i);
}
return 0;
}
a better way to do the final loop would be along the lines of:
int i = 1;
while (i < 1000) {
i = i * j;
printf ("%n\n", i);
}
This uses the correct terminating condition of the multiplied number being a thousand or more rather than what you had, a fixed number of multiplications.
You may also want to catch the possibility that the user enters one, which would result in an infinite loop.
A (relatively) professional program to do this would be similar to:
#include <stdio.h>
int main (void) {
// Get starting point, two or more.
int start = 0;
while (start < 2) {
printf("Enter a number greater than one: ");
if (scanf("%d", &start) != 1) {
// No integer available, clear to end of input line.
for (int ch = 0; ch != '\n'; ch = getchar());
}
}
// Start with one, continue while less than a thousand.
int curr = 1;
while (curr < 1000) {
// Multiply then print.
curr *= start;
printf ("%d\n", curr);
}
return 0;
}
This has the following features:
more suitable variable names.
detection and repair of most invalid input.
comments.
That code is included just as an educational example showing how to do a reasonably good job. If you use it as-is for your classwork, don't be surprised if your educators fail you for plagiarism. I'm pretty certain most of them would be using web-search tools to detect that sort of stuff.
I'm not 100% clear on what you are asking for so I'm assuming the following that you want to get user to keep on entering numbers (I've assumed positive integers) until the all of them multiplied together is greater than or equal to 1000).
The code here starts with the value 1 (because starting with 0 will mean it will never get to anything other than 0) and multiples positive integers to it while the product of all of them remains under 1000. Finally it prints the total (which may be over 1000) and also the number of values entered by the user.
I hope this helps.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char input[10];
unsigned currentTotal = 1;
unsigned value;
unsigned numEntered = 0;
while( currentTotal < 1000 )
{
printf( "Enter a number: \n" );
fgets( input, sizeof(input), stdin );
value = atoi( input );
if( value > 0 )
{
currentTotal *= value;
numEntered += 1;
}
else
{
printf( "Please enter a positive integer value\n" );
}
}
printf( "You entered %u numbers which when multiplied together equal %u\n", numEntered, currentTotal );
return 0;
}
Try this one:
#include <stdio.h>
int main()
{
int input,output=1;
while(1)
{
scanf("%d",&input);
if(input<=0)
printf("Please enter a positive integer not less than 1 :\n");
else if(input>0)
output*=input;
if(output>1000)
{
printf("\nThe result is: %d",output);
break;
}
}
return 0;
}
I'm in a beginner C course and I was wondering if there's a way to input integers straight across and averages them together? I'm trying to make my program nice and tidy as possible.
I want to input integers straight across like:
Enter the temperatures and Enter 00 when finished:
60 80 97 42
Average is: 69.75
I don't want to input integers like shown below:
Enter the temperatures and Enter 00 when finished: 75
Enter the temperatures and Enter 00 when finished: 80
Enter the temperatures and Enter 00 when finished: 46
Enter the temperatures and Enter 00 when finished: 91
Average is: 73
#include <stdio.h>
#include <string.h>
int main(void){
char input[64];
double ave = 0.0, value;
int count = 0;
printf("Enter the temperatures and Enter 00 when finished:\n");
while(1){
if(1==scanf("%63s", input)){
if(strcmp(input, "00") == 0)
break;
if(1==sscanf(input, "%lf", &value))
ave += (value - ave) / ++count;
}
}
if(count)
printf("Average is: %g\n", ave);
else
printf("Input one or more values\n");
return 0;
}
Using the scanf function any white space character is seen as the end of input for each integer. Thus using scanf within a loop you can continuously input values within the same line.
If you want it to work for a different number of entries each time you must modify the code to use a while loop and have a dynamically allocated array, since the size is unknown. Then check for an escape sequence like 00.
All the values are stored into an array where you can do the averaging calculations
#include <stdio.h>
#define NUM_OF_ENTRIES 5
int main()
{
printf("Enter numbers: ");
int i = 0;
int value_set[NUM_OF_ENTRIES];
for (i = 0; i < NUM_OF_ENTRIES; i++ )
{
scanf("%d", &value_set[i]);
}
I believe that you shall change your terminating condition from enter 00 to something like enter x.
So, your code shall look like this::
int n;
int sum = 0, count = 0;
while(scanf("%d", &n)) {
sum = sum + n;
count++;
}
printf("%lf", double(sum/count));
scanf returns the number of successfully taken inputs. Since n is declared as int, so everytime you enter some integer value, scanf will return 1 and if you enter some value which is not of type int like if you enter x (which is a char) scanf will return 0, because x is not an integer, and this way you can calculate the average.
Code can use scanf("%d", &number) to read an integer. The trouble is that "%d" first scans and discards leading white-space which includes '\n' before scanning for an int. '\n' is needed to know when to stop as OP wants "input integers straight across". So instead code should look for white-space one character at a time first. Upon finding the end-of-line '\n', scanning is complete.
With this approach there are no practical limits to the count of numbers.
#include <ctype.h>
#include <stdio.h>
double Line_Average(void) {
double sum = 0;
unsigned long long count = 0;
while (1) {
int ch;
while (isspace(ch = fgetc(stdin)) && ch != '\n')
;
if (ch == '\n' || ch == EOF) {
break; // End-of-line or End-if file detected.
}
ungetc(ch, stdin); // Put back character for subsequent `scanf()`
int data;
if (scanf("%d", &data) != 1) {
break; // Bad data
}
sum += data;
count++;
}
return sum/count;
}
// sample usage
puts("Enter the temperatures");
double Average = Line_Average();
printf("Average is: %.2f\n", Average);
One possibility:
double sum = 0;
double val;
size_t count = 0;
char follow;
while( scanf( "%lf%c", &val, &follow ) == 2 )
{
sum += val;
count++;
if ( follow == '\n' )
break;
}
printf( "average = %f\n", sum/count );
This will read each number plus the character immediately following, until it sees a newline or a non-numeric string. It's not perfect; if you type a number followed by a space followed by a newline, then it won't break the loop. But it should give you some ideas.
since u did not post the code. i have given a sample code... from here u can build what u require with some tweaks
#include<stdio.h>
main()
{
int one, two, thr, four, five, avg;
printf("\nEnter the temperatures and Enter 00 when finished:");
scanf ("%d %d %d %d %d", &one, &two, &thr, &four, &five);
avg=(one+two+thr+four+five)/5;
printf("Average value is %d", avg);
}