Frequently Asked Questions - Programming Languages ​​- Programming - HWzone Forums
adplus-dvertising
Skip to content
  • Create an account
  • About Us

    Hello Guest!

     
    Please note - in order to participate in our community, comment and open new discussions, you must join as a registered member.

    Our members enjoy many advantages, including the ability to participate in discussions, enjoy raffles and promotions for members of the site, and receive our weekly content directly by email.

    Do not like being harassed by email? You can register for the site but do not submit your registration to the weekly email updates.

FAQ Programming Languages


schnitzel

Recommended Posts

Welcome to FAQ Programming Languages!

The purpose of this topic is to concentrate common questions that arise among new programmers and the answers to them.

The subject is now under construction, so it is open to all, whether you want to offer new questions or answers, or to discuss existing ones.

Please note: this is not the place to ask just any questions! If you have a general question, open a new topic in the appropriate forum.

Link to content
Share on other sites

I try to random random numbers, but I get the same numbers over and over again. Why?

Introduction - Random Number Generator

The mechanism of creating random numbers on a computer is actually not random - the computer is unable to create truly random numbers. Behind the scenes, the creation of random numbers is usually performed by a mathematical mechanism called LCG. It is a mechanism that is "loaded" by means of an initial number known as a seed, from which, using a mathematical formula, it generates a series of numbers that appear random. Given a known nucleus, this mechanism is deterministic - if both runs of the generated program are loaded in the same nucleus, it will produce exactly the same series of numbers.

At the beginning of the program, the generator must be loaded in any nucleus. For example, in C # and Java loading occurs when the Random object is created, and in C / C ++ the load is performed when the srand function is called. Usually the kernel is produced from the clock (so each run of the program will generate a different set of numbers), but you can also move a Random constructor or a srand function to a kernel as desired.

Why do we get the same numbers?

A common mistake is to initialize the random number mechanism again and again, each time we want to get a new random number. For example, this code (in Java) will cause an error (instead of printing 10 random numbers between 1 and 10, it will print the same number 10 times):

for (int i = 0; i <10; i ++) {
Random rnd = new Random ();
int x = rnd.nextInt (10) + 1;
system.out.println (x);
}

Each iteration of the loop produces a new Random object, loaded again from the clock. Since the time is not enough to switch between iterations, then each time the generator is loaded from the same time, and therefore produced the same series of numbers. The printed value is always the first number in this series.

