0% found this document useful (0 votes)
473 views

Introduction To C Programming Language

C is a general-purpose programming language developed in 1972. It is widely used to develop system software and portable application software. The C program consists of functions, with the main function as the entry point. A simple "Hello World" program is presented to demonstrate basic C syntax and functions like printf().

Uploaded by

Poonam Chavan
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
473 views

Introduction To C Programming Language

C is a general-purpose programming language developed in 1972. It is widely used to develop system software and portable application software. The C program consists of functions, with the main function as the entry point. A simple "Hello World" program is presented to demonstrate basic C syntax and functions like printf().

Uploaded by

Poonam Chavan
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 30

Introduction to C Programming Language C is a general-purpose computer programming language developed in 1972 by Dennis Ritchie at the Bell Telephone Laboratories

for use with the Unix operating system. Although C was designed for implementing system software, it is also widely used for developing portable application software. C is one of the most popular programming languages.It is widely used on many different software platforms, and there are few computer architectures for which a C compiler does not exist. C has greatly influenced many other popular programming languages, most notably C++, which originally began as an extension to C. The C program is a set of functions. A C program always starts executing in a special function called main function. Here is the simple but famous "Hello World" program which prints "Hello World" greeting to screen. 1 2 3 4 5 6 #include <stdio.h> main() { printf("Hello World!\n"); return 0; } The first line is the the #include directive. C program uses this directive to load external function library - stdio is c library which provides standard input/output. printf is a function which is declared in the header file called stdio.h The next is the main function - the first entry point of all C programs. C program logic starts from the beginning of main function to the its ending. And finally is the printf function which accepts a string parameter. The printf function is used to print out the message to the screen.

Define function Function is a block of source code which does one or some tasks with specified purpose. Benefit of using function 1. C programming language supports function to provide modularity to the software. 2. 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. 3. By using function, you can divide complex tasks into smaller manageable tasks and test them independently before using them together 4. 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: 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 dont pass any parameter to function you can use keyword void. 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 dont 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 01 02 03 04 05 06 07 08 09 10 11 12 13 #include<stdio.h> /* functions declaration */ void swap(int *x, int *y);

void main() { int x = 10; int y = 20;

14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34

printf("x,y before swapping\n"); printf("x = %d\n",x); printf("y = %d\n",y); // using function swap swap(&x,&y); printf("x,y after swapping\n"); printf("x = %d\n",x); printf("y = %d\n",y); }

/* functions implementation */ void swap(int *x, int *y){ int temp = *x; *x = *y; *y = temp; }

Here is the output x,y before swapping x = 10 y = 20 x,y after swapping x = 20 y = 10

C Data Types 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'. 01 #include <stdio.h> 02 03 void main()

04 { 05 06 07 08 09 10 11 12 13 }

char ch = 'A'; printf("%c\n",ch); ch = 65;// using integer representation printf("%c\n",ch); ch = '\x41'; // using hexadecimal representation printf("%c\n",ch); ch = '\101'; // using octal representation printf("%c\n",ch);

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 signed char short Unsigned short long int int 1 byte 2 bytes 2 bytes 4 bytes 27 to 271 (128 to 127) 0 to 281 (0 to 255) 215 to 215 1 (32768 to 32767) 0 to 216 1 (0 to 65535) 231 to 2311 (2,147,483,648 to 2,147,483,647) Unsigned char 1 byte

2 or 4 bytes depending on Range for 2 or 4 bytes as given implementation above 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 floatingpoint 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).

