C PROGRAMMING TUTORIAL Mahira Banu
C Programming Tutorial Contents: Introduction a) b) c) d) e) f) g)
History and Usages Keywords Identifiers Variables and Constants Programming Data Types Input and Output Programming Operators
Decision and Loops a) b) c) d) e)
If‌If else and Nested If else C Programming Loops Break and Continue Switch‌..case Statement go to function
C Functions a) User Defined b) Function Recursion c) Storage class
Arrays a) One Dimensional Array b) Multi dimensional Array
Pointers a) Pointers and Function
String Structure and Union a) Union
Advance Functions in C a.) Enumeration b.) Pre-processor c.) Library Function
Chapter 1 Introduction a.)
History
C is a general purpose, structured programming language. It was developed by Dennis Ritchie in 1970 in BELL Lab. C Programming is widely used in the Programming world for to develop all the advanced applications. This tutorial will use you to learn all the basic things in the C Programming. Advantages of C:
Flexible Highly portable Easily extended by the user Faster and Efficient Include number of Built-In-function
Disadvantages of C: No runtime checking It is very executable to fixed bugs Application of C:
Unix completely developed by C Many desktop application developed by C Used to solve mathematical functions It is used to implement different OS.
Getting Started with C: For clear understanding we have to run all the basic concepts, In order to run programs we need compiler, compiler will change the source code to object code and create executable files. For practical uses we install the basic compiler Turbo C/ Advanced compiler Codelite. Character Set: Character set are the set of alphabets, numbers and some special characters which is valid in C.
Alphabets: Upper Case: A to Z Lower Case: a to z Digits: 0 to 9 Special characters: Here some of the special characters used in C > # }
b.)
< ^ {
$ â&#x20AC;? (
, â&#x20AC;&#x153; )
Keyword:
Keyword is the reserved words used in programming. Each keyword has fixed meaning and it cannot be changed by any users. Ex:
int money;
Here int is a keyword. Keyword is a case-sensitive and all keyword must be in lower case. Keywords in C Language auto
double
int
struct
break
else
long
switch
case
enum
register
typedef
char
extern
return
union
continue
for
signed
void
do
if
static
while
default
goto
sizeof
volatile
const
float
short
unsigned
c.)
Identifiers:
Identifiers are name given to C entities such as structures, keywords or functions etc… Identifiers are unique name given to the C entities which is used to identify during the execution. Ex:
int money;
Here money is an identifier. Identifier can be in Upper or Lower case. It can be start with digits or “_”. d.)
Variables and constants:
Variables: Variables are used to store memory location in system memory, each variable have unique identifiers. Ex:
int num; “num” is a variable for integer type.
Variable didn’t contain case sensitive, it may be start with underscore or digits. Constants: Constants are the term which cannot be changed during the execution of the program. It may be classified into following types: Character Constant: Character constant are the constant which used in single quotation around characters. For example: ‘a’, ‘I’, ‘m’, ‘F’. Floating Point constant: It may be numerical form that maybe fractional or exponential form. Ex: -0.012 1.23 etc… Integer Constant: Integers constant are the numeric constants without any floating point/exponential constant or character constant. It classified into 3 types: o Octal digits: 0,1,2,3,4,5,6,7 o Decimal Digits: 0,1,2,3,4,5,6,7,8,9 o Hexadecimal digits: 0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H
Escape Sequence Sometimes it is necessary to use newline, tab etc… so we have to use “/” which is known as Escape sequence. Escape Sequences
Escape Sequences
Character
\b
Backspace
\f
Form feed
\n
Newline
\r
Return
\t
Horizontal tab
\v
Vertical tab
\\
Backslash
\'
Single quotation mark
\"
Double quotation mark
\?
Question mark
\0
Null character
String Constant: Which are enclosed in double quote mark. For example “good”. Enumeration Constant: Keyword enum is used to declare enumeration. For example enum color{yellow,white,green} here the variable name is yellow,white,green are the enumeration constant which having values 0,1,2 respectively. e.)
Programming Data types
Data types in C are classified into 2 types: 1. Fundamental data types 2. Derived Data Types Syntax for Data types: Data type
variable name;
Classifications of Fundamental Data types Integer Type: Keyword int is used for declaring with integer types Floating Types: Keyword float and double are used for declaring the floating types Character Types: keyword char is used for declaring the variables of character type. Classifications of Derived Data types
Arrays Structure Enumeration Pointers
Qualifiers: It is used to alter the meaning of base data types to yield a new data type.
f.)
Input/output:
The C Program input and output functions are printf() and scanf() Printf() it’s used to provide output to the users Scanf() it’s used to taken input from the users. Examples for I/O function #include<stdio.h> Void main(); { int c; printf(“enter the number c”); scanf(“%d”,&c); printf(“number=%d,c”); return 0; } Here printf() is used to display the output .
Scanf() is ask the value from the user ‘&’ denotes that the address of the C and value stored in the number. Stdio represent standard input output function which is the library function #include is used to paste the code from the header when it is required. g.)
Programming Operators:
Operators are a symbol which operates on a value or variable. For Example: + is an operator which is used for a addition. Operators in C programming
Arithmetic operators(+,-,%,*) Increment and Decrement operators(a++,++a,a--,--a) Assignment operators(+=,a+=b is equal to a=a+b) Relational operators(==,<=,>=) Logical operators(&&,||) Conditional operators (?,: it’s used to making decision) Bitwise operators(&,| etc)
Chapter-2 Decision and loops a.) If, If…else, Nested If…else…. This Statement is used to execute the programming by one time decision i.e. execute one code and ignore one code.
If Statement It executes the statement if the test expression is true. Syntax: if (test expression) { // statement to be executed when the test expression is true }
If..else Statement This statement is used when the programmer is want to execute one statement if the test expression is true or executes other expression if the test expression is false. Syntax:
if (test expression) { Statement to be execute when expression is true; } else { Statement to be executed when it is false; }
Nested if else statement This statement is used when the programmers need more than one expression. The nested statement is work by step by step if first statement is true it never enter t the 2nd statement when it is wrong it will go to the next expression. This will used by programmers when they need to check more than one expression. Syntax: if(test expression) { execute if expression is true; }
else if( test expression 1) { execute when expression 0 is false and 1 is true; } else if (test expression 2) { execute when expression 0 and 1 are false and 2 is true); } . . . else {execute the statement when all the above are false; }
b.) C Programming Loops Loops are used when the programmer wants to execute the same block repeatedly for number of times. Loop function executes the certain block of code until the code becomes false. Types of Loops: 1. for Loop 2. while Loop 3. do…while Loop
for Loop for loop execute the program block until the given statement is false. Syntax: for(initialization; expression; update statement) { Body of the code ;}
The Initialization process run only at initial stage of the programming then it checks the expression if the expression is false loop is terminated. It is true it executes the code of the body and then executes the update statement. This process repeats until expression becomes false.
Example Program: Find out the sum of n Natural Numbers, when n is entered by the users. #include<stdio.h> #include<conio.h> int main() { int n,c,s=0; printf("enter the value of n"); scanf("%d",&n); for(c=1;c<=n;c++) { s=s+c; } printf("s=%d",s); getch(); return 0; } Output Enter the value of n=9 S=45
While Loop It checks while expression is true of false. If the expression is true it executes the body of the loop after the execution it checks the body again this process continues until it becomes false. Syntax: while (test expression) { Body of the loop; }
Example: Find the factorial of the number #include<stdio.h> int main() { int factorial,number; printf(“enter a number \n”) scanf(“%d”,&number); factorial=1; while(number>0) { factorial=factorial*number; --factorial; }
printf( factorial=%d”, factorial); return 0; }
do…while loop The only difference between the while and do while is it executes the statement and then check the test expression. Syntax: do {code to be execute; } while(test expression);
Write a C program to add the numbers until the user enter the zero #include<stdio.h> int main() { int num,sum=0; do { printf(“enter a number \n”); scanf(“%d”,&num); sum=sum+num; } while(num!=0);
printf (â&#x20AC;&#x153;%dâ&#x20AC;?,sum); return 0;} Summary for loop while loop Initialization, It checks the condition It is usually counter first, if condition is false variable, statement that it never enter into the will be executed every loop. iteration of the loop, until the counter variable increment or decrement
c.)
do..while loop It executes the statement before checks the condition at least one iteration takes place when the condition is false
Break and Continue
The two statements break and continue is used to skip or terminate the some programming blocks without checking it. Break statement It is used to terminate the loop if the statement is true. Syntax: break;
Example: write a C program to find the average value of numbers, terminate the program if the input is negative display the average value and end the program #include<stdio.h> int main()
{ int n,i; float average,num,sum; printf(“maximum numbers of inputs”); scanf(“%d”,&n); for(i=1;i<=n;++i) { printf(“enter the n %d”,i); scanf(“%d”,&n); if(num<0) break; sum=num+sum;} average=sum/(i-1); printf(“Average=%.2f”,average); return 0; }
Continue Statement To skip some statement in the function continue statement is used Syntax; continue;
Example: Write a C program to find the product of 4 numbers #include<stdio.h> int main() { int i,num,product; for(i=1,product=1;i<=4;++i) { printf(“enter the num %d”,i); scanf(“%d”,&num); if(num==0) continue; product*=num;} printf(“product=%d”,product); return 0; }
Break Continue It can appear in loop and switch It can appear only in loop statement. statements. It terminates the switch or loop It does not cause the termination, statement when break is encountered. when continue encountered it executes all iteration in the loops
d.) switch…..case Statement Decision making are used to select the particular block or code with many other alternative codes. Instead of switch case we can use nested if else but it is more complicated while compare with switch case. Syntax: switch (n) { case constant 1: A code to be executed if n is equal to constant 1; break; case constant 2:
A code to be executed if n is equal to constant 2; break; . . . default: codes to be executed if n is not equal to any constants; }
Example Program: Write a program to select the arithmetic operator and two operands and perform the corresponding operations #include<stdio.h> int main() { char o; float n1,n2;
printf(“select an operator + or – or * or \ \n); scanf(“%c”,&o); printf(“enter the two operands:”); scanf(“%f%f”,&n1,&n2); switch(o) { case +: printf(“%.1f+%.1f=%.1f”,num1,num2,num1+num2); break; case -: printf(“%.1f-%.1f=%.1f”,num1,num2,num1-num2); case *: printf(“%.1f*%.1f=%.1f”,num1,num2,num1*num2); case \: printf(“%.1f \ %.1f=%.1f”,num1,num2,num1\num2); default: printf(‘operator Error”); break; } return 0; }
e.)
go to function
This statement is used to altering the normal sequence of program by transferring control to some other parts. Syntax: goto label; ……………. …………….
label; statement;
we are not using goto statement because itâ&#x20AC;&#x2122;s make more complex and considered as a harmful construct. goto statement is replaced by the use of break and continue statement.
Chapter 3 C Functions A function is a segment which is used to perform the specified task. A C program has at least one main() function, without main there is no C programs. Types of C Functions Library Functions User defined functions Library Functions It is a built in function in C programming Example: main() --- Every programs start with main function print() --- used to display the output scanf() --- used to enter the input
a.) User Defined Function C allows the programmer to define the function according to their requirements. For example, a programmer wants to find the factorial and check whether it is prime number or not in the same program, we can use the 2 functions in the same program. Working of User defined: #include<stdio.h> void function_name() {…………………… ………………………} int main() { ……………………….. ………………………….
Function name(); …………………… ……………………. } As we mentioned earlier C program is starts with main function when the program reaches to the function name it jumps to the void function name after execution of the void function it return to the function name and executes it. Advantages: Easily maintain and debug, large no of codes easily divided in to small segments and decompose the work load.
Example: #include<stdio.h> int add(int a,int b); //Function declaration(prototype) int main() {int num1,num2,sum; printf(“enter the numbers to add”); scanf(“%d %d”,&num1,num2); sum=add(num1,num2); //function call printf(“sum=%d”,sum); return 0; } int add(int a,int b); { int add; add=a+b; return add;}
Function Declaration (prototype) Every function has to declare before they used, these type of declaration are also called function prototype. It gives compiler information about name, function, type of argument that has to pass. Syntax of Prototype return-type fun-name ( type(1) argument(1)…………….type(n) argument(n)); From the above example int add(int a,int b); this is function prototype fun-name add return type int
Function call: Control of the program transferred to the user defined when the function is called. Syntax: function_name(arg 1,arg2); Function Definition: It contains specific codes to perform specific task. It is the first line of function declaration. Syntax: function name(arg(1),arg(2))
b.) Function Recursion: The function that calls itself without any other external functions is known as recursion. Example: #include<stdio.h> int sum(int n); int main() { int num,add;
printf(“enter a positive integer”); scanf(“%d”,&n); add=sum(n); printf(“sum=%d”,add); } int sum(int n) { if(n==0) return n; else return n+sum(n-1);} Advantage: It is more elegant and requires few variables which make program clean It replaced the complex nesting code function. Disadvantage: It is hard to write the recursion. Hard to debug.
c.)
C Programming Storage:
Every variable has two properties: Type Storage Type refers to the function whether it is integer or floating or character Storage refers how long it stays. It is classifies into 4 types:
Auto External Static Register
auto: Variable declared by the inside of the function by default. It access by the local variables only. external: It can be accessed by the any function. It is called as global variables and it declared outside in the function. static: The value of static variable persists until the end of the program. register: Register variable are similar like auto and used in global variable.
Chapter-4 Arrays Main use of array is to handle similar type of data’s. For example, if the company wants to save 100 employees details. By using simple code form, the programmer has to be creating the data for 100 employees individually, but by using arrays we can easily replace it. An Array is a sequence of data types for homogeneous type. Arrays are two types 1. One Dimensional Array 2. Multi dimensional array
a.) One Dimensional Array: Declaration of One Dimensional Array: declaration_type array_name[array_size]; Example: int age[5]; Array Element: Size of array defines the number of elements used in the array. Each element can be accessed by the user by their usage. int age[5]; Age[0]
Age[1]
Age[2]
Every array element can be start by 0; Example: #include<stdio.h> void main() { int marks[10],i,n,sum=0; printf(“enter the number of students:”); scanf(“%d”,&n); for(i=0;i<n;i++)
Age[3]
Age[4]
{ printf(“enter the number of students%d:”,i+1); scanf(“%d”,&marks[i]); sum=sum+marks[i];} printf(“sum=%d”,sum); return 0; }
b.)
Multi Dimensional Array:
C Program allows programmers to create array of arrays in the program. Ex: float a[2][6]; Here, an array of two dimensions, this is example of multi-dimensional array. Initialization of Array: a[2][4]={{1,2,0,0} ,{3,4,5,6}};
Chapter-5 Pointer Pointers are the important feature it’s different the C and C++ from java and other languages. Pointers are used to access the memory and manipulate the address. Reference Operator (&): & denotes address in the memory Lets explain in the program #include<stdio.h> int main() { int var=5; printf(“value=%d”,var); printf(“address=%d”,&var); return 0;} Output: Value=5 Address=2567891 From the above code we can know clearly var is a name given to that location and 5 is stored in the 2567891 location. Reference Variable (*): It is used to hold the memory address i.e is variable that holds address is Reference variable Arrays
Pointers
Array is a single, pre-allocated and continues element
Pointer is a place in a memory which is used to store the another place or function It can be resized
It can’t be resized
It can’t be initialized
It can be initialized
a.)
Pointers and Functions
When the Argument is passed using pointer address of the memory location is passed instead of value. Example: #include<stdio.h> void swap(int *a,int *b); int main() { int n1=5,n2-10; swap(&n1,&n2); printf(“n1=%d \n”,n1); printf(“n2=%d’,n2); return 0; } void swap(int *a, int *b) { int temp; temp=*n1; *n1=*n2; *n2=temp; } The address of n1 and n2 are passed to the memory location of pointer a and b, So the value of the memory location changed the value in memory location also changed, clearly if the *a and *b are changed it will reflected in n1 & n2 This is known as call by reference.
Chapter-6 String Array of character is string. Declaration of String: String is declared like array the difference is string is denoted as char only char S[5]; S[0]
S[1]
S[2]
Declaration by using pointer char *p; Initialization of string: char c[]="abcd"; char[5]= "abcd"; char[]={‘a’, ‘b’,‘c’,‘d’,‘\0’}; Example: How to read string from terminal #include<stdio.h> #include<string.h> int main() {char name[20]; printf(“enter name:”); scanf(“%s”,name); printf(“your name is %s:”,name); return 0;} output: Enter name: Swan Tech Your name is: Swan
S[3]
S[4]
Here the compiler will give the first name only because there is white space
String Handling Functions We can use strings for various application like finding length etc.. but programmer can use the library function string.h in the program We can manipulate the string function manually so we use the handling functions. Function strlen() strcpy() strcat() strcmp()
Explanation Length of the string Copy the string Joins two string Compare two strings
gets() and puts() we can use this gets and puts condition to take input string and display the output string Example: #include<stdio.h> #include<string.h> int main() { char name[30]; printf(“enter the name”); gets(name); printf(“The name enter is:”); puts(name); return 0;} Here gets and puts are likely scanf() and printf()
Chapter-7 Structure and Union Structure: Structure is the collection variable that is used to store the different variables under a single name. If you want to store the different details of the students like register number, marks, details etc We are using structure for the better approach.
Definition: Keyword struct is used for denote the function.
Syntax: struct_structure name { datatype 1; datatype 2; . . datatype n;}
Union Union is similar to the structure, it derived from the structure and we sued union keyword to denote it in the code The main difference is All members can be accessed the structure but only the members in the union can access the code
Structure Using keyword struct for denote One or more members can initialize the function It allocates memory equal to the sum of the memory allocated to its each individual members Each member have their own space
Union Using keyword union for denote Only one member can initialize It allocates one block memory which is enough to stored all the data Only one memory for all users
Chapter-8 Advance Function in c a.) Enumeration Enumeration is user defined data type consist of integral constant and each integral constant have a keyword enum to defined the enumeration type.
enum type_name{ value 1,value 2…….value n}; By default value 1=1 and value 2=1 but the user can changed the default values.
Example of Enumerated: #include<stdio.h> enum week{Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday}; int main() { enum week today; Today=Wednesday; printf=(“%d day”,total+1); return 0;} Output: Today=4 b.)
Pre-processor
In C language the line which is beginning with # symbol is known as Pre-processor. It is substitution tool and it instruct compiler to do the specific function before the compilation of the program. Example: #include To insert particular header #define Substitute a particular macro
c.)
Library Function
It is inbuilt function of C programming which is written with their respective header files. For Example: if you want to run printf() you need to include stdio.h in the header file.