(Note: The random number generator always produces an integer series between 0 and any set M. To take a number between 0 and n, you must take the next number from the series and make modulo n in certain languages ​​such as C, In Java function (nextInt (n already does this for us.)

How do you solve the problem?

We must ensure that the generator is loaded only once. For example, in Java we must make sure that the program has only one random object, and each time a random number is required, use this object. Following the above example, in order for the code to work, the following correction should be made:

Random rnd = new Random ();
for (int i = 0; i <10; i ++) {
int x = rnd.nextInt (10) + 1;
system.out.println (x);
}

This ensures that the rnd object is created only once. Alternatively, you can ensure that there is only another Random object by using a template Singleton Or by having this object be a static field of any class.

Similarly, C / C ++ needs to worry about calling the srand function only once, at the beginning of the program.

Link to content
Share on other sites

How do you make sure that the window does not close when the program is finished?

In console programs (ie, those running in a black text window rather than a graphic window), usually when the program is finished, the window closes itself and you can not see what was printed on the screen. In order to prevent closing, we have to make sure to pause the window until the program until the user wants to close it.

The simplest way to do this is by requesting input from the user, in any other programming language (in all languages ​​the code should be placed at the end of the main function, before the return command if there is one):

#C

Console.ReadKey ();

The function waits until the user presses the keyboard.

C ++

std :: cin.get ();

(Include iostream)

C

getchar ();

(Have to include to stdio.h)

In both languages ​​the function reads the next character from the input. Note that the input will switch to the program only when the user presses Enter (as opposed to the example of #C, where each key is sufficient). Because C + + contains C, the C method will actually work in it.

I was told that it is possible in C to use the getch function but call the system ("PAUSE", is it true?

Technically yes, but not worthwhile. The getch function works as in the example of #C. The system function actually calls an external operating system command (which can run any program on the computer), and actually calls the pause command of the command window.

So why not?

Because the getch function is not part of the C standard, and theoretically it will not work on any compiler. Similarly, the pause command will work only in Dos and Windows environments, not on other operating systems (such as Linux).

Therefore, using these methods will reduce the portability of the code. There's no problem using them, but it's a bad habit to avoid.

I tried what you suggested in C and it still does not work! The program closes immediately!

Explanation: The input to the program works on a buffer, which is a memory location that stores what the user types. Typing fills the buffer with the characters the user types, and calls to functions such as scanf and getchar output characters from the buffer. If the user types when there is no call to these functions, the buffer fills up without emptying. When reading these functions, they check whether the separator is empty or not. If it is not empty, they take out the input immediately and the program continues to run. If the buffer is empty, the program is paused until the user enters any input. Therefore, if we reach the end of the program when the buffer, for some reason, is not empty, then the program will only read a character from the buffer and not from the keyboard, so it will not be delayed but will end immediately.

The solution is, of course, to worry about resetting the buffer before the call to getchar. Solution (Erroneous!) That many places recommend to use is to add before the getchar the following line of code:

fflush (stdin);

This action, on the face of it, empties the buffer and thus makes it blank before the call to getchar, but the fflush function is well defined by the device only for output files and not input. While in some environments (such as visual c) it will work, in other environments the behavior is unpredictable and therefore not recommended to use this method.

So what is the solution? Usually the buffer each time reads a whole line from the input. So a possible solution is to worry about reading from the input to the end of the current line (or the end of the file) instead of making a single call to getchar, so:

int ch;
while (((ch = getchar ())! = '\ n') && ch! = EOF) {}

In C ++ you can do something similar, using the function ignore:

std :: cin.ignore (INT_MAX, '\ n');

Link to content
Share on other sites

How can a number be broken down into his literature?

Brief - Sample Code

For example, this is a code that calculates the sum of digits in an 1234 number. The code will work in several languages ​​(C / C ++, C #, Java)

int n = 1234;
int d;
int sum = 0;
while (n> 0) {
d = n% 10;
sum + = d;
n = n / 10;
}

At the end of the loop, sum will contain the sum of digits in 1234.

Introduction - division with residual

For those who do not remember account rates, a division with residual is done as follows: Suppose we have a pair of integers a and b (for example, 20 and 6). If we ask "how many times does b enter in a" we get any number q, and some residual r. For example, if a = 20 and b = 6 then b enters 3 times within a (because 6 * 3 = 18) and we remain with the remainder of 2. Then in this case, q = 3 and r = 2.

In other words, it can be said that r is the smallest number to be subtracted from a to divisible by b, and q is the result of this division. Of course, it is possible that r is 0, in a case where a priori divides by q.

The mathematical operations used to calculate these q and r are called division and modulation, which are usually marked by the operators / and% respectively (eg C / C ++, Java and C #). Are marked in other ways (for example, in Pascal they are called DIV and MOD, and in the new Python versions an integer division is indicated by // in place).

So how does the code work?

Assume that we have the number n = 1234. For convenience, take the digits from low to high - that is, let's start with the unity, 4. The unity digit is actually the number that answers the question "How much should be subtracted from 1234 to be divisible by 10", in other words, n% 10. This is the explanation for the line:

 d = n% 10;

The following line adds d to the sum:

 sum + = d;

Of course, we could replace it with any other action that uses d (insert it into an array, print, etc.).

Then, we want to "delete" from n the book 4 to stay with the number 123, and continue reading the digits. When we divide the number by 10, we get 123.4 - but since this is an integer division, the computer rounds the result down and stays with 123. This explains this line:

 n = n / 10;

At each iteration of the loop, we "shorten" n in one digit. When the digits are out, n will be equal to 0, meaning the loop condition will be negative, and the loop will stop.

Link to content
Share on other sites

Why when I divide between two numbers I get the wrong result?

example

Let's say we wrote the following code, which calculates the result of the expression 5 / 2:

int x = 5;
int y = 2;
double z = x / y;
printf ("% lf", z);

The result we would expect to receive is 2.5. However, the result printed on the screen is 2.

explanation

In most programming languages, a division between two types representing integer numbers (such as int, short, and long) will always yield a result that is also an integer. These types are not able to represent fractions, so the result of division is always rounded down, so the result of 5 / 2 is not 2.5, but 2. Although we saved the result in a double-type variable, this save occurs only after the division and round-down operation have been performed.

solution

The numbers must be converted to a type capable of containing fractions לפני Division. In our example, we'll fix the third line:

double z = (double) x / y;

Now, the code will convert the variable x to a double type before partition, so the division will be divided into two real numbers rather than a division between two integers. Note that you do not need to convert y to double, because when you try to divide double by int (or vice versa) then the int is converted to double automatically. If we want to, "just in case" you can convert y to double before dividing,

double z = (double) x / (double) y;

Link to content
Share on other sites

Question about the explanation of random numbers:

Why do two different numbers come out in the following example?

static void Main (string [] args)
{
Random rnd = new Random ();
Console.WriteLine (rnd.Next (10));
Console.WriteLine (rnd.Next (10));

}

Could it be that the nucleus was enough to claim?

If so, why did he suffice here to argue, and in the first example that Schnitzel gave, every random object is loaded in the same nucleus?

Link to content
Share on other sites

The kernel is loaded in the random constructor (ie rnd = new Random). The first call to rnd.Next takes the first number from the series, and the second call to rnd.Next takes the second number of the series.

In the example I gave, we call new Random in each iteration of the loop.

Link to content
Share on other sites

What are Command Line Arguments? How do you use them?

Sometimes we want to pass on more information to the program as soon as it runs. Let's say for example we write a program that can copy a file from place to place. Then we want to be able to pass two arguments to the program - the file name and the place to copy it - similar to the way in which arguments are passed to a function.

The software we write can accept arguments as an array of strings. Let's look at the main function of Java and C # for a moment:

static void main (String [] args)

The args parameter is an array of strings containing the arguments we have passed to the program. For example, it can be used:

static void main (String [] args) {
if (args.Length <2) {
// handle error - not enough arguments
} Else {
String source = args [0];
String destination = args [1];
// rest of the main function
}
}

As you can see, the program checks that the argument list contains at least two arguments. If so, it preserves both variables so that the program can copy the file from one place to another.

In C (and in C ++) the program will look a bit different:

int main (int argc, char * argv []) {
if (argc <3) {
// error - not enough arguments
} Else {
char * source = argv [1];
char * destination = argv [2];
// rest of the main function
}
}

The differences and reasons for them are as follows:

1. Arrays in C do not retain the size of themselves, so the size must be moved as another parameter to the function. This parameter is argc.

2. The first element in argv is always the full name of the program running, so the first argument passed to it is in place of 1 in the array instead of 0, and to check whether two arguments have been passed, check whether argc is at least 3, not 2.

3. The arguments are represented as C-style strings, that is, an array of char, rather than a string that does not exist in C.

How do you determine which arguments are passed to the program?

Run the program by running its run file, followed by the arguments we want to move, separated by spaces. For example, if we want program program.exe to run with abc, 123, and def, then run the program as follows:

program.exe abc 123 def

This can be done from Windows vista startup window vista, From Command line interface, Or from the development environment itself, according to the development environment:

In Visual Studio, right click on the project, click Properties, and in the Debugging tab, type the arguments in the Command Line Arguments text box, or in the C ++ program under the Debugging tab, Arguments.

In Eclipse, click the Run menu, where you can select Run Configurations. In the window that opens, choose the appropriate program on the left, on the right side select the Arguments tab, and then enter the arguments in the appropriate text box.

How do I move an argument that has spaces?

In order to pass to the program the one argument abc def (unlike the two arguments abc and def), it should be wrapped in quotation marks,

program.exe "abc def"

Link to content
Share on other sites

  • 4 months later ...

What's the difference between C ++, C, and C #?

In the early seventies developed a programming language C. This language was revolutionary at the time, and has been used and used to date as the basis for many software, such as operating systems And Linux.

In the early 1980s C ++ was developed as a C language upgrade. The C ++ language is based on C and actually contains it (ie, almost every C code is also valid C ++ code, and can be compiled by a ++ compiler C), and it adds elements of object-oriented programming, such as C, C ++ is still used in many applications, and is one of the most popular languages ​​in the market. A variable named c then the action c + will raise the value of the variable in 1.

In 2001, influenced by Java language, Microsoft created a new language called #C. In spite of the name, the similarity between C and C ++ is relatively small, and is mainly the general syntax. In fact, #C is more like Java than C and C ++.

What's the difference between Visual C ++, Visual Basic, and Visual Studio?

Microsoft, which developed development environments for C in the 1980's, created an integrated development environment for 1993 (Visual C ++, which is designed to develop C ++ programming) and C, which, as stated, supports any C ++ software. -C in an inherent manner). It is important to note that Visual C ++ is not a programming language, but a software designed to write software in C ++. Over the years Microsoft has continued to develop and upgrade Visual C ++.

At the same time, Microsoft has developed a programming language called Visual Basic (VB). This language, based on an old language family called Basic, has added strong capabilities for application development with a graphical user interface in the environment (Hence its name - this is a "visual" language). In addition to being a programming language, Visual Basic is also the name of the development environment (IDE) where Visual Basic software is written. In other words, unlike the C ++ that can be written in many different development environments, the VB language has a unique working environment with the same name, and no other tools have been developed for this language.

The development of Visual Basic (language and work environment) and Visual C ++ (the workspace) continued at the same time, until 1997 Aligned these development environments, along with other development tools, and released Visual Studio.

The latest version of Visual Basic, version number 6, came out in 1998 (along with its own development environment, Visual Studio 6.0). In 2001, Developed the .NET infrastructure. (Dot Net), and a new language called #C. The Visual Studio development environment has been upgraded accordingly (now called Visual Studio .NET). The programming language, Visual Basic, whose development has been discontinued, has been replaced by a new programming language called Visual Basic .NET (VB.NET), which resembles the original Visual Basic (apparently to allow easy transition to the usual developers for the old language) Significantly different from it to support .NET infrastructure. And to easily interface with code written in .NET languages. The others, such as #C. To distinguish between VB and VB.NET, it is customary to call the old language VB6.

Today the commercial version of Visual Studio contains all of the development tools of Visual Studio (Including support for all languages ​​supported by Microsoft, including C #, C ++, and VB.NET). Additionally, Released a free version of Visual Studio called Visual Studio Express. This version is limited and contains partial capabilities. Until 2010, each component could be downloaded separately (ie, to develop C # Express and Visual Basic Express separately in the C # and VB.NET versions), but the 2012 components were grouped together, Full.

* Environment Integrated Development Environment (IDE) is a collection of tools designed to develop software easily - text editing tools, compiler, debugging tools and more - which are usually integrated into one software.

Link to content
Share on other sites

ארכיון

This discussion has been archived and new comments can not be added.

guest
This discussion is locked for new replies.
  • Latest news

  • Buzz-Zone: Everything hot on the net

×
  • Create new ...

At the top of the news:

new on the site