Presentation is loading. Please wait.

Presentation is loading. Please wait.

12/06/2016 12:01:41 CSC Alliance — 1 Kimera Richard Phone: 0701 437989 INSTITUTE OF COMPUTER SCIENCE DEPARTMENT.

Similar presentations


Presentation on theme: "12/06/2016 12:01:41 CSC Alliance — 1 Kimera Richard Phone: 0701 437989 INSTITUTE OF COMPUTER SCIENCE DEPARTMENT."— Presentation transcript:

1 12/06/2016 12:01:41 CSC Alliance — 1 Kimera Richard E-mail: rkimera@must.ac.ugrkimera@must.ac.ug Phone: 0701 437989 INSTITUTE OF COMPUTER SCIENCE DEPARTMENT OF INFORMATION SYSTEMS AND TECHNOLOGY Kimera Richard E-mail: rkimera@must.ac.ugrkimera@must.ac.ug Phone: 0701 437989 INSTITUTE OF COMPUTER SCIENCE DEPARTMENT OF INFORMATION SYSTEMS AND TECHNOLOGY C-PROGRAMMING Basic Types and Formatted I/O Friday 6th March 2015 http://kimrichies.blogspot.com

2 MUST- ICS rkimera@must.ac.ug Variables Variable  A variable is a named data storage location in your computer's memory. By using a variable's name in your program, you are, in effect, referring to the data stored there.  Variable Names  To use Variables, you need to have variable names.  Follow the following rules while writing variable names  The name can contain letters, digits, and the underscore character (_).  The first character of the name must be a letter. The underscore is also a legal first character, but its use is not recommended.  Case matters (that is, upper- and lowercase letters). Thus, the names count and Count refer to two different variables.  C keywords can't be used as variable names. A keyword is a word that is part of the C language.

3 MUST- ICS rkimera@must.ac.ug Examples of variable names  present, hello, y2x3, r2d3,.../* OK */  _1993_tar_return/* OK but don’t */  Hello#there/* illegal */  double/* shouldn’t work */  2fartogo/* illegal */  NOTE: C IS CASE SENSITIVE SO BSC AND Bsc are different

4 MUST- ICS rkimera@must.ac.ug C Variables Names ……. Suggestions regarding variable names  DO: use variable names that are descriptive  DO: adopt and stick to a standard naming convention  sometimes it is useful to do this consistently for the entire software development site  AVOID: variable names starting with an underscore  often used by the operating system and easy to miss  AVOID: using uppercase only variable names  generally these are pre-processor macros (later)

5 MUST- ICS rkimera@must.ac.ug C Basic Datatypes  There are only a few basic data types in C  char:a single byte, capable of holding one character  int: an integer of fixed length, typically reflecting the natural size of integers on the host machine (i.e., 32 or 64 bits)  float:single-precision floating point  double:double precision floating point

6 MUST- ICS rkimera@must.ac.ug C Basic Types A typical 32-bit machine Type KeywordBytesRange character char 1-128...127 integer int 4-2,147,483,648...2,147,438,647 short integer short 2-32768...32367 long integer long 4-2,147,483,648...2,147,438,647 long long integer longlong 8 -9223372036854775808 … 9223372036854775807 unsigned character unsigned char 10...255 unsigned integer unsigned int 20...4,294,967,295 unsigned short integer unsigned short 20...65535 unsigned long integer unsigned long 40...4,294,967,295 single-precision float 41.2E-38...3.4E38 double-precision double 82.2E-308...1.8E308

7 MUST- ICS rkimera@must.ac.ug Example: Variable types //a c program to tell the size of variable types in bytes #include main() { //sizeof() is one of the library functions in C printf( "\nA char is %d bytes", sizeof( char )); printf( "\nAn int is %d bytes", sizeof( int )); printf( "\nA short is %d bytes", sizeof( short )); printf( "\nA long is %d bytes", sizeof( long )); printf( "\nAn unsigned char is %d bytes", sizeof( unsigned char )); printf( "\nAn unsigned int is %d bytes", sizeof( unsigned int )); printf( "\nAn unsigned short is %d bytes", sizeof( unsigned short )); printf( "\nAn unsigned long is %d bytes", sizeof( unsigned long )); printf( "\nA float is %d bytes", sizeof( float )); printf( "\nA double is %d bytes\n", sizeof( double )); return 0; }

