Don't understand this C loop - c

Can anyone explain to me how does this loop works? I understand that the first operator counts its remainder, the second counts its division result, but I can't understand how does it sum them using the loop? Here's the code:
// Calculate the sum of the digits of the number N.
int N, S, Z;
S = 0;
printf("Input N\n");
scanf("%d", &N);
while(N != 0) {
Z = N % 10;
N = N / 10;
S = S + Z;
}
printf("Sum = %d\n", S);

This while loop adds all the digit of your number referred in by N. It add's all the digit by taking remainder of number when divided by 10. And everytime, it eliminates the last digit of the number. So if your number is 326, it will work like:
326 != 0
Z = 6
N = 32
S = 6
32 != 0
Z = 2
N = 3
S = 8
3 != 0
Z = 3
N = 0
S = 11
0 == 0 come out of loop
print value of S i.e. 11

It's basically a sum of digits of an integer number.
Example:
input ==> 1234
output ==> 4+ 3+ 2 + 1 = 10
Code Break down:
Initialize S [sum] to 0.
Loop:
Z = N % 10; , store the remainder of N after %10 into Z.
N = N / 10; , divide the contents on N by 10 and store the result back in N.
S = S + Z;, sum the content of S with the value in Z.
after that, check the modified value of N is 0 or not. If not, continue [1,2,3..)
Suggestion:
Always check the success of scanf("%d", &N);. If by any chance, scanf() fails, your code is trying to access uninitialized variable N, which may very well lead to undefined behaviour.

The loop will execute until the n value become zero. For example
N=123
Then the first time values of the variables is
Z:3 : N:12 : S:3
Second time
Z:2 : N:1 : S:5
Third time
Z:1 : N:0 : S:6
Finally the answer of S will be 3+2+1=6.

Let's for a example take 657:
Z = N % 10; // This line will store 7 in Z
N = N / 10; // this line will convert N to 65
S = S + Z; // and finally this line will add 0+7

Related

Exercise in C with loop statements: Write code to reverse numbers with do-while statement

