Converting simple C# statements to pseudocode - c#

I'm still a C# newbie and trying to fully understand some given code . Can any C# wizards explain or convert the following into 'pseudocode'?
_index = (Mathf.Max(0, _index+1))%_filenames.Count;
and
_movieLoadIndex = (_movieLoadIndex + 1)%2;

Mathf.Max takes the largest of 2 numbers, so take the largest between 0 and index+1 (basically take index+1, and make sure it's at least 0) and modulo it by the count of filenames (modulo takes the remainder of a division, so 10%4 = 2 because 10/4 = 2 and 2 remains)
Same concept for the second line, add 1 to moveLoadIndex and take the remainder of it divided by 2
This looks like code that needs documenting.

Related

How to divide two entered numbers in C#? [duplicate]

This question already has answers here:
How can I divide two integers to get a double?
(9 answers)
Closed 28 days ago.
`This is my second week of my first Computer Science class so I apologize for what is a very basic question:
"Design and implement a program that asks the user to enter the number of programming majors and the total number of students in a class. The program should display that percentage of the class that is majoring in programming. "
I've spent about four hours on this now and I thought I was getting there using past problems I've solved and changing up the coding but this is what I have and it just gives me zero for an answer no matter what.
Any help would be greatly appreciated!
https://dotnetfiddle.net/P6onoF
Is the code I am using
I just get zero for an answer no matter what I enter`
Right.
You shouldn't be asking these questions here because the whole point of going to school is to actually learn it instead of asking the solution, BUT, been there, done that... so here we go :D
There's a couple of things you're doing wrong.
integers "don't divide" (they do, but they sort of don't), you won't get decimal values from them so 1 divided by 2 is 0 although mathematically is 0.5.
If you're gonna use int you need to cast the final to a double, you're using int total = programmingMajors/studentsTotal; so this is an integer. If you have a total of 10 students, with 5 majors. 5/10 = 0.5 with decimals, 0 in integer. Change it to (double)majors/total and you'll have the 0.5 you need.
You're not really getting the percentage of the students just dividing the value. To get the percentage you need to use rule of three.
If 1000 students are 100% of the students, X majors are Y% of them.
e.g. 1000 students. 50 majors.
1000 students = 100 percent.
50 students = X
1000x = 100 * 50
1000x = 5000
x = 5000 / 1000
x = 5
In one single line would be var result = (100 * majors) / total
When using types such as int, doubles and decimals always check their range. Use this microsoft ref. After changing to double and use rule of three.
I ended up not showing how to do it in your code.
// just change the last line to this.
Console.WriteLine("The percent is: " + (100 * programmingMajors) / studentsTotal);
I would suggest write the formula out on a piece of paper first so one has an idea of what one is trying to code.
Also, as mentioned integer values do not have a decimal place, so consider using a different data type such as 'double'.
Also, in terms of display, there is an output formatter 'P' which can be used to format numbers as a percentage.

C# Decimal To Octal

There have been many questions but i can't seem to find the why in the answers. It's usually: no, replace this with this or this should work.
My task is to create a program that asks the user to input a 3 digit positive integer (decimal) that converts it to octal.
For example, on paper: To convert the number 112 to octal. (8 is the base number for octal.)
These are the steps you would take:
112 / 8 = 14 remainder = 0
14 / 8 = 1 remainder = 6
1 / 8 = 0 remainder = 1
Remainder from bottom to up is the octal number that represents 112 in decimal.
So the octal number for 112 is 160.
I found the following program on the internet but i don't understand it fully.
The comments in the program are mine. Could anyone explain it to me please?
//declaration and initialization of variables but why is there an array?
int decimalNumber, quotient, i = 1, j;
int[] octalNumber = new int[100];
//input
Console.WriteLine("Enter a Decimal Number :");
decimalNumber = int.Parse(Console.ReadLine());
quotient = decimalNumber;
//as long as quotient is not equal to 0, statement will run
while (quotient != 0)
{
//this is how the remainder is calculated but it is then put in an array + 1, i don't understand this.
octalNumber[i++] = quotient % 8;
//divide the number given by the user with the octal base number
quotient = quotient / 8;
}
Console.Write("Equivalent Octal Number is ");
//i don't understand the code below here aswell.
for (j = i - 1; j > 0; j--)
Console.Write(octalNumber[j]);
Console.Read();
Any help is truly appreciated.
The first thing to understand is: this is a terrible way to solve this problem. The code is full of odd choices; it looks like someone took a bad C solution of this problem and translated it to C# without applying careful thought or using good practices. If you are trying to learn how to understand crappy code you find on the internet, this is a great example. If you are trying to learn how to design good code, this is a great example of what not to do.
//declaration and initialization of variables but why is there an array?
There's an array because we wish to store all the octal digits, and an array is a convenient mechanism for storing a number of data of the same type.
But we could ask some more pertinent questions here:
Why of size 100? It's not wrong, but that's enormously larger than necessary. What thought process led to 100 being chosen? Why wasn't that thought process documented anywhere?
Why an array of int? We're outputting text, which is a sequence of chars. It would seem more natural to have a bunch of chars.
Why an array? Since we are building a first-in-last-out data structure, a stack seems more appropriate. Or why not simply accumulate a string? That's inefficient if the string is large, but an octal string from a 32 bit integer is never large!
Why does the program produce output to the console? Surely a better factored program would have a method that takes an int and returns an octal string, which can then be printed.
Why do some of the variables have descriptive names and some have undescriptive names? Is the author of the code deliberately trying to confuse the reader? Or did they simply not think about it very carefully?
Why does i - apparently the current index into the array -- start at one?! This is simply bizarre. Arrays start at zero in C#.
What happens if you type in a negative number? Try it!
What happens if you type in zero?
We then go on to:
decimalNumber = int.Parse(Console.ReadLine());
This code presumes that the typed-in text is a legal integer, which is not guaranteed. So this program can crash. TryParse should be used, and the failure mode should be handled.
// this is how the remainder is calculated but it is
// then put in an array + 1, i don't understand this.
octalNumber[i++] = quotient % 8;
The author of the code thinks they are being clever. This is too much cleverness. Rewrite the code in your head to how it should have been implemented in the first place. First, rename i to currentIndex. Next, produce one side effect per statement, not two:
while (quotient != 0)
{
octalNumber[currentIndex] = quotient % 8;
currentIndex += 1;
quotient = quotient / 8;
}
Now it should be clear what is going on.
// I don't understand the code below here as well.
for (j = i - 1; j > 0; j--)
Console.Write(octalNumber[j]);
Do a little example. Suppose the number is 14, which is 16 in octal. First time through the loop we put 6 in slot 1. Next time through, we put 1 in slot 2. So the array is {0, 6, 1, 0, 0, 0, 0 ... } and i is 3. We wish to output 16. So we loop j from i-1 to 1, and print out 1 then 6.
So, exercise for you: write this program again, this time using the conventions of a well-designed C# program. Put your attempt on the code review site and people will be happy to give you tips on how to improve it.
This is already built into .NET, Convert.ToString already does this.
In your code, just after you have decimalNumber = int.Parse(...) you can do this:
Console.WriteLine(Convert.ToString(decimalNumber, 8));
Console.Read();
and then remove the rest of the code.
Now, if you're not asking how to do octal conversion in .NET but actually how that code works, here's how it works:
This loop does the heavy lifting:
1 while (quotient != 0)
{
//this is how the remainder is calculated but it is then put in an array + 1, i don't understand this.
2 octalNumber[i++] = quotient % 8;
//divide the number given by the user with the octal base number
3 quotient = quotient / 8;
}
I added some numbers to the lines to make it easier writing a description.
Basically, the loop does this (lines above correspond to points below).
As long as we have a number to convert (ie. we're still not done), loop.
Figure out the least significant digit, this is the remainder after dividing by 8, which is handled by the remainder operator, %, store this digit into the array in the next position.
Divide by 8 to get rid of that least significant digit and move all the other digits one up
Then loop back.
However, since we essentially found all the digits from the rightmost side towards the left, the loop at the end writes them back out in their opposite order.
As an exercise to the reader, try to figure out how the code in the question behaves if you:
Input a negative number
Input 0
(hint, it doesn't behave correctly but Convert.ToString does)
An array is used because they are calculating each digit every interation of the while loop. (e.g.) {0, 6, 1}
The last part of the program is printing each digit out, starting with the last item in the array and moving to the first. in this case it would print out:
160

I need help understanding the modulo operator

I was trying to recreate my C++ factor program from a few years ago in my new language C#. All I could remember is that it possibly involved a modulo, and possibly didn't. I knew that it involved at least one for and if statement. However, when I started trying to recreate it I kept getting nothing near what should be. I thought it had something to do with me not understanding loops, but it turns out I understand loops just fine. What I don't understand is how to use the modulo when performing math operations.
for instance what am I doing when I say something like:
(ignore that it might not actually work, it's just an example)
if(12 % 2 == 0)
{
Console.WriteLine("I don't understand.");
}
This kind of thing I don't quite have a grasp of yet. I realize that it is taking the remainder, and that's all I can grasp, not how it's actually used in real programming. I managed to get my factor program to work in C# after a bit of thinking and tinkering, it again doesn't mean I understand this operator or its uses. I no longer have access to the old C++ file.
The % (modulo) operator yields the remainder from the division. In your example the remainder is equal to 0 and the if evaluates to true (0 == 0). A classic example is when it's used to see if a number is even or not.
if (number % 2 == 0) {
// even
} else {
// odd
}
Think of modulo like a circle with a pointer (spinner), easiest example is a clock.
Notice how at the top it is zero.
The modulo function maps any value to one of those values on the spinner, think of the value to the left of the % as the number of steps around the spinner, and the second value as the number of total steps in the spinner, so we have the following.
0 % 12 = 0
1 % 12 = 1
12 % 12 = 0
13 % 12 = 1
We always start at 0.
So if we go 0 steps around a 12 step spinner we are still at 0, if we go 1 step from zero we are on 1, if we go 12 steps we are back at 0. If we go 13 we go all the way around and end at 1 again.
I hope this helps you visualize it.
It helps when you are using structures like an array, and you want to cycle through them. Imagine you have an array of the days of the week, 7 elements (mon-sunday). You want to always display the day 3 days from the current day. well Today is tuesday, so the array element is days[1], if we want to get the day 3 days from now we do days[1+3]; now this is alright, but what if we are at saturday (days[5]) and want to get 3 days from there? well we have days[5+3] which is an index out of bounds error as our array has only 7 elements (max index of 6) and we tried to access the 8th element.
However, knowing what you know about modulos and spinners now you can do the following:
string threeDaysFromNow = days[(currentDay + 3)%7]; When it goes over the bounds of the array, it wraps around and starts at the beginning again. There are many applications for this. Just remember the visualization of spinners, that is when it clicked in my head.
The modulo operator % returns the remainder of a division operation. For example, where 13 / 5 = 2, 13 % 5 = 3 (using integer math).
It's a common tactic to check a value against % 2 to see if it is even. If it is even, the remainder will be 0, otherwise it will be 1.
As for your specific use of it, you are doing 12 % 2 which is not only 0, but will always be 0. That will always make the if condition 12 % 2 == 0 true, which makes the if rather redundant.
as mentioned, it's commonly used for checking even/odd but also can use it to iterate loops at intervals, or split files into mod chunks. i personally use mod for clock face type problems as my data often navigates a circle.
the register is in mod for example an 8 bit register rolls over at 2^8 so so can force compliance into a register size var = mod(var, 256)
and the last thing i know about mod is that it is used in checksum and random number generation, but i haven't gone into the why for those. at all
An example where you could use this is in indexing arrays in certain for loops. For example, take the simple equation that defines the new pixel value of a resampled image using bicubic interpolation:
where
Don't worry what bicubic interpolation exactly is for the moment, we're just concerned about executing what seems to be two simple for loops: one for index i and one for index j. Note that the vector 'a' is 16 numbers long.
A simple for loop someone would try could be:
int n= 0;
for(int i = 0; i < 4; ++i)
{
for(int j = 0; i < 4; ++j)
{
pxy += a[n] * pow(x,i) * pow(y,j); // p(x,y)
n++; // n = 15 when finished
}
}
Or you could do it in one for loop:
for(int i = 0; i < 16; ++i)
{
int i_new = floor(i / 4.0); // i_new provides indices 0-3 incrementing every 4 iterations of loop
int j_new = i % 4; // j_new is reset to 0 when i is a multiple of 4
pxy += a[i] * pow(x,i_new) * pow(y,j_new); // p(x,y)
}
Printing i_new and j_new in the loop:
i_new j_new
0 0
0 1
0 2
0 3
1 0
1 1
1 2
1 3
2 0
2 1
2 2
2 3
3 0
3 1
3 2
3 3
As you can see, % can be very useful.

Get last (ie endswith) 3 digits of a decimal (.NET)

I may be using Math for evil... But, in a number written as 0.7000123
I need to get the "123" - That is, I need to extract the last 3 digits in the decimal portion of a number. The least significant digits, when the first few are what most people require.
Examples:
0.7500123 -> 123
0.5150111 -> 111
It always starts from digit 5. And yes, I'm storing secret information inside this number, in the part of the decimal that will not affect how the number is used - which is the potentially evil part. But it's still the best way around a certain problem I have.
I'm wondering whether math or string manipulation is the least dodgy way of doing this.
Performance is not an issue, at all, since I'm calling it once.
Can anyone see an easy mathematical way of doing this? eg A combination of Math functions (I've missed) in .NET?
It's a strange request to be sure. But one way to get an int value of the last 3 digits is like so:
int x = (int)((yourNumber * 10000000) % 1000);
I'm going to guess there's a better way to get the information you're looking for that's cleaner, but given what you've asked for, this should work.
First Convert Your number into the String.
string s = num.ToString();
string s1 = s.Substring(s.Length - 3, 3);
Now s1 Contains Last 3 Digits Of the Number
Using modulo will get you the last 3 digits:
var d = 0.7000123m;
d = d * 10000000 % 1000;
d will now hold the value 123.
Try this:
string value= "0.1234567";
string lastthreedigit= value.Substring(value.Length - 3);

Specifically, what does % do in C#?

I have never came across anything that requires me to use it, and when I google what it does nothing comes up.
So, can someone please explain in detail, what does it do?
Its the modulus operator.
See the MSDN Link, although it doesn't have a great example.
It basically gets the remainder, when the first number is divided by the second.
Like 7 % 3 = 1. You can play with this on google.
As MSDN Example says, modding different types (doubles,decimals) results those types.
The most common use is in programs that need to check for an even number:
n % 2 == 0;// if the mod of n by 2 (remainder) is zero then n is even
Specifically like #BenVoigt says modulus actually takes the sign of the dividend.(unlike remainder which takes the sign of the divisor) It seems some languages implement it this way, there is a list here on wikipedia. So C# takes the sign of the dividend.
-7 % 3 = -1//in C#
-6 % 2 = 0// so even checks work ok with negative numbers in C#
But the result from google is 2?
It is the Modulo Operation. Returns the remainder when one integer is divided by another.
It is the modulus operator
http://msdn.microsoft.com/en-us/library/0w4e0fzs.aspx
It lets you know what is left over once the first number has been divided by the second as many times as it can. For example:
5 % 2 = 1
Because 2 can only go into 5, 2 times (4), then all you have is 1 left over.
5 % 2.2 = 0.6
Because 2.2*2 is 4.4 and 5-4.4 is 0.6.

Categories

Resources