8 MUST- ICS rkimera@must.ac.ug Variable declaration  A variable is only used after declaration, this tells the compiler about the name and type.  The compiler generates an error if you use a variable name that is not declared.  Variables are declared within the main() function.  Variable declaration syntax 1  Typename variableName; int count, number, start; /* three integer variables */ float percent, total; /* two float variables */ int x=3; /*declaration and initialization*/ - Initialization is the assignment of a first value to a variable

9 MUST- ICS rkimera@must.ac.ug Typedef keyword  The typedef keyword is used to create a new name for an existing data type. In effect, typedef creates a synonym. For example, the statement typedef int integer;  creates integer as a synonym for int. You then can use integer to define variables of type int, as in this example: integer count;  Note that typedef doesn't create a new data type; it only lets you use a different name for a predefined data type. The  most common use of typedef concerns aggregate data types.

10 MUST- ICS rkimera@must.ac.ug Initializing Numeric Variables  When you declare a variable, you instruct the compiler to set aside storage space for the variable. However, the valuestored in that space--the value of the variable--isn't defined. It might be zero, or it might be some random "garbage”value.  variable declaration by using an assignment statement, as in this example: int count; /* Set aside storage space for count */ count = 0; /* Store 0 in count */  (=) sign, which is C's assignment operator  If you write x = 12 in an algebraic statement, you are stating a fact: "x equals 12." In C, however, it means something quite different: "Assign the value 12 to the variable named x."  You can also initialize a variable when it's declared. To do so, follow the variable name in the declaration statement with an equal sign and the desired initial value: int count = 0; double percent = 0.01, taxrate = 28.5;  Be careful not to initialize a variable with a value outside the allowed range. Here are two examples of out-of-range

11 MUST- ICS rkimera@must.ac.ug Constants  Like a variable, a constant is a data storage location used by your program. Unlike a variable, the value stored in a constant can't be changed during program execution.  C has two types of constants, each with its own specific uses. 1.Literal constants: It is a value typed directly whenever its needed e.g int count = 20; float discount = 0.28;  They can also be written using scientific notation (number and exponent) e.g  1.23E2 1.23 times 10 to the 2nd power, or 123  4.08e6 4.08 times 10 to the 6th power, or 4,080,000  0.85e-4 0.85 times 10 to the -4th power, or 0.000085

12 MUST- ICS rkimera@must.ac.ug Example: Literal Constants  A variable declared as a constant cant be changed during program execution  const int count = 100;  const float pi = 3.14159;  const long debt = 12000000, float tax_rate = 0.21;

13 MUST- ICS rkimera@must.ac.ug Constants 2. Symbolic Constants  A symbolic constant is a constant that is represented by a name (symbol) in your program.  Whenever you need the constant's value in your program, you use its name as you would use a variable name.  The actual value of the symbolic constant needs to be entered only once, when it is first defined.  Its advantage is that its easy to reuse a variable e.g PI=22/7 can be defined and easily used in geometry. (circumference = 3.14159 * (2 * radius);)  C has two methods for defining a symbolic constant:  #define directive  const keyword.

14 MUST- ICS rkimera@must.ac.ug Examples: Symbolic Constants  The #define directive is one of C's preprocessor directives, The #define directive is used as follows:  #define CONSTNAME literal  The name of a symbolic constant is in UPPER CASE  To define PI as a constant, u would write;  #define PI 3.14159

15 MUST- ICS rkimera@must.ac.ug Example program using constants /* Demonstrates variables and constants */ #include /* Define a constant to convert from pounds to grams */ #define GRAMS_PER_POUND 454 /* Define a constant for the start of the next century */ const int NEXT_CENTURY = 2000; /* Declare the needed variables */ long weight_in_grams, weight_in_pounds; int year_of_birth, age_in_2000; main() { /* Input data from user */ printf("Enter your weight in pounds: "); scanf("%d", &weight_in_pounds); printf("Enter your year of birth: "); scanf("%d", &year_of_birth); /* Perform conversions */ weight_in_grams = weight_in_pounds * GRAMS_PER_POUND; age_in_2000 = NEXT_CENTURY - year_of_birth; /* Display results on the screen */ printf("\nYour weight in grams = %ld", weight_in_grams); printf("\nIn 2000 you will be %d years old\n", age_in_2000); return 0; }

16 MUST- ICS rkimera@must.ac.ug Formatted Printing with printf ( )  The printf function is used to output information (both data from variables and text) to standard output.  A C library function in the library.  Takes a format string and parameters for output.  printf(format string, arg1, arg2, …);  e.g. printf("The result is %d and %d\n", a, b);  The format string contains:  Literal text: is printed as is without variation  Escaped sequences: special characters preceeded by \  Conversion specifiers: % followed by a single character  Indicates (usually) that a variable is to be printed at this location in the output stream.  The variables to be printed must appear in the parameters to printf following the format string, in the order that they appear in the format string.