C 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: 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:

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: 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 #include <stdio.h> int global_variable = 10;// global variable void func(); void main() { int i; // test static variable for(i = 0; i < 5 ; i++) { func(); printf("after %d call \n",i); } } void func() { static int counter = 0;// static variable counter++; printf("func is called %d time(s)\n",counter); int local_variable = 10; }

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 dont 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 times 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. C Arithmetic Operators C programming language supports almost common arithmetic operator such as +,-,* and modulus operator % #include <stdio.h> /* a program demonstrates C arithmetic operators 02 */ 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 assign the value of a variable or expression to a variable. #include <stdio.h> 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 printf("y -=5;y = %d\n",y); 16 17 /* demonstrate *= operator */ 18 y *=4; 19 printf("y *=4;y = %d\n",y); 20 21 /* demonstrate /= operator */ 22 y /=2; 23 printf("y /=2;y = %d\n",y); 24 25 } 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 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(<<), and right shift(>>). We use bitwise operators in some programming contexts because bitwise operations are faster than (+) and (-) operations and significantly faster than (*) and (/) operations 01 #include <stdio.h> 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 printf("\n Bitwise XOR d1 ^ d2 = %d",d3); 20 21 d3 = ~d1; /* ones complement of 0000 0101 is 1111 1010 (-5) */ 22 printf("\n Ones complement of d1 = %d",d3); 23 24 d3 = d1<<2;/* 0000 0101 left shift by 2 bits is 0001 0000 */ 25 printf("\n Left shift by 2 bits d1 << 2 = %d",d3); 26 27 d3 = d1>>2;/* 0000 0101 right shift by 2 bits is 0000 0001 */ 28 printf("\n Right shift by 2 bits d1 >> 2 = %d",d3); 29 } 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 = 16 Right 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. Syntax of of increment operators: 1 2 3 4 variable++; variable--; ++variable; --variable;

#include <stdio.h> /* a program demonstrates C increment operators 02 */ 03 void main(){ 04 int x = 10; 05 int y = 0; 06 printf("x = %d\n",x); 07 08 /* demonstrate ++ prefix operator */ 09 y = ++x; 10 printf("y = ++x;y = %d\n",y); 11 12 /* demonstrate ++ postfix operator */ 13 y = x++; 14 printf("y = x++;y = %d\n",y); 15 16 /* demonstrate -- prefix operator */ 17 y = --x; 18 printf("y = --x;y = %d\n",y); 19 20 /* demonstrate -- postfix operator */ 21 y = x--; 22 printf("y = x--;y = %d\n",y); 23 24 /* keep console screen until a key stroke */ 25 char key; 26 scanf(&key); 27 } 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 Fals True False True True e Fals False False False True e C Relational Operators Relational operators in C programming language are used in Boolean conditions or expression and returns true or false. #include <stdio.h> /* a program demonstrates C relational operators 02 */ 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 <= operator */ 41 result = (x <= y); 42 printf("bool result = (x <= y);"); 43 print_bool(result); 44 45 46 /* keep console screen until a key stroke */ 47 char key; 48 scanf(&key); 49 } Here is the output: x = 10 y = 20 bool result = (x == y);false bool result = (x != y);true bool result = (x > y);false bool result = (x >= y);false bool result = (x < y);true bool result = (x <= y);true C Ternary Operator C ternary operator is shorthand of combination of if and returns statement. C ternary operator is shorthand of combination of if and returns statement. Syntax of ternary operator are as follows: (expression1)? expression2: expression3 If expression1 is true it returns expression2 otherwise it returns expression3. This operator is a shorthand version of this if and returns statement: 1 if(expression1) 2 return expression2; 3 else 4 return expression3;

C if Statement

