My solution for a sum-difference function isn't working - c

I'm trying to write a loop function that returns the result of a computation given a positive integer nVal.
Given nVal, the function computes for 1 + 2 - 3 + 4 - 5 + ... + nVal. So for example if nVal = 4, the function returns the result of 1 + 2 - 3 + 4. The solution I made isn't looping nVal properly and I don't know how to fix it.
Any fixes that I can try?
Here's my code so far (Btw I'm using C language):
#include <stdio.h>
int getValue (nVal)
{
int i, nResult = 0;
for (i = nVal; i <= nVal; i++)
{
if (i % 2 == 0)
{
nResult += i;
}
else if (i % 2 == 1)
{
nResult -= i;
}
}
if (nVal == 1)
nResult +=i + 1;
return nResult;
}
int main ()
{
int nVal, nResult;
printf ("Enter n value: ");
scanf ("%d", &nVal);
nResult = getValue(nVal);
printf ("Result: %d", nResult);
return 0;
}

Because the numbers are consecutives,I removed the if elseif statement ,I use the variable k to reverse '+' to '-',my loop start from 2 to nVal
Your loop
for (i = nVal; i <= nVal; i++)
runs just 1 time
so ,you should changed it to
for (i = 2; i <= nVal; i++)
and (nResult=1)because in your exercise the sign changed from the third number, not from the second number
here:
if (nVal == 1)
nResult +=i + 1;
If I write as 1 input ,the output is 2 ,I remove this line
my code:
#include <stdio.h>
int getValue (nVal)
{
int i, nResult = 1;
int k=1;
for (i = 2; i <= nVal; i++)
{
nResult+=i*k;
k*=-1;
}
return nResult;
}
int main ()
{
int nVal, nResult;
printf ("Enter n value: ");
scanf ("%d", &nVal);
nResult = getValue (nVal);
printf ("Result: %d", nResult);
return 0;
}

Related

I want to print the following pyramid of number pattern

1
2 4
3 5 7
6 8 10 12
9 11 13 15 17
Following is the code in which I am not able to print the pyramid:-
int main()
{
int i,j;
for(i=1;i<=5;i++){
for(j=1;j<=i;j++){
printf("%d ",i*j);
}
printf("\n");
}
return 0;
}
You need to track both even and odd numbers .
#include <stdio.h>
int main()
{
int even=1,odd=2;
int n=10;
for (int i = 1; i <= n; i++)
{
int a= (i % 2 == 0);
for (int j = 1; j < i; j++)
{
if(a)
{
printf("%d ",even);
}
else
{
printf("%d ",odd);
}
even += a ? 2 : 0;
odd += a ? 0 : 2;
}
printf("\n");
}
return 0;
}
Not very clean and compact algorithm but sth like this would work:
#include <stdio.h>
#include <stdlib.h>
int main() {
char tmp[10];
int n = 0, row = 1, odd = 1, even = 2, c = 0, selectOdd, fin = 0;
printf("maximum number: ");
scanf("%s", tmp);
n = atoi(tmp);
if (n != 0) {
while (fin < 2) {
selectOdd = row % 2;
c = row;
if (selectOdd) {
while (c != 0) {
printf("%3d", odd);
odd += 2;
if (odd > n) {
fin++;
break;
}
c--;
}
}
else {
while (c != 0) {
printf("%3d", even);
even += 2;
if (even > n) {
fin++;
break;
}
c--;
}
}
printf("\n");
row++;
}
}
return 0;
}
it's simple
your algorithm is odd, even, odd,... and so on
so you start with odd number until reach line number
for next line is even and you can find start number with this
you just need find number at start of line and continue print number number
in each step you just need
num += 2;
remember 'lineIndex' start from 1
num = (lineIndex - 1) * 2 + lineIndex % 2;
this is a full code
#include <stdio.h>
int main(){
int numIndex;
int lineIndex;
int num;
for (lineIndex = 1; lineIndex <= 5; lineIndex++) {
num = (lineIndex - 1) * 2 + lineIndex % 2;
for (numIndex = 0; numIndex < lineIndex; numIndex++) {
printf("%2d ", num);
num += 2;
}
printf("\n");
}
}

How many prime numbers C program

