Change For Loop into While Loop - c

I'm new to programming and I need to switch this code into a while Loop.
#include <stdio.h>
void main()
{
int i,n,sum=0;
printf("Input number of terms : ");
scanf("%d",&n);
printf("\nThe odd numbers are :");
for(i=1;i<=n;i++)
{
printf("%d ",2*i-1);
sum+=2*i-1;
}
printf("\nThe Sum of odd Natural Number upto %d terms : %d \n",n,sum);
}
The question is Write a program in C to display the n terms of odd natural number and their sum

The loop continuation condition stands alone while initialization and incrementation are done separately, before and within the loop, respectively.
#include <stdio.h>
void main()
{
int i,n,sum=0;
printf("Input number of terms : ");
scanf("%d",&n);
printf("\nThe odd numbers are :");
i = sum;
while(i<=n)
{
printf("%d ",2*i-1);
sum+=2*i-1;
i++;
}
printf("\nThe Sum of odd Natural Number upto %d terms : %d.
\n",n,sum);
}
You can use a 'do while' loop if you know the first iteration will always take place; the loop continuation condition is evaluated after execution.
do {
...
} while(i <= n);

A for loop consists of 4 parts:
for ( initial_expression; loop_condition; update_expression )
{
//body
}
initial_expression gets executed once, when entering the loop.
loop_condition is checked when entering the loop, and after each iteration
update_expression is executed each iteration. ( NOT at the first entry to loop )
body is executed each iteration.
Whereas a while loop consists of 2 parts:
while ( loop_condition )
{
//body
}
In order to make your while loop behave as your for loop, you need to add other two parts yourself.
initial_statement;
while ( loop_condition )
{
//body
update_expression;
}
This is identical to the previous for loop. I recommend you to check flowcharts for while and for loops to get better understanding of work flow.

while (i++<=n) {
/* whatever */
}
will do the job

Related

Calculating factorial multiple times in a loop only works the first time through

This program that calculates the value of n! only gives the correct value the first time through the loop. On each subsequent time through the loop it gives an incorrect value.
What am I doing wrong?
#include <stdio.h>
int main()
{
int n,result=1;
while(1){
do{
printf("\nInput n:");
scanf("%d",&n);
}while(n<1);
for (int i=1;i<=n;i++)
{
result*=i;
}
for(int j=1;j<=n;j++)
{
printf("%d",j);
if(j!=n)
{
printf("x");
}
}
printf("=%d",result);
}
}
The reason you're not getting the same value for result each time through the outer loop is because you don't reset its value when you start the loop.
The first time through the loop result starts with a value of 1. The next time through, it starts with the value it had when it finished the last iteration through the loop because you didn't bother to change it.
You want to set result to 1 at the start of the loop.
while(1){
result = 1;
do{
...

Loop does not run more than once

The output should print the statement "Case #(N): I will become a good boy." a certain number of times depending on user input. It should only print prime numbers of N. This is the latest attempt.
#include<stdio.h>
int main(){
int primeNum;
int primeCount;
int primeCheck;
int caseCount=1;
int caseCheck;
scanf("%d", &caseCheck);//gets number of cases
do {
scanf("%d", &primeNum);
primeCheck = 0;
if (primeNum<=1)
{
caseCount++;
}
for (primeCount=2 ; primeCount<=primeNum/2 ; primeCount++)//checks if number is prime
{
if ((primeNum%primeCount) == 0)//checks if number is not prime
{
primeCheck=1;
}
}
if (primeCheck==0)
printf("Case #%d: I will become a good boy.\n", caseCount);//prints if number is prime
} while (caseCount=caseCheck);//while case counter does not exceed number of cases
return(0);}`
The result of this piece of code when the output is 2 [enter] 4 [enter] 2 is "Case #2: I will become a good boy." Why does it not print more than one time and start from number 2?
Just change while (caseCount=caseCheck); to while (caseCount==caseCheck);
The problem with your code is you're not checking the condition. You're just reassigning a value to a variable.

program that tells if a number is prime

you enter a number and the program will find if the number is prime or not
so when I enter the number 7 for the first time it will show you 'the number is prime'
then I enter 8 and it will show you 'the number is not prime'
after that I re_enter the number 7 and it will show you 'the number is not prime'
I don't know where is the problem
please help me
an example photo from here
and my code is :
#include <stdio.h>
#include <stdlib.h>
int main (void){
int n;
int t;
int isPrime=0;
char var;
while(var!='q'){
printf("q=quit p=prime :");
fflush(stdin);
scanf("%c",&var);
if(var=='p'){
printf("plz put the number value :");
scanf(" %d",&n);
for(t=2;t<=n/2;t++){
if (n%t==0){
isPrime=1;
break;
}
}
if(isPrime==0){
printf("%d is a prime number\n",n);
}
else{
printf("%d is not a prime number\n",n);
}
}
else if(var=='q'){
printf("thank you bye\n");
break;
}
else{
printf("a wrong letter\n");
}
}
return 0;
}
You need to set isPrime to 0 each time the user enters a number. Otherwise, it still holds the value from the previous number.
Move the variable declaration
int isPrime = 0;
inside the while loop.
BTW, isn't that variable name backwards? You set it to 1 (i.e. true) when you discover that there's a number that divides it equally. But that's when the number is not prime.
You forgot to reset isPrime back to zero inside the "while" loop.
By they way, looks like you are doing this as a learning exercise. That's good, there's no better way to learn than to try things out.
Here's a tip in C, any non-zero value is treated as "true", and zero is treated as "false". So instead of this:
if (myFlag==1) { ... do something }
Just write this:
if (myFlag) { ... do something }

Removing repetitions of same numbers in an array

Task is to display the array that has no repetitions based on some user generated input.
I'm trying to compare the number with every number before it, if the equality happens, a=1, it should skip it. Code doesn't return anything.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int X[30],Y[30],i,j,k=0,a,N;
printf("Length of the vector: ");
scanf("%d",&N);
printf("Input the numbers: ");
for(i=0;i<N;i++)
scanf("%d",X+i);
Y[0]=X[0];
for(i=1;i<N;i++){
for(j=i-1;j>=0;j--)
if(X[i]=X[j])
a=1;
if(a==0){
k++;
Y[k]=X[i];
}
a=0;
}
for(i=0;i<k;i++)
printf("%d",Y[i]);
}
Three separate issues in your code block:
a is not initialized the first time through your loop. Add a line a = 0; above your loop.
Your if block reads if(X[i]=X[j]); it should be if(X[i] == X[j]) (you're missing one =)
Your final value of k is going to be one less than the total number of elements that you have. Change your final for loop to i = 0; i <= k; i++

C Program to find prime number

Hey guys so I need to make a program which asks the user to enter a number as a argument and then let them know if it is a prime number or 0 otherwise. So the code I have so far is as follows but I am a little confused on how to make it run through all the possible values of the and make sure that it isn't a non-prime number. Right now what happens is that the program opens, I enter a value and nothing happens. Note: I have math in the header as I am unsure if it is needed or not at this stage.
EDIT: SO I MADE THE CHANGES SUGGESTED AND ALSO ADDED A FOR LOOP HOWEVER WHEN I GO TO COMPILE MY PROGRAM I GET AN WARNING SOMETHING ALONG THE LINES OF 'CONTROL MAY REACH END OF NON-VOID FUNCTION'. HOWEVER THE PROGRAM DOES COMPILE WHEN I GO TO ENTER A NUMBER AND HIT ENTER IRRELEVANT OT WHETHER OR NOT IT IS A PRIME NUMBER I GET AN ERROR BACK SAYING 'FLOATING POINT EXCEPTION: 8'.
EDIT 2: THE FLOATING POINT ERROR HAS BEEN FIXED HOWEVER NOW THE PROGRAM SEEMS TO THINK THAT EVERY NUMBER IS NON - PRIME AND OUTPUTS IT THIS WAY. I CAN'T SEEM TO SEE WHY IT WOULD DO THIS. I AM ALSO STILL GETTING THE 'CONTROL MAY REACH END OF NON-VOID FUNCTION' WARNING
#include <stdio.h>
#include <math.h>
int prime(int a){
int b;
for(b=1; b<=a; b++){
if (a%b==0)
return(0);
}
if(b==a){
return(1);
}
}
int main(void){
int c, answer;
printf("Please enter the number you would like to find is prime or not= ");
scanf("%d",&c);
answer = prime(c);
if(answer==1){
printf("%d is a prime number \n",c);
}
else
printf("%d is not a prime number\n",c);
}
1. You never initialized i (it has indeterminate value - local variable).
2. You never call function is_prime.
And using a loop will be good idea .Comparing to what you have right now.
I just modified your function a little. Here is the code
#include <stdio.h>
#include <math.h>
int prime(int a)
{
int b=2,n=0;
for(b=2; b<a; b++)
{
if (a%b==0)
{
n++;
break;
}
}
return(n);
}
int main(void)
{
int c, answer;
printf("Please enter the number you would like to find is prime or not= ");
scanf("%d",&c);
answer = prime(c);
if(answer==1)
{
printf("%d is not a prime number \n",c);
}
else
{
printf("%d is a prime number\n",c);
}
return 0;
}
Explanation-
In the for loop, I am starting from 2 because, I want to see if the given number is divisible by 2 or the number higher than 2. And I have used break, because once the number is divisible, I don't want to check anymore. So, it will exit the loop.
In your main function, you had not assigned properly for the printf() statement. If answer==1, it is not a prime number. (Because this implies that a number is divisible by some other number). You had written, it is a prime number(which was wrong).
If you have any doubts, let me hear them.
I suggest you start with trial division. What is the minimal set of numbers you need to divide by to decide whether a is prime? When can you prove that, if a has a factor q, it must have a smaller factor p? (Hint: it has a prime decomposition.)
Some errors your program had in your prime finding algorithm:
You start the loop with number 1 - this will make all numbers you test to be not prime, because when you test if the modulo of a division by 1 is zero, it's true (all numbers are divisible by 1).
You go through the loop until a, which modulo will also be zero (all number are divisible by themselves).
The condition for a number to be prime is that it must be divisible by 1 and itself. That's it. So you must not test that in that loop.
On main, the error you're getting (control reaches end of non-void function) is because you declare main to return an int.
int main(void)
And to solve that, you should put a return 0; statement on the end of your main function. Bellow, a working code.
#include <stdio.h>
#include <math.h>
int prime(int a)
{
int b;
for (b = 2; b < a; b++) {
if (a % b == 0)
return (0);
}
return 1;
}
int main(void)
{
int c, answer;
printf
("Please enter the number you would like to find is prime or not= ");
scanf("%d", &c);
answer = prime(c);
if (answer == 1) {
printf("%d is a prime number \n", c);
} else {
printf("%d is not a prime number\n", c);
}
return 0;
}
On a side note, don't use the CAPSLOCK to write full sentences. Seems like you're yelling.
Mathematically the maximum divisor of a number can be as a large as the square of it, so we just need to loop until sqrt(number).
A valid function would be:
//Function that returns 1 if number is prime and 0 if it's not
int prime(number) {
int i;
for (i = 2; i < sqrt(number); i++) {
if (a % i == 0)
return (0);
}
return 1;
}
#include<stdio.h>
int main()
{
int n , a, c = 0;
printf ("enter the value of number you want to check");
scanf ("%d", &n);
//Stopping user to enter 1 as an input.
if(n==1)
{
printf("%d cannot be entered as an input",n);
}
for(a = 2;a < n; a++)
{
if(n%a==0)
{
c=1;
break;
}
}
if(c==0 && n!=1)
{
printf("%d is a prime number \n",n);
}
else
{
if(c!=0 && n!=1)
{
printf("%d is not a prime number \n",n);
}
}
return 0;
}
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x,i;
printf("enter the number : ");
scanf("%d",&x);
for ( i=2; i<x;i++){
if ( x % i == 0){
printf("%d",x);
printf(" is not prime number ");
printf("it can be divided by : ");
printf("%d",i);
break;
}[this is best solution ][1]
}
if( i>=x) {
printf("%d",x);
printf(" is prime number");
}
}

Resources