C if statement is used when a unit of code need to be executed by a condition true or false. 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: 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: 1 /* all code in bracket is affects by if condition*/ 2 if(x == y){ 3 x++; 4 y--; 5} 6 /* only expression x++ is affected by if condition*/ 7 if(x == y) 8 x++; 9 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: 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: 1 2 3 4 5 6 7 8 9 if(condition-1){ /* code block if condition-1 }else if (condition-2){ /* code block if condition-2 }else if (condition-3){ /* code block if condition-3 }else{ /* code block all conditions }

is true */ is true */ is true */ above are false */

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} C Switch Statement The switch statement allows you to select from multiple choices based on a set of fixed values for a given expression. Here are the common switch statement syntax: 1 switch(expression){ 2 case value1: /* execute unit of code 1 */ 3 break; 4 case value2: /* execute unit of code 2 */ 5 break; 6 ... 7 default: /* execute default action */ 8 break; 9} In the switch statement, the selection is determined by the value of an expression that you specify, which is enclosed between the parentheses after the keyword switch. The data type of value which is returned by expression must be an integer value otherwise the statement will not compile. The case constant expression must be an integer value and all values in case statement are equal. When a break statement is executed, it causes execution to continue with the statement following the closing brace for the switch. The break statment is not mandatory, but if you don't put a break statement at the end of the statements for a case, the statements for the next case in sequence will be executed as well, through to whenever another break is found or the end of the switch block is reached. This can lead some unexpected program logics happen. The default statement is the default choice of the switch statement if all cases statement are not satisfy with the expression. The break after the default statements is not necessary unless you put another case statement below it. Here is an example of using C switch statement 01 02 03 04 05 06 07 08 #include <stdio.h> const int RED = 1; const int GREEN = 2; const int BLUE = 3;

void main(){ int color = 1; printf("Enter an integer to choose a 09 color(red=1,green=2,blue=3):\n"); 10 scanf("%d",&color); 11

12 switch(color){ 13 case RED: printf("you chose red color\n"); 14 break; 15 case GREEN:printf("you chose green color\n"); 16 break; 17 case BLUE:printf("you chose blue color\n"); 18 break; 19 default:printf("you did not choose any color\n"); 20 } 21 } Here is the output: Please enter an integer to choose a color(red=1,green=2,blue=3): 2 you chose green color While Loop Statement 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: 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: 01 #include <stdio.h> 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. Here is do while loop syntax: 1 do { 2 // statements 3 } while (expression); Here is an example of using do while loop statement: 01 #include <stdio.h> 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. for (initialization_expression;loop_condition;increment_expression) { 2 // statements 3} There are three parts which is separated by semi-colons in control block of the for loop. initialization_expression is executed before execution of the loop starts. This is typically used to initialize a counter for the number of loop iterations. You can initialize a counter for the loop in this part. The execution of the loop continues until the loop_condition is false. This expression is checked at the beginning of each loop iteration. The increment_expression, is usually used to increment the loop counter. This is executed at the end of each loop iteration. Here is an example of using for loop statement to print an integer five times 01 #include <stdio.h> 02 03 void main(){ 04 // using for loop statement 05 int max = 5; 06 int i = 0; 07 for(i = 0; i < max;i++){ 08 09 printf("%d\n",i); 10 11 } 12 } And the output is 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. After continue statement the control returns to the top of the loop test conditions. Here is an example of using break and continue statement: 01 #include <stdio.h> 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:

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. 01 02 03 04 05 06 07 08 09 10 11 12 #include <stdio.h> typedef struct __address{ int house_number; char street[50]; int zip_code; char country[20]; } address; void main() {

13 14 15 16 17

18 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 printf("size of address is %d byte(s)\n",sizeof(address)); 26 } 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: 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. 1 if(pi == NULL) 2{ 3 fprintf(stderr,"error occurred: out of memory"); 4 exit(EXIT_FAILURE); 5}

printf("size of int is %d byte(s)\n",sizeof(int)); printf("size of unsigned int is %d byte(s)\n",sizeof(unsigned int)); printf("size of short is %d byte(s)\n",sizeof(short)); printf("size of unsigned short is %d byte(s)\n",sizeof(unsigned short)); printf("size of long is %d byte(s)\n",sizeof(long));

Beside malloc function, C also provides two other functions which make convenient ways to allocate memory: 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: 1 void free(void *ptr); You should always use malloc and free as a pair in your program to a void memory leak.

