How to sum all values in a same variable? - c

I am working on an assignment but the code is doing some weird stuff. It is my 7th day "programming", so it might be just an obvious mistake, which I simply cannot see.
I want the program to sum all values stored in a same variable. I tried to replicate some code from here: https://stackoverflow.com/a/42166389, but it did not work as expected.
So, given a set of values -let's say 012345-, the program should take every other number -4, 2, and 0-, and sum them -giving back "6"-. And, although it does identify the digits, it does not sum them... at least properly.
I do not understand why, but it gives back 48.
I have tried different inputs, and while identifying the digits properly, in all cases the sum was wrong.
I would really appreciate any help.
Oh, and here is my code!:
#include <cs50.h>
#include <stdio.h>
#include <string.h>
int main(void) {
char c;
string number;
int length, i, sum = 0;
printf("Type card number: ");
number = get_string();
printf("Tell us how many characters long was your number: ");
length = get_int();
for (i = 1; i <= length / 2; i++) {
c = number[(strlen(number) - i * 2)];
sum = c;
printf("%c %i %s\n", c, sum, number);
}
}
Some examples:
For input 012345 and length=6, the output is:
4 52 012345
2 50 012345
0 48 012345
For input 9876543210 and length=10, the output is:
1 49 9876543210
3 51 9876543210
5 53 9876543210
7 55 9876543210
9 57 9876543210
And, just to summarize, what I want is a way of summing all the values in a same variable.

sum = c;
You are assigning ASCII value to sum.You should get the corresponding number and also add it to sum, not just assign.
4 52 012345 //52 is ASCII value of 4
2 50 012345 //50 is ASCII value of 2
0 48 012345 //48 is ASCII value of 0
Try this,
sum+=c-'0';

Related

How to generate all the distinct numbers which can be formed by eliminating one or more digits from left and/or right end of each number

I need to read some numbers from a file and generate all the numbers which can be formed by removing 1 digit from the start and one from the end ( for each one of my numbers read ) and print them into a new file.I know how to read and print in files so my question is more about the way I should think when solving this problem.
Here is an example for this problem:
for 3457 the output should be:
457
345
34
45
57
3
4
5
7
my initial thought was to read the numbers as an array of strings using a double pointer ( assuming I know how many numbers I should read so I can dynamically allocate memory to it ) and then to work on them.
After that I though of a way to generate the numbers that are obtained by removing 1 digit from the start and one from that end ( but not simultaneously ) for that I used a for loop:
for ( i = 1, j = (strlen(p[0]) - 2); i < strlen(p[0]) - 2, j >=0; ++i, --j ) //p[0] is my first number read from the file
{
printf("\n%s", p[0] + i); //this will print the numbers 457, 57, 7
char temp[10];
strncpy(temp, p[0], j);//I copy into a new temporary string to print the numbers 345, 34, 3
temp[j] = '\0';
printf("%s", temp);
printf("\n%s", temp + i);//this will print the numbers 45,4
}
But I have no idea on how to proceed with the rest of the numbers and i simply wasn't able to find or to think of an algorithm which will print them in that order, so I would really appreciate some help on how to solve this problem
Assuming that you have the number converted to a string (e.g. using sprintf) you could do something like this:
Take the original string and remove 0 chars from the right
Remove 0 chars from the left and print
Remove 1 chars from the left and print
Remove 2 chars from the left and print
...
Remove string length - 1 chars from the left and print
Take the original string and remove 1 chars from the right
Remove 0 chars from the left and print
Remove 1 chars from the left and print
Remove 2 chars from the left and print
...
Remove string length - 1 chars from the left and print
Take the original string and remove 2 chars from the right
Remove 0 chars from the left and print
Remove 1 chars from the left and print
Remove 2 chars from the left and print
...
Remove string length - 1 chars from the left and print
The above is easy to implement using two nested for-loops. Like:
int main()
{
char str[] = "123456";
size_t len = strlen(str);
size_t i, j;
for (i = 0; i < len; i++) // i is number of chars to remove (aka not print) from right
{
for (j = 0; j < len-i; j++) // j is number of chars to remove (aka not print) from left
{
size_t z=j;
int p = 0;
while (z < (len - i))
{
printf("%c", str[z]);
z++;
p = 1;
}
if (p) printf("\n");
}
}
return 0;
}
Output:
123456
23456
3456
456
56
6
12345
2345
345
45
5
1234
234
34
4
123
23
3
12
2
1
Now if the input string is "1001" the output of the program is (comments added manually):
1001 // ok
001 // Is this valid? Or should it be 1
01 // Is this valid? Or should it be 1
1 // ok
100 // ok
00 // Is this valid? Or should it be 0
0 // ok
10 // ok
0 // ok but repeated! Is this valid?
1 // ok but repeated! Is this valid?
As you can see there may be a problem with the algorithm, e.g. leading zero and repeated numbers. If that is invalid, you'll have to
keep track of already printed numbers
avoid printing leading zeros
The following assumes that the numbers are read from the input file as strings (null-terminated character arrays) and that those strings are valid representation of base 10 integers, not necessarily in the range of an int, just only digits.
Skip the leading zeroes. I assume that a string like "0042", if not rejected, should be interpreted as the number 42, so that the output should be only 4 and 2, without any 0. strspn could be used here.
Find the length (len) of the remaining string, if it's less then two characters, return.
Loop from 1 (included) to len (excluded). That is the number of characters to be removed from the source, let's call it i.
The size of the substrings is sub_length = len - i.
Loop from 0 to i (both included) to consider all the substrings of size sub_length. E.g. from 123 we consider first 12 and 23.
If the first character of the substring is '0' and its length is greater than 1, skip the following steps, so that e.g. from 1007 we won't print 007 nor 07, only 0 and 7.
Check if the actual substring can be found in the left part of the source string that we have already considered. E.g. given 4545, after having printed 45 and 54 we would find the last 45 in 454 and skip it. A loop with functions like strncmp or memcmp may come in handy, here, more than strstr which requires null-terminated strings as parameters.
If the previous step doesn't find a duplicate, print the substring (with a loop, or using printf with the format specifier "%.*s" as explained here).
This algorithm would produce the following results:
Source: "3457"
345 457 34 45 57 3 4 5 7
Source: "1045"
104 10 45 1 0 4 5
Source: "5454"
545 454 54 45 5 4
Source: "10000"
1000 100 10 1 0
Source: "0042"
4 2

