Ask user to enter a random number between 1 and 100. Then ask how many numbers s/he wants to display that precedes first number s/he enters.
if user enter 9 and wants 3 numbers that precedes 9, your program should display this:
6 7 8 9
I can not finish it.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int endnum, pre;
printf("Enter a random number between 1 and 100: ");
scanf("%d", &endnum);
printf("how many numbers he wants to display that precedes first number you entered: ");
scanf("%d", &pre);
num = endnum - pre;
printf (%d, num+1)
num = num + 1
while (num <= endnum)
return 0;
}
You're pretty close. You've got pre and endnum. You just want to loop from pre to endnum (inclusive), and print out each of them.
You can use a while loop if you want to, but to me this situation lends itself more directly to a for loop. Something like:
for (num = endnum - pre; num <= endnum; ++num)
{
printf("%d ", num);
}
where num is pre-declared as a int.
That's not a bad first attempt, you just need to fix one slight logic problem and some minor syntax things.
As per my original pseudo-code from your previous question, you need to have a loop doing the printing. You also need semicolons for statement terminators, quotes around strings, and to print the correct value. So change:
printf (%d, num+1)
num = num + 1
while (num <= endnum)
into:
do {
printf ("%d ", num);
num = num + 1;
} while (num <= endnum);
In addition, you'll also need to define num the same way you've defined endnum and pre.
Related
Something is wrong. I'm trying to make a cade which can count number count of any natural number. Like number count of 2 is 1, 30 is 2, 456 is 3. My code is running for 1 digit numbers but not for two digit numbers.
#include<stdio.h>
void main(void)
{
int num,count,check;
float div;
printf("Enter a natural number\n");
scanf("%d", &num);
while (num<=0)
{
printf("Error\n");
printf("Enter a number\n");
scanf("%d", &num);
}
while(num>1)
{
count=1;
check=10;
div=num/check;
if(div<=1)
{
printf("Number count is\n%d", count);
break;
}
check = check*10;
count = count+1;
}
}
The problem with your solution is that after check and count are modified at the end of the loop, they are re-declared to 1 and 10 respectively at the beginning of the loop at every passage.
You need to move the declaration just before the while loop.
Also div doesn't need to be a float given that the decimal part of this number is irrelevant.
You could also use less variables by replacing check by 10 and
using num directly instead of temporarily storing results in div.
I think this might be a simpler solution
#include <stdio.h>
int main(){
int num = 0, digits = 0;
while (num <= 0)
{
printf("Enter a natural number\n");
scanf("%d", &num);
num == 0 ? printf("Error\n") : 0;
}
for( ; num > 0; digits++)
num /= 10;
printf("number of digits: %d\n", digits);
}
As num is continuously divided by 10, the decimal of the result gets truncated since num is an int while digits steadily increases.
It is time to learn to use a debugger. Using it would have immediately shown the major problem in your code: you reset the value of count and check inside the loop. So if you enter a number greater or equal to 10, you enter an infinite loop because you will consistently divide that number by 10 and find that the result is >= 1!
There is another less important problem: you use if(div<=1) when it should be if(div<1). Because 10/10 is 1 and has 2 digits...
After those fixes you should have:
...
check = 10;
count = 1;
while (num > 1)
{
div = num / check;
if (div < 1)
{
printf("Number count is\n%d", count);
break;
}
check = check * 10;
count = count + 1;
}
return 0; // main shall return an int value to its environment...
}
Which correctly gives the number of decimal digit on positive integers. But as you were said in comments, you should always test the return value of scanf (what is the user inadvertently types a t instead of 5 for example?).
That being said, this answer intends to show you what the problems were, but Keyne's solution is better...
I want to print a sequence of 1 4 9 16 25...n by inputting any number which is equal to the number of terms I want as an output.
For example: if I input 4, it should print 1 4 9 16
but I can't seem to get the result I want using this program I have made. The result goes like 0 1 4 9. I want to eliminate the first term zero, Can someone pls help me see what's wrong with my program?
int result,n;
for (int i = 1; i <= n; i++){
scanf("%d", &n);
printf("%d ", result);
result = pow(i,2);
}
#include <stdio.h>
int main()
{
int result, i, n;
printf("Input n: ");
scanf("%d", &n);
for(int i = 1; i <= n; i++)
{
result = i*i;
printf("%-3d", result);
}
}
OUTPUT: 1 4 9 16... n^2
Probably, you want this.
You should scan the value of n before the loop. Otherwise, the behavior of your program would be unpredictable. Second, it is wise to avoid floating-point calculations when possible and here you want to print the series of square of integers. i.e. 1,4,9,... so you shouldn't use
double pow(double a, double b)
function. Also as Fred said, "Calculate result before you print it."
I'm writing a c program for my intro class and I'm stuck on the if/else statements. we have to output the highest,lowest grade entered as well as the avg for those. Marks entered must be between 0-100. this is my code so far, i can't seem to figure it out, thanks for any advice! :
#include <stdio.h>
int main (void)
{
int numberofMarks;
int i;
int x;
int y;
int numofPasses=1;
int numofFails=1;
float sumpassedMarks =0;
float sumfailedMarks=0;
float markEntered=0;
float highestMark=0;
float lowestMark=0;
float totalMark=0;
float avgofMarks=0;
float avgpassedMarks=0;
float avgfailedMarks=0;
printf (" ---=== IPC mark Analyser ===---\n");
printf ("Please enter the number of marks(between 3 and 40): ");
scanf ("%d", &numberofMarks);
//asks user for number of marks, only takes 3-40, otherwise outputs error msg
for (i=1 ; (numberofMarks < 3)||(numberofMarks > 40) ; i++) {
printf ("Invalid number, enter a number between 3 and 40 inclusive: ");
scanf ("%d", &numberofMarks);
}
//for loop recieves the mark
for (x=1 ;(x <= numberofMarks) ; x++) {
printf ("%d> ", x);
scanf ("%f", &markEntered);
//contd loop..loop makes sure mark entered is between 1-100
for (y=1; (markEntered <0)||(markEntered>100); y++)
{
printf ("Error, Enter values between 0 and 100 incluisve.\n");
printf ("%d> ", x);
scanf ("%f", &markEntered);
if (markEntered >= 50) {
numofPasses=numofPasses+1;
}
if else (markEntered <= 49) {
numofFails = numofFails+1;
}
if else (markEntered > highestMark) {
highestMark = markEntered;
}
else (markEntered < lowestMark) {
lowestMark = markEntered;
}
}
//adds the mark entered to all the marks entered for a overall sum
totalMark = totalMark + markEntered;
}
avgofMarks = (float)totalMark / numberofMarks;
avgpassedMarks = (float)sumpassedMarks / numberofMarks;
avgfailedMarks = (float)sumfailedMarks / numberofMarks;
printf ("Total of %d students passed with an average of %.1f.\n", numofPasses,avgpassedMarks);
printf ("Total of %d students failed with an average of %.1f.\n", numofFails, avgfailedMarks);
printf ("Highest mark in the group: %.1f\n", highestMark);
printf ("lowest mark in the group: %.1f\n", lowestMark);
printf ("The average of all marks in this group is %.1f.\n", avgofMarks);
printf ("Program Ended.\n");
return 0;
}
The work asks,
In the loop in which marks are being entered, after each entry examine the value of the mark entered:
If it is a pass, add one to the number of passes and add the value of the mark to the sum of passed marks.
If it is a fail, add one to the number of fails and add the value of the mark to the sum of failed marks.
If the value is higher than the highest mark, set highest mark to the value read.
If the value is lower than the lowest mark, set the lowest mark to
the value read. After all the marks are entered and examined, divide
the sums by the corresponding number of marks to get the average and
print the results.
This is my output vs the sample output.
Your code is a mess; let's try to get some things straight here:
If you're not gonna use i in the body of a for loop, no reason to initialize and increment it. Better to use a while.
When you post a question, clear all not-strictly-necessary code from the answer, so that it's easier to help
Instead of making 15 variables, consider using an array or, if you're not gonna use the values later in the program, print the result directly.
Ex.
int a = 10, b = 15; If you wanna print the sum, no reason to save it in a new int sum, just printf("%d", a + b);
Do not request the number of votes outside of a loop, and then loop to verify the value (your first for loop). Consider a DO..WHILE loop instead.
Ex.
do{
scanf("%d", &n);
} while(n <= 0);
//Scan integer and save into n, until you get a positive value
Avoid nesting for loops for no reason, use more if() .. else if() .. if necessary.
It's not the best of practise, but you can also use the continue and break keywords to continue or stop the loops respectively.
Do not use "else" randomly. If you have more conditions to check, leave the if without else. You wanna use else after an if condition if (when the first condition comes back true) you don't want to check the next condition (they will be skipped !)
This is my first post on stack overflow, so this is my code so far, i'm just starting computer engineering and am having some trouble.
#include <stdio.h>
int main ( void ) {
int num, sum = 0, i, ssq = 0, isq, n;
printf("Enter an integer: ");
scanf("%d", &num);
for (i = 1; i <= num; i++) {
sum = sum + (i * i);
}
printf("The sum of the squares of integers from 0 to %d is %d\n", num, sum);
while (i >= 0) {
printf("Would you like to go again? (1 for yes, 0 for no): ");
scanf("%d", &i);
printf("Enter an integer: ");
scanf("%d", &num);
for (isq = 1; isq <= n; isq++);
ssq = ssq + (isq * isq);
printf("The sum of the squares of integers from 0 to %d is %d\n", num, sum);
if (i == 0) break;
}
return 0;
}
This is what I have so far believe it or not it took me 12 hours to do the first part, I've literally been up all night working on this, before the while loop and now I'm completely lost. I added the ssq=0, isq, and n ints in to try to help with no avail. At this point I'm just rearranging stuff for hours on end, this is my first post so please don't be too hard on me!
This contains a whole host of errors, from typos to code duplication, as #HappyCoder has noted above.
First of all, the outer part and the loop part do exactly the same. Think about it for a moment. You first do some task, unconditionally, then ask the user if they want to start over. The task itself doesn't change! Hence, what we can do is this:
do the task;
ask the user if they want to quit or go on;
if yes, return to the start.
In code, this can be done with an endless loop that you break out of if the user wants to stop:
while(1) {
// do user input and calculations here;
printf("Would you like to go again? (1 for yes, 0 for no): ");
scanf("%d", &i);
if (i == 0)
break;
}
See, now we only have one instance of the calculation code! Now, you can throw away half the variables declared in the beginning, since they are duplicate.
Now on to the calculations. You have an uninitialized variable, ssq, in the loop. See where code duplication can get you. In the outer part, it is initialized properly. Inside the loop, however, it is not guaranteed to hold any concrete value, most likely it contains garbage.
Also, as noted by #JohnHascall, this subtle error introduced most likely by a typo:
for (isq = 1; isq <= n; isq++); // <---- the evil semicolon
ssq = ssq + (isq * isq);
The semicolon after the for loop makes the loop empty, and the summation only happens once, but not in the loop, as you want it to be.
Then, you output (print) sum not ssq inside the loop, which is obviously not what you want to print. And, you use the uninitialized n variable from outside the loop as the boundary, instead of the user inputted num.
I want to add yet one more. Sanely naming the variables is a big deal as it helps you to catch potential errors and keep track of how variables are being used throughout the code, not to mention easier understanding of the code by others. Look: int i -> int choice better isn't it?
So we can rewrite the code like this:
#include <stdio.h>
int main ( void )
{
int boundary, choice, isq, ssq;
while (1) {
printf("Enter an integer: ");
scanf("%d", &boundary);
ssq = 0;
for (isq = 1; isq <= boundary; isq++) {
ssq = ssq + (isq * isq);
}
printf("The sum of the squares of integers from 0 to %d is %d\n", boundary, ssq);
printf("Would you like to go again? (1 for yes, 0 for no): ");
scanf("%d", &choice);
if (choice == 0)
break;
}
return 0;
}
for (isq=1; isq<=n; isq++);
ssq = ssq + (isq*isq);
The problem here is that 'n' is not initialized and not used in above scanf statement, you need to use 'num' instead of 'n'
for (isq=1; isq<=num; isq++)
ssq = ssq + (isq*isq);
One likely problem is here:
for (isq = 1; isq <= n; isq++);
ssq = ssq + (isq * isq);
You probably want:
for (isq = 1; isq <= n; isq++) {
ssq = ssq + (isq * isq);
}
Also, you should add:
ssq = 0;
above that loop (think about your 2nd trip through the loop).
Here is #iksemyonov 's answer refactored to honor the "no more than 7 lines in a method" rule (using a hard and fast arbitrary number like 7 is absurd, but the principle of making function do a specific understandable task is reasonable).
#include <stdio.h>
static int getBoundary ( void ) {
int boundary;
printf("Enter an integer: ");
scanf("%d", &boundary);
return boundary;
}
static int computeSSQ ( int limit ) {
int ssq = 0;
for (; limit > 0; --limit) ssq += (limit*limit);
return ssq;
}
static int again ( void ) {
int choice;
printf("Would you like to go again? (1 for yes, 0 for no): ");
scanf("%d", &choice);
return choice;
}
int main ( void ) {
do {
int boundary = getBoundary();
int ssq = computeSSQ(boundary);
printf("The sum of the squares of integers from 0 to %d is %d\n",
boundary, ssq);
} while (again());
return 0;
}
You have made a few mistakes here:
You have put a semicolon after the for loop inside the while block which should be removed.
Inside the while block you have accepted value for 'num' while you have used 'n' in the for loop (for which value is uninitialized). So you should accept the value of 'n' instead of 'num' or else replace 'n' in the for loop with 'num'.
If you want to exit the while loop immediately after user inputs 0 then move the if (i == 0) break; statement to below the scanf ("%d", &i) statement.
In the printf() statement next to the for loop, you have used value of 'sum' while you have calculated value for ssq.
Also you should write ssq = 0 after the printf() statement to reset its value to 0.
Correct all these and the program will work.
what you want to do was basically a menu driven program... i would suggest , like the above one's are right too... but another way you can do is using do{
//the task , i.e. the sum
} while(i!=0);
doing this since do while is an exit controlled loop as you might be knowing... so as in earlier stages u can be free from using break; keyword...
also as you are starting an early bird tip i would like to give is that the suggestion of using functions by #John above ....is good but not if you are doing mistakes in a normal int main() 15 lines code... since if you go in user defined functions like stated above you might go wrong in passing the arguments or basics of function passing... so go for a normal int main code for now...
Note i didnt meant that what # John said was wrong or something...just gave my view/advice
I have a problem with this code.... The project should show me repeated number in the input number. For example:
$ ./a.out
Enter a number: 9893746595
Repeated: 9 5
Here is the code:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int a[10], b[10] ;
int n,t;
printf("Enter a number: ");
for(n=0; n<10;n++)
{
scanf("%d", &a[n]);
n=t;
a[n]=b[t];
}
for(n=0;n<10;n++)
{
for(t=n;t<10;t++)
{
if(a[n]=b[t])
printf("%d", a[n]);
}
}
return 0;
}
if(a[n]=b[t]) assigns b[t] to a[n].
You most likely wanted to use if(a[n] == b[t]) to compare those values.
It's a good idea to compile using the -Wall -Wextra -Werror flags so all warnings are enabled and treated like errors (so you can't simply ignore them). With those flags the compiler will yell at you for doing an accidental assignment.
Your code is bogus. ;-)
The usual approach here is to create an array of 10 ints, one for each digit, and count the occurrences of each digit in the user-supplied number.
There's an idiomatic technique to get the digits of a number num one at a time: use num % 10 to get the last digit, and num / 10 to get the number without its last digit. Then your program might look something like this:
int dcount[10] = {0}; // 10 ints, all initialized to 0
scanf("%d", &num);
while(num) {
dcount[num % 10]++; // increment dcount[i], where i is the last digit of num
num /= 10; // "remove" last digit from num
}
for (int i = 0; i < sizeof(dcount)/sizeof(dcount[0]); i++)
printf("%d occured %d times\n", i, dcount[i]);
I didn't test the above code, so there may be some minor flaws. The general principle should be clear, though.
Hope that helps.
Your code assigns t to n before t has been initialized.
This is bound to cause problems. I haven't fully studied the rest of your code but you should start by initializing t before using it. If that still doesn't work, provide information such as what it does or doesn't do.
You might want to look at the first for loop. t is read from without ever being written to. Same for b. And, you are overwriting the just read in variable a[n] with b[t]. In the conditional for if, you meant == where = is written.
If you turn on every option in your compiler to emit warnings and strictly check for standard language compliance, it would have caught these.
int main()
{
int i, number, digitCount[10];
// Before starting, set the digit count for each digit to 0
for (i = 0; i < 10; i++)
{
digitCount[i] = 0;
}
// Store the entire number in one int
printf("Enter a number: ");
scanf("%d", &number);
// Find the remainder of number / 10 in order to get the last digit
// Divide number by 10 in order to remove that digit
// Continue to peel off digits until you reach zero
while (number != 0)
{
digitCount[number % 10]++;
number /= 10;
}
// For each digit which is counted more than once, print it
printf("Repeated: ");
for (i = 0; i < 10; i++)
{
if (digitCount[i] > 1)
{
printf("%d ", digitCount[i]);
}
}
return 0;
}