In doing an assignment, in which:
Program prints out the sum in the form of the following text
1 + 22 + 333 + 4444 + . . . + nn. . . n }n
and its result. The number n ∈ {1, 2, . . . , 9} is provided by the user
I'm stuck at the point where I don't know how to glue the numbers into one integer, so how to convert "333" into 333, etc.
Here's my code:
#include <stdio.h>
#include <string.h>
int main()
{
printf("Program calculates a sum.\nAutor: Jakub Drozd\n");
int n;
int sum = 0;
printf("Enter the length of the sum (no more than 9): ");
while (scanf_s("%d", &n)!=1 || n < 1 || getchar()!='\n')
{
printf("Wrong input, enter the length of the sum: ");
int c;
while ((c = getchar()) != '\n' && c != EOF)
;
}
for (int i = 1; i <= n; i++)
{
if (i == 1);
else { printf(" + "); }
for (int j = 1; j <= i; j++)
{
printf("%d", i);
}
}
printf("\nEnd of the program\n");
return 0;
}
As you can see, The program correctly displays the numbers to be added, but I don't know how to cast them into integers to sum them up.
Instead of printing out the individual digits, add them together to form the actual value, and then add them to a sum that you present.
The creation of the numbers could be like
int number = 0;
for (int j = 1; j <= i; ++j)
{
number = number * 10 + i;
}
Then adding the numbers is as simple as creating a variable to hole the sum, and adding to it:
int sum = 0;
// ...
sum += number;
Related
#include <stdio.h>
#include <math.h>
int main() {
int n, count, sum;
printf("Enter upper bound n \n");
scanf("%d", &n);
for (int a = 1; a <= n; a++) {
count = 0;
sum = 0;
for (int i = 2; i <= sqrt(a); ++i) {
if (a % i == 0) {
count++;
break;
}
}
if (count == 0 && a != 1) {
sum = a + sum;
}
}
printf("%d", sum);
}
The program is my attempt to print summation of primes < n. I am getting sum = 0 every time and I am unable to fix this issue.
The reason you do not get the sum of primes is you reset the value of sum to 0 at the beginning of each iteration. sum will be 0 or the value of the n if n happens to be prime.
Note also that you should not use floating point functions in integer computations: i <= sqrt(a) should be changed to i * i <= a.
The test on a != 1 can be removed if you start the loop at a = 2.
Here is a modified version:
#include <stdio.h>
int main() {
int n = 0, sum = 0;
printf("Enter upper bound n: \n");
scanf("%d", &n);
// special case 2
if (n >= 2) {
sum += 2;
}
// only test odd numbers and divisors
for (int a = 3; a <= n; a += 2) {
sum += a;
for (int i = 3; i * i <= a; i += 2) {
if (a % i == 0) {
sum -= a;
break;
}
}
}
printf("%d\n", sum);
return 0;
}
For large values of n, a much more efficient approach would use an array and perform a Sieve of Eratosthenes, a remarkable greek polymath, chief librarian of the Library of Alexandria who was the first to compute the circumference of the earth, 2300 years ago.
Here is an improved version:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
int n = 0;
long long sum = 0;
if (argc > 1) {
sscanf(argv[1], "%i", &n);
} else {
printf("Enter upper bound n: \n");
scanf("%i", &n);
}
// special case 2
if (n >= 2) {
sum += 2;
}
unsigned char *p = calloc(n, 1);
for (int a = 3; a * a <= n; a += 2) {
for (int b = a * a; b < n; b += a + a) {
p[b] = 1;
}
}
for (int b = 3; b < n; b += 2) {
sum += p[b] * b;
}
free(p);
printf("%lld\n", sum);
return 0;
}
Error about sum getting set to zero inside the loop has been already pointed out in previous answers
In current form also, your code will not return zero always. It will return zero if value of upper bound is given as non prime number. If prime number is given as upper bound, it will return that number itself as sum.
As mentioned in comment you should initialize sum before first loop something like
int n, count, sum=0;
or you can initialize sum in the loop like
for(a=1,sum=0;a <= n; a++)
and remove sum=0; inside the first loop because it changes sum to 0 every time first loop executes. You can check this by inserting this lines to your code
printf("Before sum %d",sum);
sum = 0;
printf("After Sum %d",sum);
make sure sure that if you are initializing sum in the loop, define "a" in outer of the loop if not the sum goes to local variable to for loop and it hides the outer sum.
I have return the code to find a factorial and to display trailing zeros at the end of the factorial, but the output is wrong... could you please help me to find the mistake?
#include <stdio.h>
int main() {
int m = 1, i, N, count = 0;
scanf("%d", &N);
for (i = 1; i <= N; i++) {
m = m * i;
}
printf("%d", m);
while (m > 0) {
if ((m % 10) == 0) {
count = count + 1;
m = m / 10;
}
break;
}
printf("%d", count);
return 0;
}
Your code only works for very small values of N: up to 9. For slightly larger values, you would need to add an else keyword before the break statement and you would get a correct result for a few more cases.
For larger values, you must compute the power of 5 that divides the factorial. You can do this incrementally by summing the power of 5 that divide each individual number up to and including N.
#include <stdio.h>
int main() {
int N, count;
if (scanf("%d", &N) != 1)
return 1;
/* only consider factors that are multiples of 5 */
count = 0;
for (int i = 5; i <= N; i += 5) {
for (int j = i; j % 5 == 0; j /= 5)
count++;
}
printf("%d\n", count);
return 0;
}
An even simpler and faster solution is this: compute the number of multiples of 5 less or equal to N, add the number of multiples of 5*5, etc.
Here is the code:
#include <stdio.h>
int main() {
int N, count;
if (scanf("%d", &N) != 1)
return 1;
count = 0;
for (int i = N; (i /= 5) > 0;) {
count += i;
}
printf("%d\n", count);
return 0;
}
you have two problems
your collapse the two outputs so you see only one of them / you cannot see who is who, just add a separator between them
an else is missing when you count so you count to only up to 1 and the result is wrong from factorial 10
So the minimal changes produce :
int main()
{
int m=1,i,N,count=0;
scanf("%d",&N);
for(i=1;i<=N;i++)
{
m=m*i;
}
printf("%d\n",m); /* <<< added \n */
while(m>0)
{
if((m%10)==0)
{
count=count+1;
m=m/10;
}
else /* <<< added else */
break;
}
printf("%d\n",count); /* <<< added \n */
return 0;
}
after the changes :
pi#raspberrypi:/tmp $ ./a.out
5
120
1
pi#raspberrypi:/tmp $ ./a.out
10
3628800
2
Of course that supposes first you are able to compute the factorial without overflow
I also encourage you to check a value was read by scanf, checking it returns 1
#include <stdio.h>
int main()
{
int n,i,f=1,t,c=0;
printf("Enter number ");
scanf("%d",&n);
t=n;
for(i=1;t>=5;i++)
{
t=n/5;
c=c+t;
n=t;
}
printf("number of zeros are %d",c);
return 0;
}
#include <stdio.h>
int main()
{
int i; //counter for the loop
int n; //integer
int series;
printf("Enter an integer number: ");
scanf("%d" , &n);
for(i = 1; i <= n; i++)
{
if (i % 2 == 0)
(series -= i * i);
else
(series += i * i);
}
printf("The value of the series is: %d\n" , series);
return 0;
}
So the the loop is just a basic for loop, using I as the counter for as long as it is less than or equal to n
the series that I have to replicate adds odd numbers and subtracts even numbers so the if condition tests if the number is even or odd. The program compiles fine but when I enter the integer as 5 the sum of the series should be 15, however my program gives the sum 32779. Any help on fixing my program would be appreciated.
you didn't initialize series, so it's a random value in the beginning of the calculation.
#include <stdio.h>
int main()
{
int i = 0; //counter for the loop
int n = 0; //integer
int series = 0;
printf("Enter an integer number: ");
scanf("%d" , &n);
for(i = 1; i <= n; i++)
{
if (i % 2 == 0)
(series -= i * i);
else
(series += i * i);
}
printf("The value of the series is: %d\n" , series);
return 0;
}
int main(void)
{
int i,j=0,k; //initialization
char equation[100]; //input is a string (I think?)
int data[3]; //want only 3 numbers to be harvested
printf("Enter an equation: ");
fgets(equation, 100, stdin); //not so sure about fgets()
for (i = 0; i < equation[100]+1; i++) { //main loop which combs through
//"equation" array and attempts
//to find int values and store
while (j <= 2) { //them in "data" array
if (isdigit(equation[i])) {
data[j] = equation[i]
j++;
}
}
if (j == 2) break;
}
for (k = 0; k <= 2; k++) { //this is just to print the results
printf("%d\n", data[k]);
}
return 0;
}
Hello! This is my program for my introductory class in C, I am trying to comb through an array and pluck out the numbers and assign them to another array, which I can then access and manipulate.
However, whenever I run this I get 0 0 0 as my three elements in my "data" array.
I am not sure whether I made an error with my logic or with the array syntax, as I am new to arrays.
Thanks in advance!!! :)
There are a few problems in your code:
for (i = 0; i < equation[100]+1; i++) { should be something like
size_t equ_len = strlen(equation);
for (i = 0; i < equ_len; i++) {
Whatever the input is, the value of equation[100] is uncertain, because char equation[100];, equation only has 100 element, and the last of them is equation[99].
equation[i] = data[j]; should be
data[j] = equation[i];
I suppose you want to store digit in equation to data.
break; should be deleted.
this break; statement will jump out of the while loop, the result is you will store the last digit in equation to data[0] (suppose you have switched data and equation, as pointed out in #2).
If you want the first three digits in equation, you should do something like
equ_len = strlen(equation);
j = 0;
for (i = 0; i < equ_len; i++) {
if (j <= 2 && isdigit(equation[i])) {
data[j] = equation[i];
j++;
}
if (j > 2) break;
}
printf("%d\n", data[k]); should be printf("%c\n", data[k]);
%d will give the ASCII code of data[k], for example, if the value of data[k] is character '1', %d will print 50 (the ASCII code of '1') instead of 1.
Here is my final code, based on the OP code:
#include <ctype.h>
#include <string.h>
#include <stdio.h>
int main(void)
{
int i,j,k;
char equation[100];
int data[3];
int equ_len;
printf("Enter an equation: ");
fgets(equation, 100, stdin);
equ_len = strlen(equation);
j = 0;
for (i = 0; i < equ_len; i++) {
if (j <= 2 && isdigit(equation[i])) {
data[j] = equation[i];
j++;
}
if (j > 2) break;
}
for (k = 0; k <= 2; k++) {
printf("%c\n", data[k]);
}
return 0;
}
Tested with:
$ ./a.out
Enter an equation: 1 + 2 + 3
1
2
3
I'm trying to write a program in C that gives a 13 row pyramid with the following output (notice the pattern of the letters i.e BCB):
A
BCB
DEFED
GHIJIHG
KLMNONMLK
PQRSTUTSRQP
VWXYZABAZYXWV
CDEFGHIJIHGFEDC
KLMNOPQRSRQPONMLK
TUVWXYZABCBAZYXWVUT
DEFGHIJKLMNMLKJIHGFED
OPQRSTUVWXYZYXWVUTSRQPO
ABCDEFGHIJKLMLKJIHGFEDCBA
Here is my attempt at the solution:
#include <stdio.h>
#include <stdlib.h>
int main(void){
char c = 'A';
int height = 13;
int max = 1;
for (int i = 1; i <= height; i++){
//int j = 1;
for (int k = 0; k < height - i; k++)
printf(" "); // print space on left
for (int j = 1; j <= max; j++){
if (j <= max / 2){ // print left side of pyramid
printf ("%c", c);
c = (c - 'A' + 1) % 26 + 'A';
}
else{ // print right side of pyramid
printf ("%c", c);
c = (c -'A' + 25) % 26 + 'A';
}
}
printf("\n");
max += 2;
}
}
However it gives the following incorrect output:
A
ZAZ
YZAZY
XYZAZYX
WXYZAZYXW
VWXYZAZYXWV
UVWXYZAZYXWVU
TUVWXYZAZYXWVUT
STUVWXYZAZYXWVUTS
RSTUVWXYZAZYXWVUTSR
QRSTUVWXYZAZYXWVUTSRQ
PQRSTUVWXYZAZYXWVUTSRQP
OPQRSTUVWXYZAZYXWVUTSRQPO
if I remove the the if/else statement which splits the pyramid in to two sides and simply have only c = (c - 'A' + 1) % 26 + 'A';, I get the following output:
A
BCD
EFGHI
JKLMNOP
QRSTUVWXY
ZABCDEFGHIJ
KLMNOPQRSTUVW
XYZABCDEFGHIJKL
MNOPQRSTUVWXYZABC
DEFGHIJKLMNOPQRSTUV
WXYZABCDEFGHIJKLMNOPQ
RSTUVWXYZABCDEFGHIJKLMN
OPQRSTUVWXYZABCDEFGHIJKLM
Any ideas?
The problem is that you're forgetting to increment the actual overall character. For each line, you need to add characters until you get to the value that you should start at for the next line. Thankfully, this is pretty easy to do:
...
max += 2;
c = (c - 'A' + max / 2 + 1) % 26 + 'A'; // Add this line
}
Here's a short version:
#include <stdio.h>
#define HEIGHT 6
int main(void) {
char* f = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char* b = "ZYXWVUTSRQPONMLKJIHGFEDCBA";
int c = 0;
for(int i=0; i<HEIGHT; ++i)
{
printf("%*.*s%.*s\n", 10, i+1, f+i+c, i, b+strlen(b)-(c+2*i));
c+=i;
}
return 0;
}
IDEOne Link
Output:
Success #stdin #stdout 0s 9424KB
A
BCB
DEFED
GHIJIHG
KLMNONMLK
PQRSTUTSRQP