17 MUST- ICS rkimera@must.ac.ug Formatted Printing with printf: Conversion Specifiers Specifier Meaning %cSingle character %dSigned decimal integer %x Hexadecimal number %fDecimal floating point number %eFloating point in “scientific notation” %sCharacter string (more on this later) %uUnsigned decimal integer % Just print a % sign %ld, %lldlong, and long long  There must be one conve rsion specifier for each argument being printed out.  Ensure you use the correct specifier for the type of data you are printing.

18 MUST- ICS rkimera@must.ac.ug Formatted Printing with printf (): Escape Sequences: SequenceMeaning \aBell (alert) \bBackspace \nNewline \tHorizontal tab \\Backslash \'Single quote \"Double quotation \xhhASCII char specified by hex digits hh \oooASCII char specified by octal digits ooo

19 MUST- ICS rkimera@must.ac.ug Formatted Printing with printf ( )  An example use of printf #include int main() { int ten=10,x=42; char ch1='o', ch2='f'; printf("%d% %c%c %d is %f\n", ten,ch1,ch2,x, 1.0*x / ten ); return 0; }  What is the output?

20 MUST- ICS rkimera@must.ac.ug Reading Numeric Data with scanf ()  The scanf function is the input equivalent of printf  A C library function in the library  Takes a format string and parameters, much like printf  The format string specifiers are nearly the same as those used in printf  Examples: scanf ("%d", &x); /* reads a decimal integer */ scanf ("%f", &rate); /* reads a floating point value */  The ampersand (&) is used to get the “address” of the variable  All the C function parameters are “passed by value”.  If we used scanf("%d",x) instead, the value of x is passed. As a result, scanf will not know where to put the number it reads.

21 MUST- ICS rkimera@must.ac.ug Reading Numeric Data with scanf ()  Reading more than one variable at a time:  For example: int n1, n2; float f; scanf("%d%d%f",&n1,&n2,&f);  Use white spaces to separate numbers when input. 5 10 20.3  In the format string:  You can use other characters to separate the numbers scanf("value=%d,ratio=%f", &value,&ratio);  You must provide input like: value=27,ratio=0.8

22 MUST- ICS rkimera@must.ac.ug Reading Numeric Data with scanf ()  One tricky point:  If you are reading into a long or a double, you must precede the conversion specifier with an l (a lower case L)  Example: int main() { int x; long y; float a; double b; scanf("%d %ld %f %lf", &x, &y, &a, &b); return 0; }

23 MUST- ICS rkimera@must.ac.ug Type Conversion  C allows for conversions between the basic types, implicitly or explicitly.  Explicit conversion uses the cast operator.  Example 1: int x=10; float y, z=3.14; y=(float) x; /* y=10.0 */ x=(int) z; /* x=3 */ x=(int) (-z); /* x=-3 -- rounded approaching zero */  Example 2: int i; short int j=1000; i=j*j; /* wrong!!! */ i=(int)j * (int)j; /* correct */

24 MUST- ICS rkimera@must.ac.ug Implicit Conversion  If the compiler expects one type at a position, but another type is provided, then implicit conversion occurs.  Conversion during assignments: char c = 'a'; int i; i=c; /* i is assigned the ASCII code of ‘a’ */  Arithmetic conversion – if two operands of a binary operator are not the same type, implicit conversion occurs: int i=5, j=1; float x=1.0, y; y = x / i; /* y = 1.0 / 5.0 */ y = j / i; /* y = 1 / 5 so y = 0 */ y = (float) j / i; /* y = 1.0 / 5 */ /* The cast operator has a higher precedence */

25 MUST- ICS rkimera@must.ac.ug Exercise:  Write a program that requests a user to input the radius of a circle, it calculates and outputs the Area and Circumference. NB: PI should be declared as a constant  Write a program that requests a user to input the radius of a Sphere, it calculates and outputs the Volume and Surface Area. NB: PI should be declared as a constant  Deadline 13 th March 2015, by 8:00am


Download ppt "12/06/2016 12:01:41 CSC Alliance — 1 Kimera Richard Phone: 0701 437989 INSTITUTE OF COMPUTER SCIENCE DEPARTMENT."

Similar presentations


Ads by Google