C and C++Post your C and C++ Related Tutorial Here
Notices
You are currently viewing AIOFORUM as a guest which gives you VERY limited access to view most discussions, Applications, Latest Movies & Tutorials and access our other features. By joining our free community you will have access to post topics, communicate privately with other members (PM), respond to polls, upload and Download content and access many other special features. Registration is fast, simple and absolutely free so please, Join our community today!
Function gets can be used to get a single string from the keyboard. Unlike scanf gets will get spaces too. It takes one parameter, a string. Here is the format.
gets( string );
It will continue to store characters in string until the user hits enter. You should probably use this function for reading single strings rather than scanf. To use gets you need the stdio.h header file.
Function itoa is used to convert an integer to a string. It stands for Integer to ASCII, and it is pronounced I to A. This function requires three parameters and does not return anything. Here is the format.
itoa( int_var, string, base );
The first parameter is the integer variable you want to change to a string. Actually, it can also be a constant (an actual number). The second parameter is the character array where the converted number will be stored. This array must have at least one character for each digit in the number plus one more. The extra space is required for the null byte. The last parameter is the base you want the number converted to. Usually you will use ten for this since base ten is how we normally look at numbers. Just type the number of the base you want. If you want base ten, type 10. If you want base two put a 2 in that parameter. If you are not sure about that whole base thing, just use ten.
To use itoa you must include the stdlib.h header file.
The pow function is used to get the results of a number raised to an arbitrary power. On a calculator it looks like this: yx. The pow function takes two parameters, and returns a double. The return value is the result of the first parameter raised to the power of the second parameter. A call to pow might look like this.
answer = pow(3, 4);
The first parameter (3 in this example) is the base number. The second parameter (4) is the exponent. Normally it would look like this 34, three to the fourth. The variable answer should equal 81. Remember that pow returns a double. So, if you use an integer, or even a float to store the return value, you will probably get warnings from the compiler about a possible loss of data. If you use a float you will only loose data if the number of decimal places in the answer is huge! If you use an integer you will loose all decimal places.
To use this function include either math.h or stdlib.h depending o your compiler.
As I said earlier, displaying text is not the only thing printf can do. I mentioned that the \n is called an escape sequence. With escape sequences the actual characters are not shown, only the effect they represent. For example, when you type this,
#include <stdio.h>
int main()
{
printf("I like \n to eat chicken");
return 0;
}
You would get this,
I like
to eat chicken
The space after the \n is not required, that is why the second line is pushed over one space in the display. Incidentally, that is how you use any escape sequence, just slip it in there, where ever you need it. Here is a table to list all the commonly used escape sequences. Sequence Effect
\a Makes the internal speaker beep
\b Backspace ( No erase)
\n New line (like pressing enter)
\r Carriage return (puts cursor at the beginning of the line)
\t Tab
\v Vertical tab (cursor moves down one line)
\\ Backslash
\' Apostrophe
\" Double quotes
\? Question mark
\0 Null byte (that's a zero)
\O Octal numbers (base 8)
\xH Hexadecimal numbers (base 16)
NOTE all those slashes are backslashes! * You may want to take some time and try a few of those out. But we still have not reached the limits of printf yet! It can also be used to display variables (If you are just on the Basics section, you don't need this stuff yet). This is done in a similar fashion to escape sequences, except now they are called conversion characters. Instead of a backslash, you use a percent (%) sign before everything. Like escapes, you put them in where you need them, but there is something extra you must do. After you close the last quote, you put a comma, then the name of the variable you wish to display. It would look like this,
printf("this my variable: %i", var);
And the output you would get (if the value of var was equal to 10) is this,
this is my variable: 10
If you have several variables to display, make sure you put the names, in the same order you placed the conversion characters. Let's say you had three integer variables, a, b, and c. Their values are 1, 2 , and 3 respectively. You would use the printf function like this,
printf("Here they are: %i, %i, %i", a,b,c);
And this should appear on your screen,
Here they are: 1, 2, 3
You can use as many conversion characters in one line as you like but remember to keep their names in order. Here is a table for all the conversion characters Conversion Variable type
Character it displays
%c Single character
%d decimal numbers
%e Floating point in scientific notation
%f Floating point
%lf Double
%Lf Long double
%g Uses either %e or %f, based on which is shorter
%i Integer
%o Unsigned octal integer
%s String of text
%u Unsigned integer
%x Unsigned hexadecimal integer
NOTE %i and %d both display integers, but %d ensures that it will be in decimal (base 10) format.
PRINTING IN FIELDS
When using printf() you can specify how many spaces you want a variable to use, no matter how small it is. The purpose is for formatting your output better. Also, you can specify the precision of a float (how many decimal places you want). Here is how that is done.
#include <stdio.h>
int main()
{
int x = 2;
int y = 1000;
float z = 1.12345;
printf("%3d, %3d, %.2f\n", x,y,z);
return 0;
}
The 3, between the % and the d, means that we want the variable to take at least, 3 spaces. So, when 2 is displayed, it is shown with 2 spaces in front of it. 1000 is still shown in four spaces. When variables are bigger than the field specification, the field size is ignored. The .2 in the middle of the %f, means we want to show 2 decimal places, so the 345 at the end of z are cut off. The output should look like this
2, 1000, 1.12
We could have placed a field specification in the %f too, and that would like this %4.2f That means, we want 2 decimal places, and the variable should take up at least 4 spaces. RETURN VALUE OF PRINTF
Yes, printf actually has a return value. It returns an integer, and the value of that integer is the number of characters it printed. So you could set an integer value equal to printf like this (assuming we declared and integer called count)
count = printf("This is a test");
And the value of count should be 14. Well, there you have it. By the way. If your still in the first couple lessons, and not quit understanding all this, don't worry, there will be more explanation, and plenty of examples later.
Function puts will display a single string of text on its own line. The string can be a variable or a string constant (text in closed in parenthesis). This function has no special formatting capabilities like printf does. Here is the format.
puts("This will appear on it's own line");
//or
puts( string );
Either way will result the string being on its own line. To use puts you need the stdio.h header file.
The rand function is used to get random numbers from the computer. It returns an integer value, but does not take an parameters. It is is used like this:
x = rand();
The value that rand returns is in a range form 0 to (at least) 32,767. This range could be larger depending on the specification in the stdlib.h (standard library) file. Most of the time this range will probably be too large for what you want. For example, if you are writing a program that simulates dice, you probably don't want a roll of 11,713. To set a better range, use the modulus operator (%). It should look like this.
x = rand() % 10;
The modulus operator takes two numbers, and divides them. But rather than giving you the result of that division, it gives you the remainder. So 24 % 10 (read twenty-four mod ten) would result in an answer of 4. The result will always be from 0 (if the numbers divide evenly) and one less than the number on the right. In this case 0-9. In the example, rand returns a number (probably a huge number). Then the modulus operator is used to cut it down to a range of 0 to 9. To change the range to 1 to 10, simply add one the result. To make the range 0 to 10, change the 10 to an 11.
The rand function gets numbers from your computers random number generator. The random number generator needs to be set up in order to work properly. You do this with the srand function. That function should be called before rand is ever used. If you forget to do that you may find that you are getting the same "random" numbers every time!
To use the rand function you must include the stdlib.h file.
TECHNICAL NOTES
*Random numbers from the random number generator are not really random, they are pseudorandom.
*That means they are not really random, but it is close enough.
*The random number generator selects numbers in a uniform distribution from 0 to 1, with a mean average of .5 and a standard deviation of .25.
*I'm not sure why I bothered with that last one.
The scanf function is used to read information from the keyboard. To use scanf you need a place to store the information, and the scanf function itself. Here is the proper format for using scanf.
scanf("%d",&var);
Scanf does not display anything, the contents of the quotes are the conversion character representing the variable you want to store. You must always use the ampersand before the variable name. Of course, the type of the variable you are using to store the input must be the type represented by the conversion character. After you get the input, you may use it however you want. For example,
#include <stdio.h>
int main()
{
int x;
puts("Enter a number");
scanf("%d",&x);
printf("You typed %d \n",x);
return 0;
}
This should give you these results:
Enter a number
5
You typed 5 NOTE: Users must press enter after they type their scanf info.
This is a perfectly good use for scanf. But, if you don't match the conversion character with the variable type, you'll have bad things happen. In fact, your compiler may not even tell you what you did wrong! As was showed in the first lesson on input, scanf can be used to get a string. You should probably take a little time and try using scanf with some if it's other conversion characters.
RETURN VALUE OF SCANF
Like printf, scanf has a return value too. It is also an integer, and the value of that integer is the number of things scanf read. With an integer, called count, already declared, we can do this
count = scanf("%d%d",&x,&y);
Count should equal 2, if it does not, then scanf did not work correctly. Testing this value is often helpful in finding errors. TECHNICAL NOTES
*What's up the ampersand (&) thing in scanf? Scanf needs to know the address of the variables it is using. That is what the ampersand does. When it is put in front of a variable in C, we are saying this is the address of this variable, not the value. The address of a variable is the location of the variable in your computers memory not the value.
*The f in scanf stands for formatted, just like in printf.
The sqrt function finds the square root of a number. It takes one parameter (the number you want the square root of) and returns a double. The return value will be the square root of the parameter. A call to sqrt might look like this.
answer = sqrt( 841 );
Answer should equal 29. And that's how you get a square root. Remember that sqrt returns a double. So, if you use an integer, or even a float to store the return value, you will probably get warnings from the compiler about a possible loss of data. If you use a float you will only loose data if the number of decimal places in the answer is huge! If you use an integer you will loose all decimal places.
To use this function include either math.h or stdlib.h depending o your compiler.
Srand stands for seed random. The srand function is use to set up the random number generator. It does not have a return value, but it does require a parameter. It needs and unsigned int. When srand is called it will use the number passed to it to seed a set of random numbers. To get different random numbers, you must pass srand different values for it's parameter. A call to srand looks like this.
srand( 997 );
To get truly random numbers, we must use a random seed. The most common way to use the srand function is to pass the current system date. The system date can be obtained with the time function. Time will return the current date (down to the microsecond) in the form of a single number. Here is an example.
srand( time(NULL) );
First the time function will be called, and it will return the time, which will then be passed as a parameter to the srand function. You need to use this function call before you use the rand function. To use the srand function you must include stdlib.h. To use the time function you need to include time.h TECHNICAL NOTES
*See the technical notes section of the rand page for a brief discussion of random number generators.
The strcat function (string concatenate) takes two strings and combines them into one. It takes two parameters, both strings. The second string gets stuck on the end of the first string. You need to be sure you have enough room in the first string to hold itself, plus the second string. The format looks like this.
strcat( start, end );
Start and end are both strings. End can be a string constant (text in double quotes). When strcat is done, start will have end pasted to the end of it. Here is a real example.
//start = "Hi, "
//end = "Mom!"
strcat( start, end );
The results would be that start would equal "Hi, Mom!", and end would still equal "Mom!." For strcat to work you must include the string.h header file.
TECHNICAL NOTES
*Concatenate - "Kon-Kat-un-ate" to string things together.