storing multiple values in c language without using arrays [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
have to reverse number and get difference between normal and reverse number.
The input consists of N numbers, where N is an arbitrary positive integer. The first line of the input
contains only a positive integer N. Then follows one or more lines with the N numbers; these numbers
should all be non-negative and may be single or multiple digits. These are the original numbers you need
to generate their N corresponding magic numbers.
i was thinking maybe using a while loop and just doing one input at a time, anyone have any thoughts?
what i have so far
#include <stdio.h>
int reverseInteger();
int generateMagicNumber();
int main()
{
int n,i;
char all;
printf("How many magic numbers do you want");
scanf("%d",&n);
while (i<n){ //
while (n != 0) //reversing number
{
rev = rev * 10;
rev = rev + n%10;
n = n/10;
i++;
all = n;
}
}
}
Assignment 1:
Reverse Number Magic Sequence
Due: Wednesday January 27, 2016 11:59pm EST
A reverse number is a number written in arabic numerals, but where the
order of digits is reversed. The first digit becomes the last and vice
versa. For example, the number 1245 when its digits are reversed it
would become 5421. Note that all the leading zeros are omitted. That
means if the number ends with a zero, the zero is lost by reversing
(e.g. 1200 gives 21). Also note that the reversed number never has any
trailing zeros. Finally, every single digit number (i.e. 0-9) is its
own reverse number. In order to generate a magic number, we reverse a
given original number and store the absolute value of the difference
between the original number and its reversed version. For example,
given the number 476, we will generate the reverse number 674 and then
compute the absolute value of the difference between 476 and 674 to be
198. We then reverse 198 to display the number 891; we call that the magic number!
We need your help to compute the magic numbers of a given sequence.
Your task is to calculate the difference between a given number and
its reverse version, and output the reverse of the difference. Of
course, the result is not unique because any particular number is a
reversed form of several numbers (e.g. 21 could be 12, 120 or 1200
before reversing). Thus we must assume that no zeros were lost by
reversing (e.g. assume that the original number was 12).
Input
The
input consists of N numbers, where N is an arbitrary positive integer.
The first line of the input contains only a positive integer N. Then
follows one or more lines with the N numbers; these numbers should all
be non-negative and may be single or multiple digits. These are the
original numbers you need to generate their N corresponding magic
numbers.
Output
For each original number in the sequence, print
exactly one integer – its magic number. Omit any leading zeros in the
output. On a separate line, output the largest absolute difference
encountered in the sequence. Sample Input
6
24 1 4358 754 305 794
Sample Output
81 0 6714 792 891 792
4176
Specific Requirements: [15 pts]
[ 3 pts] Write a function called reverseInteger, that takes as input an unsigned integer and returns its reversed digits version as an
unsigned integer.
[ 3 pts] Write a function called generateMagicNumber, that takes as input an unsigned integer and return its magic number as described in
the problem.
[ 3 pts] Display the sequence of magic numbers correctly. (shown in the script file)
[ 2 pts] Display the largest absolute difference (shown in the script file)
[ 3 pts] Demonstrate the complete program using a main function capable of processing the input of any sequence and producing its
corresponding output.
[ 1 pt] Compilation on the CS server gcc compiler without errors and warnings.
Failure to properly document your entire code will receive a mark of
zero.
You are to submit the following:
Source code file: assign1.c
Script file demonstrating the compilation and execution : assign1.txt
To generate the script file use the following command from the CS
server:
cp assign1.c assign1.backup
typescript assign1.txt
cc assign1.c
a.out
[test your code here with at least 3 different input test cases in addition to the example given]
exit
[These steps will create a file called assign1.txt. Do not edit its contents - just submit it!]
Hint: This table explains the work done in this example:
Originalnumber
Reverse Absolute difference
Reverse (Magic number)
X Xr |X-Xr| |X-Xr|r
24 42 18 81
1 1 0 0
4358 8534 4176 6714
754 457 297 792
305 503 198 891
794 497 297 792
Note that your program should not use arrays and should be able to
read a sequence of N size, for any value of N (a 32 bit integer). Of
course, memory space optimization should be considered since there is
no need to store all the N numbers in memory all at once at any given
time.
You should read a new number in each iteration of the while loop:
#include <stdio.h>
int reverseInteger();
int generateMagicNumber();
int main() {
int n, i;
char all;
printf("How many magic numbers do you want");
if (scanf("%d", &n) != 1)
return 1;
for (i = 0; i < n; i++) {
int num, temp, rev, magic;
if (scanf("%d", &num) != 1)
return 2;
rev = 0;
temp = num;
while (temp != 0) { //reversing number
rev = rev * 10;
rev = rev + temp % 10;
temp = temp / 10;
}
if (rev < num)
magic = num - rev;
else
magic = rev - num;
printf("%d ", magic);
}
printf("\n");
return 0;
}
If you enter all the numbers on one line, the answers will appear on a single line below it.

Fibonacci series using arrays (as long as user input)

I am currently a beginner in programming learning, my professor has instructed me to do a program with the instructions below. However when i wrote my program I did the following to take the input from the user on how long the array should be however because my array size isnt defined it gives me an error but the professor hasnt instructed me to specify a size so im really confused :S
My attempt :
void displayarray(int n){
int i;
int aray[]={0,1};
for (i=0;i<n;i++){
printf("%i", aray[i]);
}
printf("\n");
}
int main()
{ int n;
scanf("%i",&n);
displayarray(n);
getchar();
getchar();
}
The Task assigned:
The Fibonacci numbers are a famous sequence of numbers. They begin with 0 and 1, and then the next value in the sequence is the sum of the previous two values.
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765
(fib[8] is 21 -- remember to start counting from 0!)
Write a program that calculates the Fibonacci sequence.
-Make a function that accepts n, which is the number of integers to generate.
-Declare an array, initialize it with only the first two Fibonacci numbers, then calculate the rest.
-Display the sequence for n=10 and n=20.
-Try generating output for n=50. If anything goes wrong in this step, you don't need to fix it. Just add a comment explaining what happens, and why.
You can calculate all the Fibonacci sequence by only using a 3 lenght array. Initialize the first two elements of the array with the two first numbers of the Fibonacci sequence (0 and 1) and then, with these two values, calculate the third number of the sequence.
int f[3];
f[0] = 0;
f[1] = 1;
f[2] = f[0] + f[1]
Try to figure out what to do in the for loop to calculate the Fibonacci number for any integer n.
You can use "malloc()" or "calloc()" function to allocate array of given size.
You need to declare it like
int *array;
array = malloc(n, sizeof(int));
// do something
free(array)

why my program isn't showing correct result?

I wrote the following code for
this
Given an integer number, Write a C program that displays the number as follows:
First line : all digits
Second line : all digits except first digit
Third line: all except first two digits
last line : the last digit
For eg.,
the number 5678 will be displayed as:
5 6 7 8
6 7 8
7 8
8
=>
#include<stdio.h>
#include<math.h>
main()
{
long int x,y,n,z,i=1;
printf("enter no. of digits=");
scanf("%d",&n);
printf("x=");
scanf("%d",&x);
while(i<=n)
{
y=x/pow(10,i);
z=y*pow(10,i);
printf("%d\n",(x-z));
i++;
}
}
The code works(if we ignore the formatting) but does some rounding of and stuff fr some output values ...don't know why??
There are solutions using array and all...but whts wrong with this one??
I'm assuming by "some values" with problems, you're referring to values that have zeroes in them, such as input like 50345, which will print:
50345
345
345
45
5
rather than:
50345
0345
345
45
5
The problem is that the integer representation of numerical values does not acknowledge leading zeroes as being a unique integer value.
If you must print the values, including leading zeroes, you're going to have to treat your number like a token or string, meaning that a value that has leading zeroes is a unique string value from the version without leading zeroes. This is why the array-versions, which treat the numeral value like a string, work, and your current version does not when presented with this type of input case.
The rounding off you are seeing could be because of the use of int as data type for all the variables. So something like (5/10) would be rounded to 0 and not 0.5.
#include<stdio.h>
#include<math.h>
main()
{
int num, count=0, x,no;
printf("Enter a number\n");
scanf("%d",&num);
no=num;
printf("The number you entered is:\n %d\n",num);
while(num){
num=num/10;
count++;
}
for(;count>1;count--){
x=pow(10,count-1);
printf("%d\n",no%x);
}
}
#include <stdio.h>
#include<conio.h>
void main()
{
int number,i=0;
int digits[8];
scanf("%d"&number);
while(number!=0)
{
digits[i]=numder%10;
number=number/10;
i++
}
for(i=i-1;i>=0;i--){
for(j=i;j>=0;j--){
printf("%d ",digits[j]);
}
printf("\n"):
}
}

Write a program that sums the sequence of integers, as well as the smallest in the sequence

Write a program that sums the sequence
of integers as well as the smallest in
the sequence. Assume that the first
integer read with scanf specifies the
number of values remaining to be
entered. For example the sequence
entered:
Input: 5 100 350 400 550 678
Output: The sum of the sequence of
integers is: 2078
Input: 5 40 67 9 13 98
Output: The smallest of the integers
entered is: 9
This is a daily problem I am working on but by looking at this, Isnt 5 the smallest integer? I have no idea how to write this program. Appreciate any help
First thing, the 5 is not considered part of the list, it's the count for the list. Hence it shouldn't be included in the calculations.
Since this is homework, here's the pseudo-code. Your job is to understand the pseudo-code first (run it through your head with sample inputs) then turn this into C code and try to get it compiling and running successfully (with those same sample inputs).
I would suggest the sample input of "2 7 3" (two items, those being 7 and 3) as a good start point since it's small and the sum will be 10, smallest 3.
If you've tried to do that for more than a day, then post your code into this question as an edit and we'll see what we can do to help you out.
get a number into quantity
set sum to zero
loop varying index from 1 to quantity
get a number into value
add value to sum
if index is 1
set smallest to value
else
if value is less than smallest
set smallest to value
endif
endif
endloop
output "The sum of the sequence of integers is: ", sum
output "The smallest of the integers entered is: ", smallest
Stack Overflow seems to be divided into three camps, those that will just give you the code, those that will tell you to push off and do your own homework and those, like me, who would rather see you educated - by the time you hit the workforce, I hope to be retired so you won't be competing with me :-).
And before anyone picks holes in my algorithm, this is for education. I've left at least one gotcha in it to help train the guy - there may be others and I will claim I put them there intentionally to test him :-).
Update:
Robert, after your (very good) attempt which I've already commented on, this is how I'd modify your code to do the task (hand yours in of course, not mine). You can hopefully see how my comments modify the code to reach this solution:
#include <stdio.h>
int main (int argCount, char *argVal[]) {
int i; // General purpose counter.
int smallNum; // Holds the smallest number.
int numSum; // Holds the sum of all numbers.
int currentNum; // Holds the current number.
int numCount; // Holds the count of numbers.
// Get count of numbers and make sure it's in range 1 through 50.
printf ("How many numbers will be entered (max 50)? ");
scanf ("%d", &numCount);
if ((numCount < 1) || (numCount > 50)) {
printf ("Invalid count of %d.\n", numCount);
return 1;
}
printf("\nEnter %d numbers then press enter after each entry:\n",
numCount);
// Set initial sum to zero, numbers will be added to this.
numSum = 0;
// Loop, getting and processing all numbers.
for (i = 0; i < numCount; i++) {
// Get the number.
printf("%2d> ", i+1);
scanf("%d", &currentNum);
// Add the number to sum.
numSum += currentNum;
// First number entered is always lowest.
if (i == 0) {
smallNum = currentNum;
} else {
// Replace if current is smaller.
if (currentNum < smallNum) {
smallNum = currentNum;
}
}
}
// Output results.
printf ("The sum of the numbers is: %d\n", numSum);
printf ("The smallest number is: %d\n", smallNum);
return 0;
}
And here is the output from your sample data:
pax> ./qq
How many numbers will be entered (max 50)? 5
Enter 5 numbers then press enter after each entry:
1> 100
2> 350
3> 400
4> 550
5> 678
The sum of the numbers is: 2078
The smallest number is: 100
pax> ./qq
How many numbers will be entered (max 50)? 5
Enter 5 numbers then press enter after each entry:
1> 40
2> 67
3> 9
4> 13
5> 98
The sum of the numbers is: 227
The smallest number is: 9
pax> ./qq
How many numbers will be entered (max 50)? 0
Invalid count of 0.
[fury]$ ./qq
How many numbers will be entered (max 50)? 51
Invalid count of 51.
By the way, make sure you always add comments to your code. Educators love that sort of stuff. So do developers that have to try to understand your code 10 years into the future.
Read:
Assume that the first integer read
with scanf specifies the number of
values remaining to be entered
so it's not part of the sequence...
for the rest, it's your homework (and C...)
No. 5 is the number of integers you have to read into the list.
Jeebus, I'm not doing your homework for you, but...
Have you stopped to scratch this out on paper and work out how it should work? Write some pseudo-code and then transcribe to real code. I'd have thought:
Read integer
Loop that many times
** Read more integers
** Add
** Find Smallest
IF you're in C look at INT_MAX - that will help out finding the smallest integer.
Since the list of integers is variable, I'd be tempted to use strtok to split the string up into individual strings (separate by space) and then atoi to convert each number and sum or find minimum on the fly.
-Adam
First you read the number of values (ie. 5), then create an array of int of 5 elements, read the rest of the input, split them and put them in the array (after converting them to integers).
Then do a loop on the array to get the sum of to find the smallest value.
Hope that helps
wasn[']t looking for you guys to do the work
Cool. People tend to take offense when you dump the problem text at them and the problem text is phrased in an imperative form ("do this! write that! etc.").
You may want to say something like "I'm stuck with a homework problem. Here's the problem: write a [...]. I don't understand why [...]."
#include <stdio.h>
main ()
{
int num1, num2, num3, num4, num5, num6, i;
int smallestnumber=0;
int sum=0;
int numbers[50];
int count;
num1 = 0;
num2 = 0;
num3 = 0;
num4 = 0;
num5 = 0;
num6 = 0;
printf("How many numbers will be entered (max 50)? ");
scanf("%d", &count);
printf("\nEnter %d numbers then press enter after each entry: \n", count);
for (i=0; i < count; i++) {
printf("%2d> ", i+1);
scanf("%d", &numbers[i]);
sum += numbers[i];
}
smallestnumber = numbers[0];
for (i=0; i < count; i++) {
if ( numbers[i] < smallestnumber)
{
smallestnumber = numbers[i];
}
}
printf("the sum of the numbers is: %d\n", sum);
printf("The smallest number is: %d", smallestnumber);
}

Resources