#include <stdio.h>
int main()
{
int n1, n2, temp, n, d, p;
printf("Enter two numbers(The limits of your prime numbers): ");
scanf("%d %d", &n1, &n2);
if (n1>n2)
{
temp=n1;
n1=n2;
n2=temp;
}
printf("The prime numbers between %d and %d are: ", n1, n2);
for(n=n1;(n<=n2)||(n<2000);++n)
{
p=1;
for(d=2; d<=n/2; ++d)
{
if(n%d==0)
{
p=0;
break;
}
}
if(p==1)
{
if (n==1)
{continue;}
printf("%d",n);
//I don't know what to put here so that the last term won't have a comma
printf(", ");
}
}
return 0;
}
I'm trying to print prime numbers between two intervals(inclusive) but the last terms always have a comma. I need a way to prevent the comma from printing after the last term. The commas are followed by a space before the next term.
For example(My current situation):
Input:1 10
Output:2, 3, 5, 7,
What it should be:2, 3, 5, 7
I forgot to mention that once "n" exceeds 2000 it should stop printing..
A very common problem, independent from the programming language and more of a logical thinking exercise. In this case, you can't tell when you're printing the last number, but you can tell when you print the first. Use that knowledge and put the ", " first in your loop, omitting it on the first iteration.
edit: eg use a flag for this: if (firstRun) { firstRun = 0; } else { fputs(", ", stdout); }
Print the comma separately before the number, and have a conditional stating if this is the first prime number, don't print the comma. Otherwise print it out....
Try this
(n<=n2)?printf(","):(n<2000?printf(","):printf("\n"))
Something like this:
char *separator = "";
for (...) {
...
printf("%s%d", separator, n);
separator = ",";
}
i have a great solution for your question use
printf("\b\b "); //2 time space after \b\b
it include before return 0; statement like :
if(p==1)
{
if (n==1)
{continue;}
printf("%d",n);
//I don't know what to put here so that the last term won't have a comma
printf(", ");
}
}
printf("\b\b "); //here insert code
return 0;
it will help surely
Related
Hi I keep trying to figuure this out but my input keeps getting ignored, thanks in advance
#include <stdio.h>
#include <stdlib.h>
int main(){
float a, b, a0, b0,i;
char ans;
printf("Fibonacci search method\n\nEnter the function:\n");
printf("\nEnter the intervals over which the Fibonacci method must be applied:\n");
for (i = 1; i <= 1; i++) {
printf("a0 = ", i);
scanf("%f", & a);
printf("bo = ", i);
scanf("%f", & b);
}
printf("Narrow down on either a maximiser or a minimiser (max/min): \n", ans);
scanf(" %c", &ans);
while(ans == 'max'){
printf("maximum selected");
}
printf("minimum selected");
return 0;
}
First of all, you're comparing a single char to a whole string, so you need to modify your ans variable declaration to make it a string, like:
char ans[4]
Keep in mind, this will have a maximum size of 3. If you need to store a bigger string, you'll need to modify this.
Then, after doing this, using a while to do that comparison isn't correct. It's better to implement an if-else. And, inside that, the comparison you're doing is wrong. You need to compare strings, not chars, so you need to use strcmp() function, like:
strcmp(ans,"max") == 0
If this function returns a 0, it means both strings are equal.
Another thing to comment is that you will need to modify your scanf to scan a string, not a char, the new one will be scanf("%3s", &ans);.
And let me tell you one more thing. The for you're using has no sense. You're using a for with parameters i = 1; i <= 1; i++. That means i will start the buckle fulfilling the conditions to break it, so it will only be executed once. In other words, the code inside that for will be executed just once, no matter if it's inside or outside the for.
Anyway, and to sum up, here's your new code:
int main(){
float a, b, a0, b0,i;
char ans[4];
printf("Fibonacci search method\n\nEnter the function:\n");
printf("\nEnter the intervals over which the Fibonacci method must be applied:\n");
for (i = 1; i <= 1; i++) {
printf("a0 = ", i);
scanf("%f", & a);
printf("bo = ", i);
scanf("%f", & b);
}
printf("Narrow down on either a maximiser or a minimiser (max/min): \n", ans);
scanf("%3s", &ans);
if(strcmp(ans,"max") == 0)
printf("maximum selected");
else
printf("minimum selected");
return 0;
}
Only the 'strlen' function is being executed by the program.
The if statements inside this while loop do not even work...
#include<stdio.h>
#include<string.h>
#include <ctype.h>
main()
{
char cMessage[100];
int cLow = 0, cUp = 0, cSpec = 0, cSpace = 0, cNum = 0;
printf("Enter your message: ");
scanf("%s", cMessage);
int x = 0;
while(cMessage[x] != 0)
{
x = strlen(cMessage);
printf("Total characters: %d", x);
if(islower(cMessage[x]))
{
printf("\nTotal Lowercase Letters: %d", cLow);
cLow++;
}
else if(isupper(cMessage[x]))
{
printf("\nTotal Uppercase Letters: %d", cUp);
cUp++;
}
else if(isalnum(cMessage[x]))
{
printf("\nTotal Special Characters: %d", cSpec);
cSpec++;
}
else if(isspace(cMessage[x]))
{
printf("\nTotal Lowercase Letters: %d", cSpace);
cSpace++;
}
else if(isdigit(cMessage[x]))
{
printf("\nTotal Lowercase Letters: %d", cNum);
cNum++;
}
}
x++;
}
I cannot figure out the cause of this issue...
What may be the cause of this?
EDIT: So here's the revised code of the program, the only problem that I have now is that the spaces are not being counted. And btw, is there a specific function used to 'count' special characters? I've used 'isalnum' and I realized it was wrong
#include<stdio.h>
#include<string.h>
#include <ctype.h>
#include<conio.h>
main(){
char cMessage[100];
int cLow=0, cUp=0, cSpec=0, cSpace=0, cNum=0;
printf("Enter your message: ");
scanf("%s", cMessage);
int x=0;
while(cMessage[x]){
printf("Total characters: %d", strlen(cMessage));
while(cMessage[x]!=0){
if(islower(cMessage[x])){ cLow++;}
if(isupper(cMessage[x])){ cUp++;}
if(isalnum(cMessage[x])){ cSpec++; }
if(isspace(cMessage[x])){ cSpace++; }
if(isdigit(cMessage[x])){ cNum++; }
x++;
}
printf("\nTotal Lowercase Letters: %d", cLow);
printf("\nTotal Uppercase Letters: %d", cUp);
printf("\nTotal Special Characters: %d", cSpec);
printf("\nTotal Spaces: %d", cSpace);
printf("\nTotal Numbers: %d", cNum);
getch();
}
}
The x = strlen(cMessage); will give you the length of cMessage which is always the index of the last item + 1.
for example if: cMessage = "The" and x = strlen(cMessage) , then:
x = 3
cMessage[0] = 'T'
cMessage[1] = 'h'
cMessage[2] = 'e'
cMessage[3] = NULL terminator // equivalence to 0
Note that there is usually a NULL terminator after the last character.
So as you can see, the while condition is always false after the first pass.
Try to use a separate variable to iterate through cMessage.
Also you need to consider putting variables like cUp++' before the 'printf statements.
A more elegant alternative will be using for statement instead of while.
Also note that isalnum(cMessage[x]) is interfering with if(isdigit(cMessage[x])) so, it is better to use separate if statements and git rid of else if, moreover, if you want to count special characters you have to negates isalnum to be: if(!isalnum(cMessage[x])).
At last your input will not accept sentences (word with spaces between them), so you have to consider replacing:
scanf("%s", cMessage);
with
scanf("%[^\n]s",&cMessage);
You take x as the lenght of your string. So that's one longer then your Array. After the full array is always a 0 to show the program the array is not longer. This way you can never go in the if's
cMessage[x] after x=strlen(cMessage) is always 0. String contains chars from 0 till x - 1, char at post x is 0. Thus any if-condition is false.
I suppose x=strlen(cMessage); is not needed and must be removed, x++ must be three last operator in the loop body, since you want to count chars of different kinds.
printf("Total characters: %zu", strlen(cMessage));
while(cMessage[x] != 0) {
if(islower(cMessage[x])) {
...
}
x++;
}
%d is not proper format for size_t type on 64-bit platform. Read this: How can one print a size_t variable portably using the printf family?
Im having trouble with my prime number section part of my program. When I compile and run my program, the prime numbers print out fine for the first number, but when reprompted for another number. It usually prints out either no numbers or it cuts off the prime numbers from a certain point down. Im new to coding and this forum so I'm sorry about any formatting issues in my post.
#include <stdio.h>
#include <math.h>
int main(void)
{
int number, n=1;
long factorial=1;
int a=1, b=0,c;
int q=2, r=2, w=0;
int prime, count;
printf("Enter a Number:\n");
scanf("\n%d", &number);
while(number!=1000)
{
if(number<1||number>1000)
printf("Input is Invalid\n");
else
{
if(number==1000)
printf("Goodbye\n");
if(number<15)
{
factorial=number;
n=number-1;
while(n>=1)
{
factorial=factorial*n;
n--;
}
printf("The Factorial of %d is: %ld\n", number, factorial);
}
c=a+b;
printf("Fibonacci Sequence up to %d\n ", number);
while(c<number&&a+b<number)
{
c=a+b;
a=b;
b=c;
n++;
printf("%d\t", c);
count=n;
if(count%10==0)
printf("\n");
}
printf("\nTotal:%d\n", n);
printf("\nPrime numbers up to %d:\n", number);
while(q<=number)
{
prime=0;
for(r=2;r<q;++r)
{
if(q%r==0)
{
prime=1;
}
}
if(prime==0)
{
printf("%d\t", r);
w++;
}
q++;
}
count=r;
if(count%10==0)
printf("\n");
printf("\nTotal:%d\n", w);
}
printf("\nEnter a Number:\n");
scanf("\n%d", &number);
a=1;
b=0;
}
return(0);
}
You are never resetting your variable q, which is the control variable for your prime number loop. It is best practice to create all of your variables which need to be reset inside your loop. Either reset q at the beginning/end of your loop, or create q at the beginning of your outer loop and set it to 2.
Like this:
while(number != 1000) {
int q = 2;
//other assignments below which need to be reset
...
//all other code below
...
}
I want a program that can get two integers from user and put the sum of those inputs in a variable, after that checks that is sum more than 5 or not ? (I know I can do it with if , ... but I want to do it with while). I myself did it but it has some problems, would you mind saying what is the problem and how can I debug it ? Here is my code :
#include <stdio.h>
int main()
{
int ui1;
int ui2;
puts("Please enter two numbers:");
scanf("%2i", &ui1, &ui2);
int sum;
sum = ui1+ui2;
while(sum > 5) {
printf("Whats up !");
}
return 0;
}
This line is only scanning for 1 integer (%i with a 2 format, indicating only take 2 digits.):
scanf("%2i", &ui1, &ui2);
But it seems you expected to receive two integers.
This will leave the second argument, ui2, uninitialized.
(It should fill ui1 successfully, at least)
Try instead:
scanf("%i %i", &ui1, &ui2);
Try including the scanf statement into the loop, it will no longer be an infinite loop... (also need to dereference the integers, see EDIT)
#include <stdio.h>
int main()
{
int ui1;
int ui2;
puts("Please enter two numbers:\n");
//scanf("%2i", &ui1, &ui2);
int sum = 10;//(so that it will enter the loop at least once)
//sum = ui1+ui2;
while(sum > 4)
{
printf("enter number 1:\n");
scanf("%i", &ui1); //EDIT &
printf("enter number 2:\n");
scanf("%i", &ui2); //EDIT &
sum = ui1+ui2;
}
printf("result is: %d\n", sum);
getchar();//so you can see the result;
getchar();
return 0;
}
Actually while is a loop stmt not a conditional checker
if you want conditional checker use if...else series , switch etc
Note: in your code loop starts if (sum > 5) and never ends (infinate "Whats up !")
sum = ui1+ui2;
while(sum > 5) ///loop starts if (sum > 5) and never ends (infinate "Whats up !")
{
printf("Whats up !"); // (infinate "Whats up !")
}
if(sum > 5)
{
//greater stuff
}
else
{
//lower stuff
}
See Tutorial Here conditionals Stmts
You need to reset the "sum", because otherwise the while loop will be true FOREVER.
Second the input scanf is simply wrong.
Here the correct code
#include <stdio.h>
int main()
{
int ui1;
int ui2;
puts("Please enter two numbers:");
scanf("%d %d", &ui1, &ui2);
int sum;
sum = ui1+ui2;
while(sum > 4) { printf("Whats up !");
sum=0;}
return 0;
}
I'm not sure that i got what you want to do... but if you simply want to check the sum of the two integers using the while statement, you can put a break inside the while loop and everything will work :)
#include <stdio.h>
int main()
{
int ui1;
int ui2;
puts("Please enter two numbers:");
scanf("%2i", &ui1, &ui2);
int sum;
sum = ui1+ui2;
while(sum > 5) {
printf("Whats up !");
break;
}
return 0;
}
As others told you, using a if is the best solution
I'm trying to make the letters of a matrix sort alphabetically and then be written out in a single string.For instance you type ten words,which are then stored in an array,and every letter has its place in the matrix then,right?But after I've written the words I want to bunch all the letters of all words together and then type all the letters out in alphabetical order.This is what I have so far:
#include <stdio.h>
#include <conio.h>
int main(void){
int i, j, k, f, n, m;
//was trying out various things,that's why I have so many useless ints up there
char word[10][15],temp;
for(i=0;i<=9;i++)
{
printf("Type in wword number %d: ", i+1);
gets(word[i]);
}
for(k=i-1;k>=0;k--)
{
for(m=0;m<k;m++)
if(word[k][f] > word[m][n])
{
temp=word[k][f];
word[k][f]=word[m][n];
word[m][n]=temp;
}
}
printf("Letters alphabetically sorted: ");
for(i=0;i<=9;i++){
for(j=0;j<=14;j++){
printf("%d",word[i][j]);
}
}
printf("\n");
getch();
}
I'm still in the process of learning about matrixes and I've gotten pretty familiar with arrays by now.But the sorting thing is confusing me,this was my attempt but it doesn't work.It lets you write all the words,and then it crashes.
What am I doing wrong here?And how do I correct it?
In your code here:
temp=word[k][f];
word[k][f]=word[m][n];
word[m][n]=temp;
the variables n and f are used uninitialised. That will most likely be the cause of the crash.
f,n are uninitialized. It has garbage and is the reason for crashing at this point.
for(k=i-1;k>=0;k--)
{
for(m=0;m<k;m++)
if(word[k][f] > word[m][n]) // f,n are uninitialized and are error prone
I think this will work..Please excute and tell me..
void main()
{
char word[10][15],temp,sorted_word[15];
int i,j,ii,k,l=0;
for(i=0;i<=9;i++)
{
printf("Type in wword number %d: ", i+1);
gets(word[i]);
}
for(i=0;i<=9;i++)
{
for(j=0;word[i][j]!='\0';j++)
{
ii=i;
for(k=j+1;1;k++)
{
if(ii==9 && word[ii][k]=='\0')
break;
if(word[ii][k]=='\0')
{
ii++;
k=0;
}
if(word[i][j]>word[ii][k])
{
temp=word[i][j];
word[i][j]=word[ii][k];
word[ii][k]=temp;
}
}
sorted_word[l++]=word[i][j];
}
}
sorted_word[l]='\0';
printf("%s",sorted_word);
getch();
}
here the
for(i=0;i<=9;i++)
{ printf("type in wword %d: ",i+1);
gets(word[i]);
}
gets (word[1]);
stores the value from word[1] onwards but where as the character array starts from
word[0].
may be this is not the full solution for u problem
this issue may help u in solving your doubt.