I wrote this program to find prime numbers between 1 and 50000, and I still need to find how many prime numbers there is (I tried a lot of tricks but I did not succeed)
#include <stdio.h>
//int getValueFromUser();
void PrintListOfPrime(int value);
int main() {
int value = 23;
PrintListOfPrime(value);
return 0;
}
void PrintListOfPrime(int value) {
int ValueIsPrime; //ValueIsPrime is used as flag variable
printf("The list of primes: ");
for (int i = 2; i <= value; i++) {
ValueIsPrime = 1;
/* Check if the current number i is prime or not */
for (int j = 2; j <= i / 2; j++) {
/*
* If the number is divisible by any number
* other than 1 and self then it is not prime
*/
if (i % j == 0) {
ValueIsPrime = 0;
break;
}
}
/* If the number is prime then print */
if (ValueIsPrime == 1)
printf("%d, ", i);
}
printf("\n");
}
I tried a lot of tricks but I did not succeed
If OP's code takes too long to ran, iterate to the square root of i, not up to i/2.
j <= i / 2 is very slow. Use j <= i / j instead.
Form a count and increment with every prime. #gspr
if (ValueIsPrime == 1) {
printf("%d, ", i);
prime_count++;
}
Bigger change yet even faster to "find prime numbers between 1 and 50000", research Sieve of Eratosthenes
Hello fast answer is to create a variable in main, int totaleOfPrimes = 0; for example.
then send it by reference to the fucntion :
Function declaration : void PrintListOfPrime(int value,int* counter);
Function call : void PrintListOfPrime(value,&totaleOfPrimes);
then Increment counter befor printing :
if (ValueIsPrime == 1){
(*counter)++;
printf("%d, ", i);
}
There is no need to iterate the loops for all numbers between 2 and value. You should consider only 2 and odd numbers.
The function can look the following way as it is shown in the demonstrative program below.
#include <stdio.h>
static inline size_t PrintListOfPrime( unsigned int n )
{
size_t count = 0;
printf( "The list of primes:\n" );
for ( unsigned int i = 2; i <= n; i = i != 2 ? i + 2 : i + 1 )
{
int isPrime = 1;
/* Check if the current number i is prime or not */
for ( unsigned int j = 3; isPrime && j <= i / j; j += 2 )
{
/*
* If the number is divisible by any number
* other than 1 and self then it is not prime
*/
isPrime = i % j != 0;
}
/* If the number is prime then print */
if ( isPrime )
{
if ( ++count % 14 == 0 ) putchar( '\n' );
printf( "%u ", i );
}
}
return count;
}
int main(void)
{
unsigned int n = 50000;
size_t count = PrintListOfPrime( n );
printf( "\n\nThere are %zu prime numbers up to %u\n", count, n );
return 0;
}
Run this code in C. It will return the value of a pi(x) function. It is basically the Prime counting function:
#include <stdio.h>
#define LEAST_PRIME 2
#include <math.h>
int main() //works for first 10000 primes.
{
int lower_limit = 2, no_of_sets;
// printf("NUMBER OF SETS: ");
// scanf("%d", &no_of_sets);
int remainder, divisor = 2, remainder_dump, upper_limit; //upper limit to be specified
//by user.
int i = 1;
// printf("SPECIFY LOWER LIMIT: ");
// scanf("%d", &lower_limit);
int number_to_be_checked = lower_limit;
printf("SPECIFY UPPER LIMIT: ");
scanf("%d", &upper_limit);
printf("2\t\t\t\t", number_to_be_checked);
//PRINTS 2.*/
do
{
remainder_dump = 1;
divisor = 2;
do
{
remainder = number_to_be_checked % divisor;
if (remainder == 0)
{
remainder_dump = remainder_dump * remainder; // dumping 0 for rejection.
break;
}
++divisor;
} while (divisor <= number_to_be_checked / divisor); // upto here we know number
is prime or not.
if (remainder_dump != 0)
{
++i;
printf("%d.\t\t\t\t", number_to_be_checked); //print if prime.
};
number_to_be_checked = number_to_be_checked + 1;
} while (number_to_be_checked <= upper_limit);
printf("\n pi(x) = %d \n", i);
//printf("pi function value is %f.", (i - 1) / (log(i - 1)));
float app;
app = upper_limit / (log(upper_limit));
float plot_value;
plot_value = (i) / app;
printf(" BETA FUNCTION VALUE ~ %f", plot_value);
return 0;
}

loop inside another loop what is wrong with this code

My input was
2
4
as I entered t as 2, it should run the the loop twice and accept one more integer but it replies
return 0
I am trying to get many different inputs and running second loop according to them but after first input program returns 0. I don't know why; please correct me
#include <stdio.h>
int main()
{
int t, i, n, sum = 0;
scanf("%d", &t);
for (i = 0; i < t; i++)
{
scanf("%d", &n);
for (i = 1; i < n; i = i + 2)
{
sum = sum + ((n - i + 1) * (n - i + 1));
}
printf("%d\n", sum);
}
return 0;
}

i am using 4 for lopp , 2 are working correct rest 2 are showing issue 3 and 4 loop are showing invalid answer