I have a task (currently studying the loop statement so I'm in the beginner phase)that asks to make a program to reverse an integer number so it must have the do statement .
The output should be (example):
Enter a number: 4568
The reversal is: 8654
Please put in mind that since I'm following my book so far I've studied and know the very basics + selection and loop statements. I have very limited choices so no arrays.
The book suggests to make a do loop to divide repeatedly the number by 10 until it reaches 0 this is what I did so far (code not completed) :
int main(void)
{
int n,x;
printf("Enter a number: ");
scanf("%d", &n);
printf("The reversal is: ");
x = n % 10;
printf("%d",x); /*outputs the last number digit in the first place*/
do{
....
n /= 10; /* for example if I divide the number 56222 by ten the output would come out as
5622 562 56 5*/
....
}while (n!=0);
return 0;
}
I found a way to put the last digit in the first place as you can see but
I'm struggling to figure out how to reverse the rest of the numbers after dividing the number by 10 repeadetly with this very limited choices.
What should I put in the do statement?
Many thanks in advance .
int main(void)
{
int n,x;
printf("Enter a number: ");
scanf("%d", &n);
printf("The reversal is: ");
int rev = 0;
do{
x = n % 10;
rev = rev * 10 + x;
n /= 10;
}while (n!=0);
printf ("%d", rev);
return 0;
}
here you need a new integer rev whose value is 0 initially. Lets take
example of 432
n = 432
when you do x = n % 10 x = 2
so when you do rev = rev * 10 + x rev is 0 and value of rev will be 2
n /= 10 make n = 43
-->so in the next iteration
n = 43
x = n % 10 results in x = 3
rev value now is 2
so rev = rev * 10 + x results in 2 * 10 + 3
so rev = 23
n /= 10 results in n = 4
-->in the last iteration n = 4
x = n % 10 results in x = 4 rev value now is 23
so rev = rev * 10 + x results in 23 * 10 + 4 so rev = 234
n /= 10 results in n = 0
so when you print rev you get the answer 234 reverse of 432

Percentage in-between variables

I have an assignment to write a code that prints out all prime numbers between 1-100. I am looking at different programs to get an idea on what to do and keep running into i.e. "if (x%c == 0)".
Now I can't find out what the "x%c" means. I've looked around a lot and can't find any good answers anywhere. Possibly because of searching for the wrong thing. What exactly does that do in the following code?
#include<stdio.h>
int main()
{
int n, i = 3, count, c;
printf("Enter the number of prime numbers required\n");
scanf("%d",&n);
if ( n >= 1 )
{
printf("First %d prime numbers are :\n",n);
printf("2\n");
}
for ( count = 2 ; count <= n ; )
{
for ( c = 2 ; c <= i - 1 ; c++ )
{
if ( i%c == 0 )
break;
}
if ( c == i )
{
printf("%d\n",i);
count++;
}
i++;
}
return 0;
}
It is the modulo operation.
https://en.wikipedia.org/wiki/Modulo_operation
It is the remainder, if you do a division in integer space.
for example:
3 % 3 = 3 mod 3 = 0
means if you divide 3 by 3 you get one and the remainder is 0.
If the division leaves no remainder the first number is a multiple of the second.
That means it is not a prime (if the number you divide with is not 1 or the same number)
A full example
15 % 2 = 1
15 % 3 = 0
15 is no prime
"percentage in-between variables" is the operator for finding the remainder in C.
For example, if x = 10 and y = 4, then, x % y would be 2.
for ( c = 2 ; c <= i - 1 ; c++ )
{
if ( i%c == 0 )
break;
}
In the code snippet above, we will break out of this loop when a value of c is reached such that i is divisible by c i.e. i when divided by c gives 0 as the remainder.

Perplexing Output of C language program using Turbo C++ 3.0 compiler

Concerning my determination for output.It's 1 40 1 While using C it displays output as 0 41 1 How's that possible?What wrong step I'm going into?
#include<stdio.h>
#include<conio.h>
void main(void)
{
clrscr();
int n,a,b;
n = 400;
a = n % 100; //remainder operation
b = n / 10; //division operation
n = n % 10; //remainder operation
printf("%d %d %d",n++,++b,++a); //post-,pre-,pre- increment used
getch();
}
What your compiler prints is correct. Here is the program flow:
#include<stdio.h>
#include<conio.h>
void main(void)
{
clrscr();
int n,a,b;
n = 400; // n has value 400
a = n % 100; // a has value 0
b = n / 10; // b has value 40
n = n % 10; // n has value 0
// n++ evaluates to 0, afterwards n has the value 1
// ++b evaluates to 41, afterwards b has the value 41
// ++a evaluates to 1, afterwards a has the value 1
printf("%d %d %d",n++,++b,++a);
// Thus, 0 41 1 is printed.
getch();
}
Notice especially that the postfix-incrememnt operator n++ returns the value of n unchanged and then changes n. That's why 0 is printed in the first column.

atoi function in C programming language K&R

I quite don't know what this loop does.
int atoi(char s[])
{
int i, n;
n = 0;
for (i = 0; s[i] >= '0' && s[i] <= '9'; ++i)
n = 10 * n + (s[i] - '0');
return n;
}
This part I don't get:
for (i = 0; s[i] >= '0' && s[i] <= '9'; ++i)
n = 10 * n + (s[i] - '0');
I get the whole for loop inside parentheses, and what s[i] - '0' does.
But I don't get what kind of operation is going on here --> n = 10 * n.
I don't know what n is representing and why is multiplying 10.
I know it's converting string of digits to numeric equivalent, but I just don't get the whole operation there.
But I don't get what kind of operation is going on here --> n = 10 * n
That's just how you build a number digit by digit. It's basically the same as it would work if you were writing a calculator. If I wrote a simple calculator, here's how it would handle the input 547:
Start with 0
5 ==> 0*10 + 5 = 5
4 ==> 5*10 + 4 = 54
7 ==> 54*10 + 7 = 547
Basically, atoi does, the exact same thing, but instead of reading each digit from button presses, it's reading them from a string. Each time you read a new digit, you do n *= 10 to make room for that next digit, which just gets directly added on the end.
n is the digits that has already been processed. For instance, for the string "123", first, the program gets digit 1, convert it to integer and store it in n, and then get the next digit 2, this is where n = 10 * n is useful, the previous 1 is multiplied by 10, and added to the next digit 2, the result is 12, and this is stored as the current n.
The same goes on, when processing 3, the previous stored 12 is multiplied by 10, results in 120 and added to 3, ended as 123 as result.

How to check if a int var contains a specific number

How to check if a int var contains a specific number
I cant find a solution for this. For example: i need to check if the int 457 contains the number 5 somewhere.
Thanks for your help ;)
457 % 10 = 7 *
457 / 10 = 45
45 % 10 = 5 *
45 / 10 = 4
4 % 10 = 4 *
4 / 10 = 0 done
Get it?
Here's a C implementation of the algorithm that my answer implies. It will find any digit in any integer. It is essentially the exact same as Shakti Singh's answer except that it works for negative integers and stops as soon as the digit is found...
const int NUMBER = 457; // This can be any integer
const int DIGIT_TO_FIND = 5; // This can be any digit
int thisNumber = NUMBER >= 0 ? NUMBER : -NUMBER; // ?: => Conditional Operator
int thisDigit;
while (thisNumber != 0)
{
thisDigit = thisNumber % 10; // Always equal to the last digit of thisNumber
thisNumber = thisNumber / 10; // Always equal to thisNumber with the last digit
// chopped off, or 0 if thisNumber is less than 10
if (thisDigit == DIGIT_TO_FIND)
{
printf("%d contains digit %d", NUMBER, DIGIT_TO_FIND);
break;
}
}
Convert it to a string and check if the string contains the character '5'.
int i=457, n=0;
while (i>0)
{
n=i%10;
i=i/10;
if (n == 5)
{
printf("5 is there in the number %d",i);
}
}

Resources