C pointer is a memory address. When you define a variable for example: 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 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: 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: 1 int *px = &x; After that you can change the content of variable x for example you can increase, decrease x value :

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: 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

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: 1 data_type array_name[size]; For example, to declare an integer array which contains 100 elements we can do as follows: 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. 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. 01 #include <stdio.h> 02 03 void main() 04 { 05 06 const int size = 5; 07 08 int list[size] = {2,1,3,7,8}; 09 10 int* plist = list; 11

12 13 14 15 16 17 18 19 20 21 22 23 24

// 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

25 element of the array */ 26 plist++; 27 } 28 29 } 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. 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 single-dimensional array. To declare a multidimensional array you can do follow syntax 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: 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:

1 int matrix[3][3] = 2{ 3 {11,12,13}, 4 {21,22,23}, 5 {32,31,33}, 6 };

Introducing to C structure In some programming contexts, you need to access multiple data types under a single name for easier data 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 or even other structures. Each variable in structure is called a structure member. Defining structure To define a structure, you use struct keyword. Here is the common syntax of structure definition: struct struct_name{ structure_member }; The name of structure follows 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 }; The address structure 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 creating any structure instance. To create or declare a structure instance, you can do it in two ways: The first way is to declare a structure followed 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 the structure instance at a different location in your source code after structure definition. Here is structure declaration syntax : 1 struct struct_name instance_1,instance_2 instance_n; Complex structure If a structure contains arrays or other structures, it is called complex structure. For example address structure is a structure. We can define a complex structure called customer which contains address structure as follows: 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: 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. 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: 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: 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 1 typedef struct{ 2 unsigned int house_number; 3 char street_name[50]; 4 int zip_code; 5 char country[50]; 6 } address; 7 8 address billing_addr; 9 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 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: 01 #include <stdio.h> 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. 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 #include <stdio.h> typedef struct _student{ char name[50]; unsigned int mark; } student;

void print_list(student list[], int size); void read_list(student list[], int size);

void main(){ const int size = 3; student list[size]; read_list(list,size); print_list(list,size);

} void read_list(student list[], int size) { printf("Please enter the student information:\n"); for(int i = 0; i < size;i++){ printf("\nname:"); scanf("%S",&list[i].name); printf("\nmark:"); scanf("%U",&list[i].mark); }

39 } 40 41 void print_list(student list[], int size){ 42 printf("Students' information:\n"); 43 44 for(int i = 0; i < size;i++){ printf("\nname: %s, mark: 45 %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

String Definition C does not have a string type as other modern programming languages. C only has character type so a C string is defined as an array of characters or a pointer to characters. Null-terminated String String is terminated by a special character which is called as null terminator or null parameter (/0). So when you define a string you should be sure to have sufficient space for the null terminator. In ASCII table, the null terminator has value 0.

Declaring String As in string definition, we have two ways to declare a string. The first way is, we declare an array of characters as follows: 1 char s[] = "string"; And in the second way, we declare a string as a pointer point to characters: 1 char* s = "string"; Declaring a string in two ways looks similar but they are actually different. In the first way, you declare a string as an array of character, the size of string is 7 bytes including a null terminator. But in the second way, the compiler will allocate memory space for the string and the base address of the string is assigned to the pointer variable s. Looping Through a String You can loop through a string by using a subscript. Here is an example of looping through a string using a subscript: 1 // loop through a string using a subscript 2 char s[] = "C string"; 3 int i; 4 for(i = 0; i < sizeof(s);i++) 5{ 6 printf("%c",s[i]); 7} You can also use a pointer to loop through a string. You use a char pointer and point it to the first location of the string, then you iterate it until the null terminator reached. 1 2 3 4 5 6 // loop through a string using a pointer char* ps = s; while(*ps != '\0'){ printf("%c",*ps); ps++; }

Passing a String to Function A formal way to pass a string to a function is passing it as a normal array.

You might also like