i am using 4 for lopp , 2 are working correct rest 2 are showing issue 3 and 4 loop are showing invalid answer:
#include <stdio.h>
int main(void) {
// your code goes here
int n,arr[n],i,l=0,m=0,u=0,d=0;
printf("enter the value of n");
scanf("%d",&n);
arr[0]=0;
for(i=0;i<n;i++) {
arr[i+1]=arr[i]+10;
}
printf("%d",arr[3]);
for(i=1;i<=n;i=i+4) {
l=arr[i]+l;
}
for(i=2;i<=n;i=i+4) {
u=arr[i]+u;
}
for(i=3;i<=n;i=i+4) {
m=arr[i]+m;
}
/* for(i=4;i<=n;i=i+4) { d=arr[i]+d; } */
printf("\n%d\n",l);
printf("%d\n",u);
printf("%d\n",m);
printf("%d\n",d);
return 0;
}
answer in negative
Among the things wrong in this code
Your decl of arr[n] is based on an indeterminate n value. The array doesn't magically resize when you read n later in your program. n has to be known before the arr decl.
Your loop limits are potentially out of range (and definitely with the first loop).
The scanf call to populate n isn't checked for successful stdin input. Never assume your IO works, especially the 'I' in IO.
Just fixing those:
#include <stdio.h>
int main(void)
{
int n, i, l = 0, m = 0, u = 0, d = 0;
printf("enter the value of n");
if (scanf("%d", &n) == 1 && n > 0)
{
int arr[n];
arr[0] = 0;
for (i = 0; i<(n - 1); i++) {
arr[i + 1] = arr[i] + 10;
}
printf("%d", arr[3]);
for (i = 1; i < n; i += 4) {
l = arr[i] + l;
}
for (i = 2; i < n; i += 4) {
u = arr[i] + u;
}
for (i = 3; i < n; i += 4) {
m = arr[i] + m;
}
printf("\n%d\n", l);
printf("%d\n", u);
printf("%d\n", m);
printf("%d\n", d);
}
return 0;
}
See it live on ideone.com

How to find the sum of Prime Numbers in C within a given range?

I'm very new to programming and I was asked to find the sum of prime numbers in a given range, using a while loop. If The input is 5, the answer should be 28 (2+3+5+7+11). I tried writing the code but it seems that the logic isn't right.
CODE
#include <stdio.h>
int main()
{
int range,test;
int sum = 2;
int n = 3;
printf("Enter the range.");
scanf("%i",range);
while (range > 0)
{
int i =2;
while(i<n)
{
test = n%i;
if (test==0)
{
goto end;
}
i++;
}
if (test != 0)
{
sum = sum + test;
range--;
}
end:
n++;
}
printf("The sum is %i",sum);
return 0;
}
It would be nice if you could point out my mistake and possibly tell me how to go about from there.
first of all, in the scanf use &range and not range
scanf("%i",&range);
Second this instruction is not correct
sum = sum + test;
it should be
sum = sum + n;
and also the
while (range > 0)
should be changed to
while (range > 1)
Because in your algorithm you have already put the first element of the range in the sum sum = 2 so the while should loop range - 1 times and not range times
That's all
OK, my C is really bad, but try something like the following code. Probably doesn't compile, but if it's a homework or something, you better figure it out yourself:
UPDATE: Made it a while loop as requested.
#include <stdio.h>
int main()
{
int range, test, counter, innerCounter, sum = 1;
int countPrimes = 1;
int [50] primesArray;
primesArray[0] = 1;
printf("Enter the range.");
scanf("%i",range);
counter = 2;
while (counter <= range) {
for (innerCounter = 1; innerCounter < countPrimes; innerCounter++) {
if (counter % primesArray[innerCounter] == 0)
continue;
primesArray[countPrimes + 1] = counter;
countPrimes ++;
sum += counter;
}
counter ++
}
printf("The sum is %i",sum);
return 0;
}
I haven't done C in a while, but I'd make a few functions to simplify your logic:
#include <stdio.h>
#include <math.h>
int is_prime(n) {
int i;
for (i = 2; i <= sqrt(n); i++) {
if (n % i == 0) {
return 0;
}
}
return 1;
}
int main() {
int range, i, sum, num_primes = 0;
printf("Enter the range: ");
scanf("%d", &range);
for (i = 2; num_primes < range; i++) {
if (is_prime(i)) {
sum += i;
num_primes++;
}
}
printf("The sum is %d", sum);
return 0;
}
Using goto and shoving all of your code into main() will make your program hard to debug.
Copy - pasted from here.
#include <stdio.h>
int main() {
int i, n, count = 0, value = 2, flag = 1, total = 0;
/* get the input value n from the user */
printf("Enter the value for n:");
scanf("%d", &n);
/* calculate the sum of first n prime nos */
while (count < n) {
for (i = 2; i <= value - 1; i++) {
if (value % i == 0) {
flag = 0;
break;
}
}
if (flag) {
total = total + value;
count++;
}
value++;
flag = 1;
}
/* print the sum of first n prime numbers */
printf("Sum of first %d prime numbers is %d\n", n, total);
return 0;
}
Output:
Enter the value for n:5
Sum of first 5 prime numbers is 28
Try the simplest approach over here. Check C program to find sum of all prime between 1 and n numbers.
CODE
#include <stdio.h>
int main()
{
int i, j, n, isPrime, sum=0;
/*
* Reads a number from user
*/
printf("Find sum of all prime between 1 to : ");
scanf("%d", &n);
/*
* Finds all prime numbers between 1 to n
*/
for(i=2; i<=n; i++)
{
/*
* Checks if the current number i is Prime or not
*/
isPrime = 1;
for(j=2; j<=i/2 ;j++)
{
if(i%j==0)
{
isPrime = 0;
break;
}
}
/*
* If i is Prime then add to sum
*/
if(isPrime==1)
{
sum += i;
}
}
printf("Sum of all prime numbers between 1 to %d = %d", n, sum);
return 0;
}

Resources