Basics of C Language
May 11, 2017 | Author: Niranjana Devi | Category: N/A
Short Description
Download Basics of C Language...
Description
Programming in C
Introduction A Programing Language should be designed to support certain kind of data, such as numbers,characters,strings etc. To get useful output known as information. A program is a set of statements for a specific task, which will be executed in a sequential form. These statements/instructions are formed using certain words and symbols according to the rules known as syntax rules or grammar of the language. Every program must follow accurately the syntax rules supported by the language. The C Character set The characters used to form words,numbers and expressions depend upon the computer on which the program runs. The Characters in C are classified in to four categories. 1. Letters-------------> Ex: A to Z and a to z 2. Digits--------------> Ex: All decimal digits 0 to 9 3. White spaces--------> Ex: Blank space, Horizontal tab, Vertical tab, New line, Form feed 4. Special characters--> Ex:, . ; " ' ! | / \ ~ _ $ ? & ^ * - + < > ( ) [ ] { } % # = @ The C Keywords The C keywords are reserved words by the compiler. All the C keywords have
been assigned fixed meaning. The Keywords cannot be used as variable names because they have been assigned fixed jobs. However, few C compilers allow to construct variable names, which exactly coincides with the keywords. It is suggested not to mix up keywords with variable names. Keywords: auto-----break-----case----char----const----continue----default----do double----else-----enum-----extern-------float--------for-----goto----if int----long----register---return---short---signed----sizeof---static struct----switch----typedef----union---unsigned---void---volatile----while In addition to these standard keywords some more like asm,typeof,huge,interrupt,near,etc. Identifiers Identifiers are names of variables,functions, and arrays. They are user-defined names, consisting of sequence of letters and digits, with the letters as the first character. Lower case letters are preferred. However, the upper case letters are also permitted. The (_) under score symbol can be used as an identifier. Examples:1. #define N 10 2. # define a 15 Here 'N' and 'a' are user-defined identifiers Constants The Constants in C are applicable to the values, which do not change during the execution of a program. There are several types of constants in C. They are 1. Numeric Constants 2. Character Constants Numeric Constants Numeric Constants Classifieds into several categories.They are
* Integer constants
These are the sequence of numbers from 0 to 9 without decimal points or fractional part or any other symbols. It requires minimum two bytes and maximum four bytes. Integer constants could either be positive or negative or maybe zero. The number without a sign is assumed as positive. Example: 50,70,+80,-15 etc. * Real constants
Real constants often as floating point constants. Integer constants are unfit to represent many quantities. Many parameters or quantities are defined not only in integers but also in real numbers. For example length, height, prize, distance etc. are measured in real numbers. Example: 1.0,2.3450,3.14 etc. The real constants can be written in exponential notation,which contains a fractional part and an exponential part. For example, the value 2456.123 can be written as 2.4561Xe+3. The General format of the real number contains mantissa and an exponent. The mantissa is either a real number represented in decimal or an integer.The exponent is an integer number which may be positive or nagative. The letter 'e' separating the mantissa and exponent can be written in lower case or upper case. Character Constants * Single character constants:
A characteer constant is a single character. They are also represented with a single digit or a single special symbol or white space enclosed within a pair of single quote marks. Example: 'a','d','m',etc. * String constants:
String constants are sequence of characters enclosed within a double quote marks. The string may be a combination of all kinds of symbols. Example: "Hello","Sample","Ramana" etc. Variables A variable is a data name used for storing a data value. A variable is a name which is used for storing some value in it. Its value may be changed during the program execution of a program. A variable name may be declared based on the meaning of the operation. Example: height,weight, average, sum, mul etc. Rules for defining variables 1. They must begin with a character without spaces but underscore is permitted. 2. The length of the variable varies from compiler to compiler. Generally most of the compilers support 8 characters excluding extension. However, the ANSI standard recognizes the maximum length of a variable upto 31 characters. 3. The variable should not be a C keyword. 4. The variable names may be a combination of upper and lower characters. For example Sum and sum are not the same. 5. The variable name should not start with a digit. Data Types All C compilers support a variety of data types. This enables the programmer to select the appropriate data type as per the need of the application. Which type of data is storing in a variable is known as data type. Generally data is represented using numbers or characters. The numbers may be integers or real. A C language programmer has to tell the system before-hand, the type of
numbers or characters he is using in his program. These are data types. There are many data types in C language. A C programmer has to use appropriate data type as per his requirement. C language data types can be broadly classified as * Primary data type * Derived data type * User-defined data type All C Compilers accept the following fundamental data types 1. Integer -------------------------------------> int 2. Character ----------------------------------> char 3. Floating Point ------------------------------> float 4. Double precision floating point------------> double 5. Void ---------------------------------------> void The size and range of each data type is given in the below * char -----------------------------------> -128 to 127 * int -----------------------------------> -32768 to +32767 * float ---------------------------------->3.4 e-38 to 3.4 e+38 * double --------------------------------> 1.7 e-308 to 1.7 e+308 Integer Type : Integers are whole numbers with a machine dependent range of values. A good programming language as to support the programmer by giving a control on a range
of numbers and storage space. C has 3 classes of integer storage namely short int, int and long int. All of these data types have signed and unsigned forms. A short int requires half the space than normal integer values. Unsigned numbers are always positive and consume all the bits for the magnitude of the number. The long and unsigned integers are used to declare a longer range of values. Floating Point Types : Floating point number represents a real number with 6 digits precision. Floating point numbers are denoted by the keyword float. When the accuracy of the floating point number is insufficient, we can use the double to define the number. The double is same as float but with longer precision. To extend the precision further we can use long double which consumes 80 bits of memory spaces. Void Type : Using void data type, we can specify the type of a function. It is a good practice to avoid functions that does not return any values to the calling function. Character Type : A single character can be defined as a defined as a character type of data. Characters are usually stored in 8 bits of internal storage. The qualifier signed or unsigned can be explicitly applied to char. While unsigned characters have values between 0 and 255, signed characters have values from –128 to 127.
Data types and their control strings Data Type------------------->Size(bytes)--------->Range--------------------------->Control String Char................................................ 1 ............................... -128 to 127............................................... %c Unsigned Char............................... 1 ............................... 0 to 255...................................................... %c
Short or int................................... 2 ............................. -32,768 to 32,767 .................................... %i or %d Unsigned int ................................. 2 .................................. 0 to 655355............................................... %u Long................................................ 4 ................................. -2147483648 to 2147483647.................. %ld Unsigned long............................... 4 ..................................... 0 to 4294967295................................. %lu Float............................................... 4 .................................... 3.4e-38 to 3.4e+38.................. %f or %g Double.............................................. 8 ................................... 1.7e-308 to 1.7e+308.......................... %lf Long Double......................................... 10 .......................... 3.4e-4932 to 1.1e+4932.................. %lf
ARRAY Array definition Array by definition is a variable that hold multiple elements which has the same data type.
Declaring Arrays We can declare an array by specify its data type, name and the number of elements the array holds between square brackets immediately following the array name. Here is the syntax: view source print?
1.data_type array_name[size]; For example, to declare an integer array which contains 100 elements we can do as follows: view source print?
1.int a[100]; There are some rules on array declaration. The data type can be any valid C data types including structure and union. The array name has to follow the rule of variable and the size of array has to be a positive constant integer. We can access array elements via indexes array_name[index]. Indexes of array starts from 0 not 1 so the highest elements of an array is array_name[size-1].
Initializing Arrays It is like a variable, an array can be initialized. To initialize an array, you provide initializing values which are enclosed within curly braces in the declaration and placed following an equals sign after the array name. Here is an example of initializing an integer array. view source print?
1.int list[5] = {2,1,3,7,8};
Array and Pointer Each array element occupies consecutive memory locations and array name is a pointer that points to the first element. Beside accessing array via index we can use pointer to manipulate array. This program helps you visualize the memory address each array elements and how to access array element using pointer. view source print?
01.#include 02. 03.void main() 04.{ 05. 06. const int size = 5;
07. 08. 09. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29.}
int list[size] = {2,1,3,7,8}; int* plist = list; // print memory address of array elements for(int i = 0; i < size;i++) { printf("list[%d] is in %d\n",i,&list[i]); } // accessing array elements using pointer for(i = 0; i < size;i++) { printf("list[%d] = %d\n",i,*plist); /* increase memory address of pointer so it go to the next element of the array */ plist++; }
Here is the output
list[0] is in 1310568 list[1] is in 1310572 list[2] is in 1310576 list[3] is in 1310580 list[4] is in 1310584 list[0] = 2 list[1] = 1 list[2] = 3 list[3] = 7 list[4] = 8 You can store pointers in an array and in this case we have an array of pointers. This code snippet use an array to store integer pointer. view source print?
1.int *ap[10];
Multidimensional Arrays An array with more than one index value is called a multidimensional array. All the array above is called singledimensional array. To declare a multidimensional array you can do follow syntax view source
print?
1.data_type array_name[][][]; The number of square brackets specifies the dimension of the array. For example to declare two dimensions integer array we can do as follows: view source print?
1.int matrix[3][3]; Initializing Multidimensional Arrays You can initialize an array as a single-dimension array. Here is an example of initialize an two dimensions integer array: view source print?
1.int matrix[3][3] = 2.{ 3. {11,12,13}, 4. {21,22,23}, 5. {32,31,33}, 6.};
C Pointer C pointer is a memory address. When you define a variable for example: view source print?
1.int x = 10; You specify variable name (x), its data type (integer in this example) and its value is 10. The variable x resides in memory with a specified memory address. To get the memory address of variable x, you use operator & before it. This code snippet print memory address of x view source print?
1.printf("memory address of x is %d\n",&x); and in my PC the output is
memory address of x is 1310588 Now you want to access memory address of variable x you have to use pointer. After that you can access and modify the content of memory address which pointer point to. In this case the memory address of x is 1310588 and its content is 10. To declare pointer you use asterisk notation (*) after pointer's data type and before pointer name as follows: view source print?
1.int *px; Now if you want pointer px to points to memory address of variable x, you can use address-of operator (&) as follows: view source print?
1.int *px = &x; After that you can change the content of variable x for example you can increase, decrease x value : view source print?
1.*px += 10; 2.printf("value of x is %d\n",x); 3.*px -= 5; 4.printf("value of x is %d\n",x); and the output indicates that x variable has been change via pointer px.
value of x is 20 value of x is 15 It is noted that the operator (*) is used to dereference and return content of memory address.
In some programming contexts, you need a pointer which you can only change memory address of it but value or change the value of it but memory address. In this cases, you can use const keyword to define a pointer points to a constant integer or a constant pointer points to an integer as follows: view source print?
01.int c = 10; 02.int c2 = 20; 03. 04./* define a pointer and points to an constant integer. 05.pc can point to another integer but you cannot change the 06.content of it */ 07. 08.const int *pc = &c; 09. 10./* pc++; */ /* cause error */ 11. 12.printf("value of pc is %d\n",pc); 13. 14.pc = &c2; 15. 16.printf("value of pc is %d\n",pc); 17. 18./* define a constant pointer and points to an integer. 19.py only can point to y and its memory address cannot be changed 20.you can change its content */ 21. 22.int y = 10; 23.int y2 = 20; 24. 25.int const *py = &y; 26. 27.*py++;/* it is ok */ 28.printf("value of y is %d\n",y); 29. 30./* py = &y2; */ /* cause error */ Here is the output for code snippet
value of pc is 1310580 value of pc is 1310576 value of y is 10
Data Type Data types are used to store various types of data that is processed by program. Data type attaches with variable to determine the number of bytes to be allocate to variable and valid operations which can be performed on that variable. C supports various data types such as character, integer and floating-point types.
Character Data Type C stores character type internally as an integer. Each character has 8 bits so we can have 256 different characters values (0-255). Character set is used to map between an integer value and a character. The most common character set is ASCII. Let take a look at example of using a variable which hold character 'A'. view source print?
01.#include 02. 03.void main() 04.{ 05. char ch = 'A'; 06. printf("%c\n",ch); 07. ch = 65;// using integer representation 08. printf("%c\n",ch); 09. ch = '\x41'; // using hexadecimal representation 10. printf("%c\n",ch); 11. ch = '\101'; // using octal representation 12. printf("%c\n",ch); 13.} Here is the output
A A A A
Integer Data Type Integer data types are used to store numbers and characters. Here is the table of integer data type in various forms: Data Type Memory Allocation Range 7
7
signed char
1 byte
−2 to 2 −1 (−128 to 127)
Unsigned char
1 byte
0 to 2 −1 (0 to 255)
short
2 bytes
−2
Unsigned short
2 bytes
8
15
to 2 16
0 to 2 31
15
−1 (−32768 to 32767)
−1 (0 to 65535) 31
long int
4 bytes
2
int
2 or 4 bytes depending on implementation
Range for 2 or 4 bytes as given above
to 2 −1 (2,147,483,648 to 2,147,483,647)
Floating-point Data Type The floating-point data types are used to represent floating-point numbers. Floating-point data types come in three sizes: float (single precision), double (double precision), and long double (extended precision). The exact meaning of single, double, and extended precision is based on implementation defined. Choosing the right precision for a problem where the choice matters requires understanding of floating point computation.
Floating-point literal Floating-point literal is double by default. You can use the suffix f or F to get a floating-point literal 3.14f or 3.14F
Type Conversion Type conversion occurs when an expression has a mixed data types. At this time, the compiler will try to convert from lower to higher type, because converting from higher to lower may cause loss of precision and value.C has following rules for type conversion.
Integer types are lower than floating-point types.
Signed types are lower than unsigned types.
Short whole-number types are lower than longer types.
The hierarchy of data types is as follows: double, float, long, int, short, char.
So based on those rules, we have general rules for type conversion:
Character and short data are promoted to integer.
Unsigned char and unsigned short are converted to unsigned integer.
If the expression includes unsigned integer and any other data type, the other data type is converted to an unsigned integer and the result will be unsigned integer.
If the expression contains long and any other data type, that data type is converted to long and the result will be long.
Float is promoted to double.
If the expression includes long and unsigned integer data types, the unsigned integer is converted to unsigned long and the result will be unsigned long.
If the mixed expression is of the double data type, the other operand is also converted to double and the result will be double.
If the mixed expression is of the unsigned long data type, then the other operand is also converted to double and the result will be double.
Conversion Type Casting When we want to convert the value of a variable from one type to another we can use type casting. Type casting does not change the actual value of variable. It can be done using a cast operator (unary operator).
VARIABLES Defining Variables A variable is a meaningful name of data storage location in computer memory. When using a variable you refer to memory address of computer.
Naming Variables The name of variable can be called identifier or variable name in a friendly way. It has to follow these rules:
The name can contain letters, digits and the underscore but the first letter has to be a letter or the underscore. Be avoided underscore as the first letter because it can be clashed with standard system variables.
The length of name can be up to 247 characters long in Visual C++ but 31 characters are usually adequate. Keywords cannot be used as a variable name.
Of course, the variable name should be meaningful to the programming context.
Declaring Variables To declare a variable you specify its name and kind of data type it can store. The variable declaration always ends with a semicolon, for example: view source print?
1.int counter; 2.char ch; You can declare variables at any point of your program before using it. The best practice suggests that you should declare your variables closest to their first point of use so the source code is easier to maintain. In C programming language, declaring a variable is also defining a variable.
Initializing Variables You can also initialize a variable when you declare it, for example: view source print?
1.int x = 10; 2.char ch = 'a';
Storage of Variables Each variable has its own lifetime (the length of time the variable can be accessible) or storage duration. When you declare your variable you implicitly assign it a lifetime. Let take a look at this source code example: view source print?
01.#include 02. 03.int global_variable = 10;// global variable
04. 05.void func(); 06. 07.void main() 08.{ 09. int i; 10. // test static variable 11. for(i = 0; i < 5 ; i++) 12. { 13. func(); 14. printf("after %d call \n",i); 15. } 16.} 17.void func() 18.{ 19. static int counter = 0;// static variable 20. counter++; 21. printf("func is called %d time(s)\n",counter); 22. 23. int local_variable = 10; 24. 25.}
Explanations global_variable is a global variable. It is visible and accessible to all functions. It has static life time (static means variable is retained until the program executes). It is suggested that we should avoid using global variable because it is difficult to maintain, and we don’t know exactly the state of global variable because any functions can change it at any time of program execution. The local_variable and i are only existed until function completed. We cannot access it anymore. In this case it is call automatic lifetimes. In case you want a local variable has static lifetimes, you can use static keyword like counter variable in func(). It retains until program executes even when the func() completed.
extern and register keywords You can use extern keyword when declaring a variable or function to imply that the variable is implemented elsewhere and it will be implement later on. register keyword is used when you want a variable which is accessed many time and required fast memory access. Be noted that, declaring a variable with register keyword acts as a directive. It means it does not guarantee the allocation of a register for storing values.
Scope of Variables You can define variable in a block of code which specifies by {and} braces. The variable has the scope inside block it is declared.
Introducing to C structure In some programming contexts, you need to access multiple data types under a single name for easy manipulation; for example you want to refer to address with multiple data like house number, street, zip code, country C supports structure which allows you to wrap one or more variables with different data types. A structure can contain any valid data types like int, char, float even arrays and other structures. Each variable in structure is called a structure member.
Defining structure To define a structure, you can use struct keyword. Here is the common syntax of structure definition: struct struct_name{ structure_member }; The name of structure is followed the rule of variable name. Here is an example of defining address structure: view source print?
1.struct address{ 2. unsigned int house_number; 3. char street_name[50]; 4. int zip_code; 5. char country[50]; 6. }; It contains house number as an positive integer, street name as a string, zip code as an integer and country as a string.
Declaring structure The above example only defines an address structure without create any instance of it. To create or declare a structure you have two ways: The first way is declare a structure follows by structure definition like this : view source print?
1.struct struct_name { 2. structure_member; 3. ... 4. } instance_1,instance_2 instance_n; In the second way you can declare your structure instance at a different location in your source code after structure definition. Here is structure declaration syntax : view source print?
1.struct struct_name instance_1,instance_2 instance_n;
Complex structure Structure can contains arrays or other structures so it is sometimes called complex structure. For example address structure is a complex structure. We can define a complex structure which contains address structure as follows: view source print?
1.struct customer{ 2. char name[50]; 3. structure address billing_addr; 4. structure address shipping_addr; 5. };
Accessing structure member To access structure members we can use dot operator (.) between structure name and structure member name as follows: structure_name.structure_member For example to access street name of structure address we do as follows: view source print?
1.struct address billing_addr; 2.billing_addr.country = "US"; If the structure contains another structure, we can use dot operator to access nested structure and use dot operator again to access variables of nested structure. view source print?
1.struct customer jack; 2.jack.billing_addr.country = "US";
Initializing structure C programming language treats a structure as a custom data type therefore you can initialize a structure like a variable. Here is an example of initialize product structure: view source print?
1.struct product{ 2. char name[50]; 3. double price; 4. } book = { "C programming language",40.5}; In above example, we define product structure, then we declare and initialize book structure with its name and price.
Structure and pointer A structure can contain pointers as structure members and we can create a pointer to a structure as follows: view source print?
1.struct invoice{ 2. char* code; 3. char date[20]; 4. }; 5. 6. struct address billing_addr; 7. struct address *pa = &billing_addr;
Shorthand structure with typedef keyword To make your source code more concise, you can use typedef keyword to create a synonym for a structure. This is an example of using typedef keyword to define address structure so when you want to create an instance of it you can omit the keyword struct view source print?
01.typedef struct{ 02. unsigned int house_number; 03. char street_name[50]; 04. int zip_code; 05. char country[50]; 06. } address; 07. 08. address billing_addr; 09. address shipping_addr;
Copy a structure into another structure One of major advantage of structure is you can copy it with = operator. The syntax as follows view source print?
1.struct_intance1 = struct_intance2 be noted that some old C compilers may not supports structure assignment so you have to assign each member variables one by one.
Structure and sizeof function sizeof is used to get the size of any data types even with any structures. Let's take a look at simple program: view source print?
01.#include 02. 03.typedef struct __address{ 04. int house_number;// 4 bytes 05. char street[50]; // 50 bytes 06. int zip_code; // 4 bytes 07. char country[20];// 20 bytes 08. 09.} address;//78 bytes in total
10. 11.void main() 12.{ 13. // it returns 80 bytes 14. printf("size of address is %d bytes\n",sizeof(address)); 15.} You will never get the size of a structure exactly as you think it must be. The sizeof function returns the size of structure larger than it is because the compiler pads struct members so that each one can be accessed faster without delays. So you should be careful when you read the whole structure from file which were written from other programs.
Source code example of using C structure In this example, we will show you how to use structure to wrap student information and manipulate it by reading information to an array of student structure and print them on to console screen. view source print?
01.#include 02. 03.typedef struct _student{ 04. char name[50]; 05. unsigned int mark; 06.} student; 07. 08. 09. 10.void print_list(student list[], int size); 11.void read_list(student list[], int size); 12. 13. 14. 15.void main(){ 16. 17. const int size = 3; 18. student list[size]; 19. 20. read_list(list,size); 21. 22. print_list(list,size); 23. 24. 25.} 26. 27.void read_list(student list[], int size) 28.{ 29. printf("Please enter the student information:\n"); 30. 31. for(int i = 0; i < size;i++){ 32. printf("\nname:");
33. scanf("%S",&list[i].name); 34. 35. printf("\nmark:"); 36. scanf("%U",&list[i].mark); 37. } 38. 39.} 40. 41.void print_list(student list[], int size){ 42. printf("Students' information:\n"); 43. 44. for(int i = 0; i < size;i++){ 45. printf("\nname: %s, mark: %u",list[i].name,list[i].mark); 46. } 47.} Here is program's output
Please enter the student information: name:Jack mark:5 name:Anna mark:7 name:Harry mark:8 Students' information: name: J, mark: 5 name: A, mark: 7 name: H, mark: 8
OPERATORS Arithmetic Operators C programming language supports almost common arithmetic operator such as +,-,* and modulus operator % C programming language supports almost common arithmetic operator such as +,-,* and modulus operator %. Modulus operator (%) returns the remainder of integer division calculation. The operators have precedence rules which are the same rule in math. Here is a C program demonstrate arithmetic operators: view source print?
01.#include 02./* a program demonstrates C arithmetic operators */ 03.void main(){ 04. int x = 10, y = 20; 05. 06. printf("x = %d\n",x); 07. printf("y = %d\n",y); 08. /* demonstrate = operator + */ 09. y = y + x; 10. printf("y = y + x; y = %d\n",y); 11. 12. /* demonstrate - operator */ 13. y = y - 2; 14. printf("y = y - 2; y = %d\n",y); 15. /* demonstrate * operator */ 16. y = y * 5; 17. printf("y = y * 5; y = %d\n",y); 18. 19. /* demonstrate / operator */ 20. y = y / 5; 21. printf("y = y / 5; y = %d\n",y); 22. 23. /* demonstrate modulus operator % */ 24. int remainder = 0; 25. remainder = y %3; 26. 27. printf("remainder = y %% 3; remainder = %d\n",remainder); 28. 29. /* keep console screen until a key stroke */ 30. char key; 31. scanf(&key); 32.} And here is the output
x = 10 y = 20 y = y + x; y = 30 y = y - 2; y = 28 y = y * 5; y = 140 y = y / 5; y = 28 remainder = y % 3; remainder = 1 C Assignment Operators C assignment operators are used to assigned the value of a variable or expression to a variable. C assignment operators are used to assigned the value of a variable or expression to a variable. The syntax of assignment operators is: view source print?
1.var = expression; 2.var = var; Beside = operator, C programming language supports other short hand format which acts the same assignment operator with additional operator such as +=, -=, *=, /=, %=. view source print?
1.var +=expression; //means 2.var = var + expression; Each assignment operator has a priority and they are evaluated from right to left based on its priority. Here is assignment operator and its priority: =, +=, -=, *=, /=, %=. A simple C program to demonstrate assignment operators: view source print?
01.#include 02./* a program demonstrates C assignment operator */ 03.void main(){ 04. int x = 10; 05. 06. /* demonstrate = operator */ 07. int y = x; 08. printf("y = %d\n",y); 09. 10. /* demonstrate += operator */ 11. y += 10; 12. printf("y += 10;y = %d\n",y); 13. /* demonstrate -= operator */ 14. y -=5;
15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25.}
printf("y -=5;y = %d\n",y); /* demonstrate *= operator */ y *=4; printf("y *=4;y = %d\n",y); /* demonstrate /= operator */ y /=2; printf("y /=2;y = %d\n",y);
Here is the output:
y = 10 y += 10;y = 20 y -=5;y = 15 y *=4;y = 60 y /=2;y = 30 C Bit-wise Operators Bit-wise operators interpret operands as strings of bits. Bit operations are performed on this data to get the bit strings Bitwise operators interpret operands as strings of bits. Bit operations are performed on this data to get the bit strings. These bit strings are then interpreted according to data type. There are six bit operators: bitwise AND(&), bitwise OR(|), bitwise XOR(^), bitwise complement(~), left shift(). We use bitwise operators in some programming contexts because bitwise operations are faster than (+) and (-) operations and significantly faster than (*) and (/) operations. Here is a program which demonstrate C bitwise operator: view source print?
01.#include 02./* a demonstration of C bitwise operators */ 03.void main() 04.{ 05. int d1 = 4,/* 101 */ 06. d2 = 6,/* 110*/ 07. d3; 08. 09. printf("\nd1=%d",d1); 10. printf("\nd2=%d",d2); 11. 12. d3 = d1 & d2; /* 0101 & 0110 = 0100 (=4) */ 13. printf("\n Bitwise AND d1 & d2 = %d",d3); 14. 15. d3 = d1 | d2;/* 0101 | 0110 = 0110 (=6) */ 16. printf("\n Bitwise OR d1 | d2 = %d",d3); 17. 18. d3 = d1 ^ d2;/* 0101 & 0110 = 0010 (=2) */
19. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29.}
printf("\n Bitwise XOR d1 ^ d2 = %d",d3); d3 = ~d1; /* ones complement of 0000 0101 is 1111 1010 (-5) */ printf("\n Ones complement of d1 = %d",d3); d3 = d12;/* 0000 0101 right shift by 2 bits is 0000 0001 */ printf("\n Right shift by 2 bits d1 >> 2 = %d",d3);
And here is the output
d1=4 d2=6 Bitwise AND
d1 & d2 = 4
Bitwise OR d1 | d2 = 6 Bitwise XOR d1 ^ d2 = 2 Ones complement of d1 = -5 Left shift by 2 bits d1 > 2 = 1 C Increment Operators We can use increment operator to increase or decrease the value of variable. C increment operators support in both prefix and postfix form. We can use increment operator to increase or decrease the value of variable. C increment operators support in both prefix and postfix form. Here are syntax of of increment operators: view source print?
1.variable++; 2.variable--; 3.++variable; 4.--variable; Here is the demonstration program: view source print?
01.#include 02./* a program demonstrates C increment operators */ 03.void main(){ 04. int x = 10; 05. int y = 0; 06. printf("x = %d\n",x); 07. 08. /* demonstrate ++ prefix operator */
09. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25. 26. 27.}
y = ++x; printf("y = ++x;y = %d\n",y); /* demonstrate ++ postfix operator */ y = x++; printf("y = x++;y = %d\n",y); /* demonstrate -- prefix operator */ y = --x; printf("y = --x;y = %d\n",y); /* demonstrate -- postfix operator */ y = x--; printf("y = x--;y = %d\n",y); /* keep console screen until a key stroke */ char key; scanf(&key);
And the output is:
x = 10 y = ++x;y = 11 y = x++;y = 11 y = --x;y = 11 y = x--;y = 11 C Logical Operators Logical operators allow us to combine relational operators or logical operators into one Boolean result. C programming language supports the negation (!), logical AND (&&), and logical OR (||). a b a&&b a||b !a True True True
True False
True False False True False False True False True True False False False False True
C Relational Operators Relational operators in C programming language are used in Boolean conditions or expression and returns true or false. view source print?
01.#include 02./* a program demonstrates C relational operators */ 03.
04. 05.void print_bool(bool value){ 06. value == true ? printf("true\n") : printf("false\n"); 07.}; 08. 09.void main(){ 10. int x = 10, y = 20; 11. 12. printf("x = %d\n",x); 13. printf("y = %d\n",y); 14. 15. /* demonstrate == operator */ 16. bool result = (x == y); 17. printf("bool result = (x == y);"); 18. print_bool(result); 19. 20. /* demonstrate != operator */ 21. result = (x != y); 22. printf("bool result = (x != y);"); 23. print_bool(result); 24. 25. /* demonstrate > operator */ 26. result = (x > y); 27. printf("bool result = (x > y);"); 28. print_bool(result); 29. 30. /* demonstrate >= operator */ 31. result = (x >= y); 32. printf("bool result = (x >= y);"); 33. print_bool(result); 34. 35. /* demonstrate < operator */ 36. result = (x < y); 37. printf("bool result = (x < y);"); 38. print_bool(result); 39. 40. /* demonstrate = y);false bool result = (x < y);true bool result = (x y){ 5. printf("x is greater than y"); 6.}else if (x < y){ 7. printf("x is less than y"); 8.}
C Switch Statement The switch statement allows you to select from multiple choices based on a set of fixed values for a given expression. if statement is a basic control flow structure of C programming language. if statement is used when a unit of code need to be executed by a condition true or false. If the condition is true, the code in if block will execute otherwise it does nothing. The if statement syntax is simple as follows: view source print?
1.if(condition){ 2./* unit of code to be executed */ 3.} C programming language forces condition must be a boolean expression or value. if statement has it own scope which defines the range over which condition affects, for example: view source print?
01./* all code in bracket is affects by if condition*/ 02.if(x == y){ 03. x++; 04. y--; 05.} 06./* only expression x++ is affected by if condition*/ 07.if(x == y) 08.x++;
09.y--; In case you want to use both condition of if statement, you can use if-else statement. If the condition of if statement is false the code block in else will be executed. Here is the syntax of if-else statement: view source print?
1.if(condition){ 2. /* code block of if statement */ 3.}else{ 4. /* code block of else statement */ 5.} If we want to use several conditions we can use if-else-if statement. Here are common syntax of if-else-if statement: view source print?
01.if(condition-1){ 02. /* code block if condition-1 03.}else if (condition-2){ 04. /* code block if condition-2 05.}else if (condition-3){ 06. /* code block if condition-3 07.}else{ 08. /* code block all conditions 09.}
is true */ is true */ is true */ above are false */
view source print?
1.if(x == y){ 2. printf("x is equal y"); 3.} 4.else if (x > y){ 5. printf("x is greater than y"); 6.}else if (x < y){ 7. printf("x is less than y"); 8.}
While Loop Statement The while loop is used when you want to execute a block of statements repeatedly with checked condition before making an iteration. A loop statement allows you to execute a statement or block of statements repeatedly. The while loop is used when you want to execute a block of statements repeatedly with checked condition before making an iteration. Here is syntax of while loop statement: view source
print?
1.while (expression) { 2. // statements 3.} This loop executes as long as the given logical expression between parentheses after while is true. When expression is false, execution continues with the statement following the loop block. The expression is checked at the beginning of the loop, so if it is initially false, the loop statement block will not be executed at all. And it is necessary to update loop conditions in loop body to avoid loop forever. If you want to escape loop body when a certain condition meet, you can use break statement Here is a while loop statement demonstration program: view source print?
01.#include 02. 03.void main(){ 04. int x = 10; 05. int i = 0; 06. 07. // using while loop statement 08. while(i < x){ 09. i++; 10. printf("%d\n",i); 11. } 12. 13. 14. // when number 5 found, escape loop body 15. int numberFound= 5; 16. int j = 1; 17. while(j < x){ 18. if(j == numberFound){ 19. printf("number found\n"); 20. break; 21. } 22. printf("%d...keep finding\n",j); 23. j++; 24. } 25. 26.} And here is the output:
1 2 3 4
5 6 7 8 9 10 1...keep finding 2...keep finding 3...keep finding 4...keep finding number found C do-while Loop Statement do while loop statement allows you to execute code block in loop body at least one. do while loop statement allows you to execute code block in loop body at least one. Here is do while loop syntax: view source print?
1.do { 2. // statements 3.} while (expression); Here is an example of using do while loop statement: view source print?
01.#include 02.void main(){ 03. int x = 5; 04. int i = 0; 05. // using do while loop statement 06. do{ 07. i++; 08. printf("%d\n",i); 09. }while(i < x); 10. 11.} The program above print exactly 5 times as indicated in do while loop body
1 2 3 4 5
C for Loop Statement C for loop statement is usually used to execute code block for a specified number of times. do while loop statement allows you to execute code block in loop body at least one. Here is do while loop syntax: view source print?
1.do { 2. // statements 3.} while (expression); Here is an example of using do while loop statement: view source print?
01.#include 02.void main(){ 03. int x = 5; 04. int i = 0; 05. // using do while loop statement 06. do{ 07. i++; 08. printf("%d\n",i); 09. }while(i < x); 10. 11.} The program above print exactly 5 times as indicated in do while loop body
1 2 3 4 5 C break and continue Statements break statement is used to break any type of loop such as while, do while an for loop. break statement terminates the loop body immediately. continue statement is used to break current iteration. break statement is used to break any type of loop such as while, do while an for loop. break statement terminates the loop body immediately. continue statement is used to break current iteration. After continue statement the control returns to the top of the loop test conditions. Here is an example of using break and continue statement: view source print?
01.#include
02.#define SIZE 10 03.void main(){ 04. 05. // demonstration of using break statement 06. 07. int items[SIZE] = {1,3,2,4,5,6,9,7,10,0}; 08. 09. int number_found = 4,i; 10. 11. for(i = 0; i < SIZE;i++){ 12. 13. if(items[i] == number_found){ 14. 15. printf("number found at position %d\n",i); 16. 17. break;// break the loop 18. 19. } 20. printf("finding at position %d\n",i); 21. } 22. 23. // demonstration of using continue statement 24. for(i = 0; i < SIZE;i++){ 25. 26. if(items[i] != number_found){ 27. 28. printf("finding at position %d\n",i); 29. 30. continue;// break current iteration 31. } 32. 33. // print number found and break the loop 34. 35. printf("number found at position %d\n",i); 36. 37. break; 38. } 39. 40.} Here is the output
finding at position 0 finding at position 1 finding at position 2 number found at position 3 finding at position 0 finding at position 1
finding at position 2 number found at position 3
Introduce to dynamic memory allocation In some programming contexts, you want to process data but dont know what size of it is. For example, you read a list of students from file but dont know how many students record there. Yes, you can specify the enough maximum size for the the array but it is not efficient in memory management. C provides you a powerful and flexible way to manage memory allocation at runtime. It is called dynamic memory allocation. Dynamic means you can specify the size of data at runtime. C programming language provides a set of standard functions prototype to allow you to handle memory effectively. With dynamic memory allocation you can allocate and free memory as needed.
Getting to know the size of data Before allocating memory, we need to know the way to identify the size of each data so we can allocate memory correctly. We can get the size of data by using sizeof() function. sizeof() function returns a size_t an unsigned constant integer. For example to get the size of integer type you can do as follows: view source print?
1.sizeof(int); It returns 4 bytes in typical 32 bit machines. Here is a simple program which prints out the size of almost common C data type. view source print?
01.#include 02. 03.typedef struct __address{ 04. int house_number; 05. char street[50]; 06. int zip_code; 07. char country[20]; 08. 09.} address; 10. 11.void main() 12.{ 13. 14. printf("size of int is %d byte(s)\n",sizeof(int)); 15. printf("size of unsigned int is %d byte(s)\n",sizeof(unsigned int)); 16. printf("size of short is %d byte(s)\n",sizeof(short)); 17. printf("size of unsigned short is %d byte(s)\n",sizeof(unsigned short)); 18. printf("size of long is %d byte(s)\n",sizeof(long)); 19. 20. printf("size of char is %d byte(s)\n",sizeof(char)); 21. 22. printf("size of float is %d byte(s)\n",sizeof(float)); 23. printf("size of double is %d byte(s)\n",sizeof(double)); 24.
25. 26.}
printf("size of address is %d byte(s)\n",sizeof(address));
And you can see the output:
size of int is 4 byte(s) size of unsigned int is 4 byte(s) size of short is 2 byte(s) size of unsigned short is 2 byte(s) size of long is 4 byte(s) size of char is 1 byte(s) size of float is 4 byte(s) size of double is 8 byte(s) size of address is 80 byte(s)
Allocating memory We use malloc() function to allocate memory. Here is the function interface: void * malloc(size_t size); malloc function takes size_t as its argument and returns a void pointer. The void pointer is used because it can allocate memory for any type. The malloc function will return NULL if requested memory couldnt be allocated or size argument is equal 0. Here is an example of using malloc function to allocate memory: view source print?
1.int* pi; 2.int size = 5; 3.pi = (int*)malloc(size * sizeof(int)); sizeof(int) return size of integer (4 bytes) and multiply with size which equals 5 so pi pointer now points to the first byte of 5 * 4 = 20 bytes memory block. We can check whether the malloc function allocate memory space is successful or not by checking the return value. view source print?
1.if(pi == NULL) 2.{ 3. fprintf(stderr,"error occurred: out of memory"); 4. exit(EXIT_FAILURE); 5.} Beside malloc function, C also provides two other functions which make convenient ways to allocate memory: view source print?
1.void *calloc(size_t num, size_t size); 2.void *realloc(void *ptr, size_t size);
calloc function not only allocates memory like malloc but also allocates memory for a group of objects which is specified by num argument. realloc function takes in the pointer to the original area of memory to extend and how much the total size of memory should be.
Freeing memory When you use malloc to allocate memory you implicitly get the memory from a dynamic memory pool which is called heap. The heap is limited so you have to deallocate or free the memory you requested when you don't use it in any more. C provides free function to free memory. Here is the function prototype: view source print?
1.void free(void *ptr); You should always use malloc and free as a pair in your program to a void memory leak.
C function Introduce to C function C function is a block of source code which does one or some tasks with specificed purpose.
Define function Function is a block of source code which does one or some tasks with specified purpose.
Benefit of using function
C programming language supports function to provide modularity to the software.
One of major advantage of function is it can be executed as many time as necessary from different points in your program so it helps you avoid duplication of work.
By using function, you can divide complex tasks into smaller manageable tasks and test them independently before using them together.
In software development, function allows sharing responsibility between team members in software development team. The whole team can define a set of standard function interface and implement it effectively.
Structure of function
Function header The general form of function header is: view source print?
1.return_type function_name(parameter_list) Function header consists of three parts:
Data type of return value of function; it can be any legal data type such as int, char, pointer… if the function does not return a value, the return type has to be specified by keyword void.
Function name; function name is a sequence of letters and digits, the first of which is a letter, and where an underscore counts as a letter. The name of a function should meaningful and express what it does, for example bubble_sort,
And a parameter list; parameter passed to function have to be separated by a semicolon, and each parameter has to indicate it data type and parameter name. Function does not require formal parameter so if you don’t pass any parameter to function you can use keyword void.
Here are some examples of function header: view source print?
1./* sort the array of integer a with the 2.specified size and return nothing */ 3.void sort(int a[], int size); 4. 5./* authenticate user by username and password and return true 6.if user is authenticated */ 7.bool authenticate(char*username,char*password)
Function body Function body is the place you write your own source code. All variables declare in function body and parameters in parameter list are local to function or in other word have function scope.
Return statement Return statement returns a value to where it was called. A copy of return value being return is made automatically. A function can have multiple return statements. If the void keyword used, the function don’t need a return statement or using return; the syntax of return statement is return expression;
Using function
How to use the function Before using a function we should declare the function so the compiler has information of function to check and use it correctly. The function implementation has to match the function declaration for all part return data type, function name and parameter list. When you pass the parameter to function, they have to match data type, the order of parameter.
Source code example Here is an example of using function. view source print?
01.#include 02. 03./* functions declaration */ 04. 05.void swap(int *x, int *y); 06. 07. 08. 09.void main() 10.{ 11. int x = 10; 12. int y = 20; 13. 14. printf("x,y before swapping\n"); 15. printf("x = %d\n",x); 16. printf("y = %d\n",y); 17. 18. // using function swap 19. swap(&x,&y); 20. 21. printf("x,y after swapping\n"); 22. printf("x = %d\n",x); 23. printf("y = %d\n",y); 24. 25.} 26. 27. 28./* functions implementation */
29. 30.void swap(int *x, int *y){ 31. int temp = *x; 32. *x = *y; 33. *y = temp; 34.} Here is the output
x,y before swapping x = 10 y = 20 x,y after swapping x = 20 y = 10 Press any key to continue Passing Arguments to Function C supports a wide range of mechanisms to allow you to program functions effectively. In order to write correct function you should know how to pass arguments to it. C supports a wide range of mechanisms to allow you to program functions effectively.
Pass by value With this mechanism, all arguments you pass to function are copied into copy versions and your function work in that copy versions. So parameters does not affects after the function finished.
Pass by pointer In some programming contexts, you want to change arguments you pass to function. In this case, you can use pass by pointer mechanism. Remember that a pointer is a memory address of a variable. So when you pass a pointer to a function, the function makes a copy of it and changes the content of that memory address, after function finish the parameter is changed with the changes in function body.
Pass an array to function C allows you pass an array to a function, in this case the array is not copied. The name of array is a pointer which points to the first entry of it. And this pointer is passed to the function when you pass an array to a function.
Source code example of various way to pass arguments to function view source print?
01.#include 02. 03./* functions declaration */ 04. 05./* demonstrate pass by pointer */ 06.void swap(int *x, int *y); 07. 08./* demonstrate pass by value */ 09.void swap(int x, int y);
10. 11./* demonstrate pass an array to the function */ 12.void bubble_sort(int a[], int size); 13. 14.void print_array(int a[],int size); 15. 16.void main() 17.{ 18. int x = 10; 19. int y = 20; 20. 21. 22. printf("x,y before swapping\n"); 23. printf("x = %d\n",x); 24. printf("y = %d\n",y); 25. 26. // pass by value 27. swap(x,y); 28. 29. printf("x,y after swapping using pass by value\n"); 30. printf("x = %d\n",x); 31. printf("y = %d\n",y); 32. 33. // pass by pointer 34. swap(&x,&y); 35. 36. printf("x,y after swapping using pass by pointer\n"); 37. printf("x = %d\n",x); 38. printf("y = %d\n",y); 39. 40. // declare an array 41. const int size = 5; 42. int a[size] = {1,3,2,5,4}; 43. 44. printf("array before sorting\n"); 45. print_array(a,size); 46. 47. bubble_sort(a,size); 48. 49. printf("array after sorting\n"); 50. print_array(a,size); 51. 52. 53.} 54. 55. 56./* functions implementation */ 57. 58.void swap(int *x, int *y){
59. int temp = *x; 60. *x = *y; 61. *y = temp; 62.} 63. 64.void swap(int x, int y){ 65. int temp = x; 66. x = y; 67. y = temp; 68.} 69. 70.void bubble_sort(int a[], int size) 71.{ 72. int i,j; 73. for(i=0;i
View more...
Comments