Professional Documents
Culture Documents
C Program
C Program
Contents
C – Language History.............................................................................................................................3
Features of C language:.....................................................................................................................3
Uses of C language:...........................................................................................................................3
Which level the C language is belonging to?..............................................................................3
C language is a structured language...........................................................................................4
1. C Basic Program:...........................................................................................................................4
Hello World!.........................................................................................................................................4
Explanation for above C basic Program:.........................................................................................4
2. Steps to write C programs and get the output:...........................................................................5
3. Basic structure of C program:.......................................................................................................5
Example C program to compare all the sections:...........................................................................6
Description for each section of a C program:..................................................................................7
C – printf and scanf................................................................................................................................7
1. C printf() function:.......................................................................................................................8
Example program for C printf() function:..................................................................................8
2. C scanf() function:..........................................................................................................................9
Example program for printf() and scanf() functions in C:.......................................................9
C – Data Types.....................................................................................................................................10
C – Data types:..............................................................................................................................10
1. Basic data types in C:..............................................................................................................10
1.1. Integer data type:..............................................................................................................10
1.2. Character data type:.........................................................................................................11
1.3. Floating point data type:...................................................................................................11
1.3.1. sizeof() function in C:.........................................................................................................11
1.3.2. Modifiers in C:.................................................................................................................12
2. Enumeration data type in C:....................................................................................................13
C – enum example program:...................................................................................................14
3. Derived data type in C:............................................................................................................14
4. Void data type in C:..................................................................................................................14
C – Tokens and keywords....................................................................................................................14
1. C tokens:......................................................................................................................................14
C tokens example program:........................................................................................................15
1
DAVINCI [C PROGRAMMING]
2. Identifiers in C language:.........................................................................................................15
Rules for constructing identifier name in C:...............................................................................15
3. Keywords in C language:.........................................................................................................15
C – Constant........................................................................................................................................16
Types of C constant:.....................................................................................................................16
Rules for constructing C constant:..........................................................................................17
C – Variable..........................................................................................................................................19
Rules for naming C variable:.......................................................................................................20
Declaring & initializing C variable:..............................................................................................20
There are three types of variables in C program They are,....................................................20
1. Example program for local variable in C:..............................................................................20
2. Example program for global variable in C:............................................................................21
3. Environment variables in C:....................................................................................................22
Difference between variable declaration & definition in C:......................................................24
C – Operators and Expressions............................................................................................................24
C – Decision Control statement......................................................................................................38
C – Loop control statements...........................................................................................................40
C – Case control statements...........................................................................................................43
C – Array............................................................................................................................................47
C – String...........................................................................................................................................50
C – strcat() function.........................................................................................................................52
C – strcpy() function........................................................................................................................53
C – strlen() function.........................................................................................................................53
C – strcmp() function.......................................................................................................................54
C – strlwr() function.........................................................................................................................55
C – strupr() function........................................................................................................................55
C – strrev() function.........................................................................................................................56
C – Pointer.........................................................................................................................................57
C – Function......................................................................................................................................58
C – Argument & return value...........................................................................................................62
C – Structure.....................................................................................................................................67
C – Typedef.......................................................................................................................................71
C – Union...........................................................................................................................................74
2
DAVINCI [C PROGRAMMING]
C – Language History
C language is a structure oriented programming language, was developed at Bell Laboratories in 1972 by
Dennis Ritchie
C language features were derived from earlier language called “B” (Basic Combined Programming Language
– BCPL)
C language was invented for implementing UNIX operating system
In 1978, Dennis Ritchie and Brian Kernighan published the first edition “The C Programming Language”
and commonly known as K&R C
In 1983, the American National Standards Institute (ANSI) established a committee to provide a modern,
comprehensive definition of C. The resulting definition, the ANSI standard, or “ANSI C”, was completed late 1988.
Features of C language:
Reliability
Portability
Flexibility
Interactivity
Modularity
Efficiency and Effectiveness
Uses of C language:
C language is used for developing system applications that forms major portion of operating
systems such as Windows, UNIX and Linux. Below are some examples of C being used.
Database systems
Graphics packages
Word processors
Spread sheets
Operating system development
Compilers and Assemblers
Network drivers
Interpreters
Examples:
2 C, C++ Assembler
Java, Python
3
DAVINCI [C PROGRAMMING]
Examples:
BASIC, COBOL,
5 C++, JAVA and C# (C sharp)
C, Pascal, ALGOL and FORTRAN
Modula-2
1. C Basic Program:
#include <stdio.h>
int main()
{
/* Our first simple C basic program */
printf("Hello World! ");
getch();
return 0;
}
Output:
Hello World!
Let’s see all the sections of the above simple C program line by line.
4
DAVINCI [C PROGRAMMING]
printf(“Hello_World!
5 printf command prints the output onto the screen.
“);
6 getch(); This command waits for any character input from keyboard.
Below are the steps to be followed for any C program to create and get the output. This is common to all C
program and there is no exception whether its a very small C program or very large C program.
Structure of C program is defined by set of rules called protocol, to be followed by programmer while writing C
program. All C programs are having sections/parts which are mentioned below.
1. Documentation section
5
DAVINCI [C PROGRAMMING]
2. Link Section
3. Definition Section
4. Global declaration section
5. Function prototype declaration section
6. Main function
7. User defined function definition section
You can compare all the sections of a C program with the below C program.
Author: fresh2refresh.com
Date : 01/01/2012
*/
{
return 0;
Output:
6
DAVINCI [C PROGRAMMING]
Please note that a C program mayn’t have all below mentioned sections except main function
and link sections.
Also, a C program structure mayn’t be in below mentioned order.
In this section, variables are defined and values are set to these
3 Definition Section
variables.
Global declaration Global variables are defined in this section. When a variable is to
4
section be used throughout the program, can be defined in this section.
Function prototype Function prototype gives many information about a function like
5
declaration section return type, parameter names used inside the function.
User defined User can define their own functions in this section which perform
7
function section particular task as per the user requirement.
1. C printf() function:
printf() function is used to print the “character, string, float, integer, octal and hexadecimal
values” onto the output screen.
We use printf() function with %d format specifier to display the value of an integer variable.
Similarly %c is used to display character, %f for float variable, %s for string variable, %lf for
double and %x for hexadecimal variable.
7
DAVINCI [C PROGRAMMING]
C language is case sensitive. For example, printf() and scanf() are different from Printf() and
Scanf(). All characters in printf() and scanf() functions must be in lower case.
#include <stdio.h>
int main()
char ch = 'A';
char str[20] = "fresh2refresh.com";
int no = 150;
return 0;
Output:
Character is A
String is fresh2refresh.com
Float value is 10.234000
Integer value is 150
Double value is 20.123456
Octal value is 226
Hexadecimal value is 96
You can see the output with the same data which are placed within the double quotes of printf statement in the
program except
8
DAVINCI [C PROGRAMMING]
2. C scanf() function:
scanf() function is used to read character, string, numeric data from keyboard
Consider below example program where user enters a character. This value is assigned to the
variable “ch” and then displayed.
Then, user enters a string and this value is assigned to the variable ”str” and then displayed.
int main()
char ch;
char str[100];
scanf("%c", &ch);
scanf("%s", &str);
Output:
The format specifier %d is used in scanf() statement. So that, the value entered is received as
an integer and %s for string.
Ampersand is used before variable name “ch” in scanf() statement as &ch.
It is just like in a pointer which is used to point to the variable
9
DAVINCI [C PROGRAMMING]
C – Data Types
C data types are defined as the data storage format that a variable can store a data to perform a specific
operation.
Data types are used to define a variable before to use in a program.
Size of variable, constant and array are determined by data types.
C – Data types:
There are four data types in C language. They are,
10
DAVINCI [C PROGRAMMING]
For example, ‘A’ can be stored using char datatype. You can’t store more than one character using char data
type.
Please refer C – Strings topic to know how to store more than one characters in a variable.
1. float
2. double
1. float:
Float data type allows a variable to store decimal values.
Storage size of float data type is 4. This also varies depend upon the processor in the CPU as “int” data type.
We can use up-to 6 digits after decimal using float data type.
For example, 10.456789 can be stored in a variable using float data type.
2. double:
Double data type is also same as float data type which allows up-to 10 digits after decimal.
The range for double datatype is from 1E–37 to 1E+37
.
#include <stdio.h>
#include <limits.h>
int main()
int a;
char b;
float c;
double d;
return 0;
11
DAVINCI [C PROGRAMMING]
Output:
1.3.2. Modifiers in C:
The amount of memory space to be allocated for a variable is derived by modifiers.
Modifiers are prefixed with basic data types to modify (either increase or decrease) the amount of storage
space allocated to a variable.
For example, storage space for int data type is 4 byte for 32 bit processor. We can increase the range by using
long int which is 8 byte. We can decrease the range by using short int which is 2 byte.
There are 5 modifiers available in C language. They are,
1. short
2. long
3. signed
4. unsigned
5. long long
Below table gives the detail about the storage size of each C basic data type in 16 bit processor.
Please keep in mind that storage size and range for int and float datatype will vary depend on the CPU processor (8,16,
32 and 64 bit)
storage
S.No C Data types Range
Size
12
DAVINCI [C PROGRAMMING]
The above enum functionality can also be implemented by “#define” preprocessor directive as given below.
Above enum example is same as given below.
#define Jan 20;
#define Feb 21;
#define Mar 22;
int main()
if(month == 0)
printf("Value of Jan");
else if(month == 1)
printf("Month is Feb");
if(month == 2)
printf("Month is Mar");
13
DAVINCI [C PROGRAMMING]
Output:
Month is March
1. C tokens:
C tokens are the basic buildings blocks in C language which are constructed together to write a
C program.
Each and every smallest individual units in a C program are known as C tokens.
C tokens are of six types. They are,
1. Keywords (eg: int, while),
2. Identifiers (eg: main, total),
3. Constants (eg: 10, 20),
4. Strings (eg: “total”, “hello”),
5. Special symbols (eg: (), {}),
6. Operators (eg: +, /,-,*)
int x, y, total;
total = x + y;
14
DAVINCI [C PROGRAMMING]
where,
main – identifier
{,}, (,) – delimiter
int – keyword
x, y, total – identifier
main, {, }, (, ), int, x, y, total – tokens
Do you know how to use C token in real time application programs? We have given simple real time
application programs where C token is used. You can refer the below C programs to know how to use C token in
real time program.
2. Identifiers in C language:
Each program elements in a C program are given a name called identifiers.
Names given to identify Variables, functions and arrays are examples for identifiers. eg. x is a
name given to integer variable in above program.
3. Keywords in C language:
Keywords are pre-defined words in a C compiler.
Each keyword is meant to perform a specific function in a C program.
Since keywords are referred names for compiler, they can’t be used as variable name.
C language supports 32 keywords which are given below. Click on each keywords below for detail description and
example programs.
do if static while
15
DAVINCI [C PROGRAMMING]
C – Constant
C Constants are also like normal variables. But, only difference is, their values can not be modified by the
program once they are defined.
Constants refer to fixed values. They are also called as literals
Constants may be belonging to any of the data type.
Syntax:
const data_type variable_name; (or) const data_type *variable_name;
Types of C constant:
1. Integer constants
2. Real or Floating point constants
3. Octal & Hexadecimal constants
4. Character constants
5. String constants
6. Backslash character constants
float 10.456789
2 Real or Floating point constants
doule 600.123456789
16
DAVINCI [C PROGRAMMING]
2. Real constants in C:
A real constant must have at least one digit
It must have a decimal point
It could be either positive or negative
If no sign precedes an integer constant, it is assumed to be positive.
No commas or blanks are allowed within a real constant.
\b Backspace
\f Form feed
\n New line
\r Carriage return
\t Horizontal tab
\” Double quote
\’ Single quote
\\ Backslash
\v Vertical tab
\a Alert or bell
\? Question mark
17
DAVINCI [C PROGRAMMING]
#include <stdio.h>
void main()
Output:
preprocessor directive in C:
#include <stdio.h>
18
DAVINCI [C PROGRAMMING]
void main()
Output:
19
DAVINCI [C PROGRAMMING]
void test();
int main()
error */
test();
void test()
20
DAVINCI [C PROGRAMMING]
error */
Output:
values : m = 22 and n = 44
values : a = 50 and b = 80
void test();
int main()
printf("\nvalues : m= %d : n= %d : a= %d : b= %d",m,n,a,b);
test();
void test()
printf("\nvalues : m= %d : n= %d : a= %d : b= %d",m,n,a,b);
21
DAVINCI [C PROGRAMMING]
Output:
3. Environment variables in C:
Environment variable is a variable that will be available for all C applications and C
programs.
We can access these variables from anywhere in a C program without declaring and initializing
in an application or C program.
The inbuilt functions which are used to access, modify and set these environment variables are
called environment functions.
There are 3 functions which are used to access, modify and assign an environment variable in
C. They are,
1. setenv()
2. getenv()
3. putenv()
#include <stdio.h>
#include <stdlib.h>
int main()
return 0;
Output:
/usr/bin/test/ Example
program for
setenv() function
in C:
This function sets the value for environment variable. Let us assume that environment variable “FILE” is to be
assigned “/usr/bin/example.c”
#include <stdio.h>
22
DAVINCI [C PROGRAMMING]
#include <stdlib.h>
int main()
setenv("FILE","/usr/bin/example.c",50);
return 0;
Output:
Example
File = /usr/bin/example.c
program for
putenv()
function in C:
This function modifies the value for environment variable. Below example program shows that how to modify
an existing environment variable value.
#include <stdio.h>
#include <stdlib.h>
int main()
setenv("DIR","/usr/bin/example/",50);
"%s\n", getenv("DIR"));
putenv("DIR=/usr/home/");
return 0;
Output:
23
DAVINCI [C PROGRAMMING]
Declaration tells the compiler about data type Definition allocates memory for the
1
and size of the variable. variable.
Variable can be declared many times in a It can happen only one time for a
2
program. variable in a program.
24
DAVINCI [C PROGRAMMING]
Arithmetic Operators in C:
1 + Addition A+B
2 - Subtraction A-B
3 * multiplication A*B
4 / Division A/B
5 % Modulus A%B
In this example program, two values “40″ and “20″ are used to perform arithmetic operations
such as addition, subtraction, multiplication, division, modulus and output is displayed for each operation.
#include <stdio.h>
int main()
add = a+b;
sub = a-b;
mul = a*b;
div = a/b;
mod = a%b;
25
DAVINCI [C PROGRAMMING]
Output:
Addition of a, b is : 60
Subtraction of a, b is : 20
Multiplication of a, b is : 800
Division of a, b is : 2
Modulus of a, b is : 0
Assignment operators in C:
In C programs, values for the variables are assigned using assignment operators.
For example, if the value “10″ is to be assigned for the variable “sum”, it can be assigned as
“sum = 10;”
Other assignment operators in C language are given below.
+= sum+=10 This_is_same_as_sum=sum+10…………
In this program, values from 0 – 9 are summed up and total “45″ is displayed as output.
Assignment operators such as “=” and “+=” are used in this program to assign the values and
to sum up the values.
# include <stdio.h>
int main()
26
DAVINCI [C PROGRAMMING]
int Total=0,i;
for(i=0;i<10;i++)
{
}
Output:
Total = 45
Relational operators in C:
Relational operators are used to find the relation between two variables. i.e. to compare the
values of two variables in a C program.
S.no Operators Example Description
5 == x == y x is equal to y
6 != x != y x is not equal to y
In this program, relational operator (==) is used to compare 2 values whether they are equal are
not.
If both values are equal, output is displayed as ” values are equal”. Else, output is displayed as
“values are not equal”.
Note : double equal sign (==) should be used to compare 2 values. We should not single equal
sign (=).
#include <stdio.h>
int main()
int m=40,n=20;
27
DAVINCI [C PROGRAMMING]
if (m == n)
{
}
else
{
}
Output:
Logical operators in C:
These operators are used to perform logical operations on the given expressions.
There are 3 logical operators in C language. They are, logical AND (&&), logical OR (||) and
logical NOT (!).
S.no Operators Name Example Description
#include <stdio.h>
int main()
28
DAVINCI [C PROGRAMMING]
{
}
{
}
{
}
else
{
getch();
}
Output:
In this program, operators (&&, || and !) are used to perform logical operations on the given
expressions.
&& operator – “if clause” becomes true only when both conditions (m>n and m! =0) is true.
Else, it becomes false.
|| Operator – “if clause” becomes true when any one of the condition (o>p || p!=20) is true. It
becomes false when none of the condition is true.
! Operator – It is used to reverses the state of the operand.
If the conditions (m>n && m!=0) is true, true (1) is returned. This value is inverted by “!”
operator.
So, “! (m>n and m! =0)” returns false (0).
29
DAVINCI [C PROGRAMMING]
Bit wise operators in C:
These operators are used to perform bit operations. Decimal values are converted into binary
values which are the sequence of bits and bit wise operators work on these bits.
Bit wise operators in C language are & (bitwise AND), | (bitwise OR), ~ (bitwise OR), ^
(XOR), << (left shift) and >> (right shift).
Truth table for bit wise operation Bit wise operators
0 0 0 0 0 & Bitwise_AND
0 1 1 0 1 | Bitwise OR
1 0 1 0 1 ~ Bitwise_NOT
1 1 1 1 0 ^ XOR
Consider x=40 and y=80. Binary form of these values are given below.
x = 00101000
y= 01010000
In this example program, bit wise operations are performed as shown above and output is
displayed in decimal format.
30
DAVINCI [C PROGRAMMING]
#include <stdio.h>
int main()
int m=40,n=80,AND_opr,OR_opr,XOR_opr,NOT_opr ;
AND_opr = (m&n);
OR_opr = (m|n);
NOT_opr = (~m);
XOR_opr = (m^n);
Output:
AND_opr value = 0
OR_opr value = 120
NOT_opr value = -41
XOR_opr value = 120
left_shift value = 80
right_shift value = 20
Conditional operators return one value if condition is true and returns another value is
condition is false.
This operator is also called as ternary operator.
Syntax : (Condition? true_value: false_value);
In above example, if A is greater than 100, 0 is returned else 1 is returned. This is equal to if
else conditional statements.
Example program for conditional/ternary operators in C:
#include <stdio.h>
31
DAVINCI [C PROGRAMMING]
int main()
int x=1, y ;
y = ( x ==1 ? 2 : 0 ) ;
Output:
x value is 1
y value is 2
Increment operators are used to increase the value of the variable by one and decrement operators are used to
decrease the value of the variable by one in C programs.
Syntax:
Increment operator : ++var_name; (or) var_name++;
Decrement operator : – - var_name; (or) var_name – -;
Example:
Increment operator : ++ i ; i ++ ;
Decrement operator: – - i ; i – - ;
In this program, value of “i” is incremented one by one from 1 up to 9 using “i++” operator
and output is displayed as “1 2 3 4 5 6 7 8 9”.
//Example for increment operators
#include <stdio.h>
int main()
while(i<10)
{
32
DAVINCI [C PROGRAMMING]
i++;
}
Output:
123456789
Example program for decrement operators in C:
In this program, value of “I” is decremented one by one from 20 up to 11 using “i–” operator
and output is displayed as “20 19 18 17 16 15 14 13 12 11”.
//Example for decrement operators
#include <stdio.h>
int main()
int i=20;
while(i>10)
{
i--;
}
Output:
20 19 18 17 16 15 14 13 12 11
Below table will explain the difference between pre/post increment and decrement operators in
C.
++i
1 Pre increment Value of i is incremented before assigning it to variable i.
i++
2 Post-increment Value of i is incremented after assigning it to variable i.
33
DAVINCI [C PROGRAMMING]
– –i
3 Pre decrement Value of i is decremented before assigning it to variable i.
i– –
4 Post_decrement Value of i is decremented after assigning it to variable i.
#include <stdio.h>
int main()
{
printf("%d ",i);
}
return 0;
Output:
1234
#include <stdio.h>
int main()
{
34
DAVINCI [C PROGRAMMING]
printf("%d ",i);
}
return 0;
Output:
12345
#include <stdio.h>
int main()
{
printf("%d ",i);
}
return 0;
Output:
9876
#include <stdio.h>
35
DAVINCI [C PROGRAMMING]
int main()
{
printf("%d ",i);
}
return 0;
Output:
98765
In this program, “&” symbol is used to get the address of the variable and “*” symbol is used
to get the value of the variable that the pointer is pointing to. Please refer C – pointer topic to know more about
pointers.
#include <stdio.h>
36
DAVINCI [C PROGRAMMING]
int main()
int *ptr, q;
q = 50;
ptr = &q;
printf("%d", *ptr);
return 0;
Output:
50
sizeof() operator is used to find the memory space allocated for each C data types.
#include <stdio.h>
#include <limits.h>
int main()
int a;
char b;
float c;
double d;
return 0;
37
DAVINCI [C PROGRAMMING]
Output:
Syntax for each C decision control statements are given in below table with description.
Decision
control Syntax Description
statements
if (condition1)
If condition 1 is false, then condition 2 is
{ Statement1; }
checked and statements are executed if it is
nested if else_if (condition2)
true. If condition 2 also gets failure, then else
{ Statement2; }
part is executed.
else Statement 3;
int m=40,n=40;
38
DAVINCI [C PROGRAMMING]
if (m == n)
{
}
Output:
In C if else control statement, group of statements are executed when condition is true. If condition is false,
then else part statements are executed.
#include <stdio.h>
int main()
int m=40,n=20;
if (m == n) {
}
else {
}
Output:
In “nested if” control statement, if condition 1 is false, then condition 2 is checked and
statements are executed if it is true.
If condition 2 also gets failure, then else part is executed.
#include <stdio.h>
int main()
39
DAVINCI [C PROGRAMMING]
int m=40,n=20;
if (m>n) {
}
else if(m<n) {
}
else {
}
Output:
m is greater than n
1. for
2. while
3. do-while
Syntax for each C loop control statements are given in below table with description.
Where,
exp1 – variable initialization
( Example: i=0, j=2, k=3 )
for (exp1; exp2; expr3)
1 for exp2 – condition checking
{ statements; }
( Example: i>5, j<3, k=3 )
exp3 – increment/decrement
( Example: ++i, j–, ++k )
40
DAVINCI [C PROGRAMMING]
do { statements; } where,
3 do while
while (condition); condition might be a>5, i<10
In for loop control statement, loop is executed until condition becomes false.
#include <stdio.h>
int main()
int i;
for(i=0;i<10;i++)
{
printf("%d ",i);
}
Output:
0 1 2 3 4 5 6 7 8 9
In while loop control statement, loop is executed until condition becomes false.
#include <stdio.h>
int main()
int i=3;
while(i<10)
{
printf("%d\n",i);
i++;
}
Output:
3 4 5 6 7 8 9
41
DAVINCI [C PROGRAMMING]
In do..while loop control statement, while loop is executed irrespective of the condition for first time. Then
2nd time onwards, loop is executed until condition becomes false.
#include <stdio.h>
int main()
int i=1;
do
{
printf("Value of i is %d\n",i);
i++;
Output:
Value of i is 1
Value of i is 2
Value of i is 3
Value of i is 4
1. switch
2. break
3. continue
4. goto
42
DAVINCI [C PROGRAMMING]
Switch case statements are used to execute only specific case statements based on the switch
expression.
Below is the syntax for switch case statement.
switch (expression)
{
case label1: statements;
break;
case label2: statements;
break;
default: statements;
break;
}
Example program for switch..case statement in C:
#include <stdio.h>
int main ()
int value = 3;
switch(value)
{
case 1:
printf("Value is 1 \n" );
break;
case 2:
printf("Value is 2 \n" );
break;
case 3:
printf("Value is 3 \n" );
break;
case 4:
printf("Value is 4 \n" );
break;
default :
43
DAVINCI [C PROGRAMMING]
}
return 0;
Output:
Value is 3
2. break statement in C:
Break statement is used to terminate the while loops, switch case loops and for loops from the
subsequent execution.
Syntax: break;
Example program for break statement in C:
#include <stdio.h>
int main()
int i;
for(i=0;i<10;i++)
{
if(i==5)
{
break;
}
printf("%d ",i);
}
Output:
0 1 2 3 4
Coming out of for loop when i = 5
44
DAVINCI [C PROGRAMMING]
3. Continue statement in C:
Continue statement is used to continue the next iteration of for loop, while loop and do-while
loops. So, the remaining statements are skipped within the loop for that particular iteration.
Syntax : continue;
Example program for continue statement in C:
#include <stdio.h>
int main()
int i;
for(i=0;i<10;i++)
{
if(i==5 || i==6)
{
continue;
}
printf("%d ",i);
}
Output:
0 1 2 3 4
4. goto statement in C:
goto statements is used to transfer the normal flow of a program to the specified label in the
program.
Below is the syntax for goto statement in C.
{
…….
45
DAVINCI [C PROGRAMMING]
go to label;
…….
…….
LABEL:
statements;
}
Example program for goto statement in C:
#include <stdio.h>
int main()
int i;
for(i=0;i<10;i++)
{
if(i==5)
{
goto HAI;
}
printf("%d ",i);
}
Output:
0 1 2 3 4
We are using goto statement when i = 5
Now, we are inside label name “hai”
C – Array
C Array is a collection of variables belongings to the same data type. You can store group of data of same data
type in an array.
46
DAVINCI [C PROGRAMMING]
Always, Contiguous (adjacent) memory locations are used to store array elements in memory.
It is a best practice to initialize an array to zero or null while declaring, if we don’t assign any
values to array.
Example for C Arrays:
age[0];_/*0_is_accessed*/
int age [5]; int age[5]={0, 1, 2, 3, 4, 5}; age[1];_/*1_is_accessed*/
age[2];_/*2_is_accessed*/
char str[10]={‘H’,‘a’,‘i’}; (or)
str[0];_/*H is accessed*/
char str[0] = ‘H’;
char str[10]; str[1]; /*a is accessed*/
char str[1] = ‘a’;
str[2]; /* i is accessed*/
char str[2] = ‘i;
#include<stdio.h>
int main()
int i;
47
DAVINCI [C PROGRAMMING]
*/
for (i=0;i<5;i++)
{
}
Output:
value of arr[0] is 10
value of arr[1] is 20
value of arr[2] is 30
value of arr[3] is 40
value of arr[4] is 50
Syntax:
data_type arr_name[2][2] =
1 data_type arr_name [num_of_rows] arr_name[index];
{{0,0},{0,1},{1,0},{1,1}};
[num_of_column];
48
DAVINCI [C PROGRAMMING]
#include<stdio.h>
int main()
int i,j;
*/
for (i=0;i<2;i++)
{
{
}
}
Output:
C – String
C Strings are nothing but array of characters ended with null character (‘\0’).
This null character indicates the end of the string.
Strings are always enclosed by double quotes. Whereas, character is enclosed by single quotes in C.
49
DAVINCI [C PROGRAMMING]
char string[20] = { ‘f’ , ’r’ , ‘e’ , ‘s’ , ‘h’ , ‘2’ , ‘r’ , ‘e’ , ‘f’ , ’r’ , ‘e’ , ‘s’ , ‘h’ , ‘\0’}; (or)
char string[20] = “fresh2refresh”; (or)
char string [] = “fresh2refresh”;
Difference between above declarations are, when we declare char as “string[20]“, 20 bytes of memory space
is allocated for holding the string value.
When we declare char as “string[]“, memory space will be allocated as per the requirement during execution
of the program.
Example program for C string:
#include <stdio.h>
int main ()
return 0;
Output:
C String functions:
String.h header file supports all the string functions in C language. All the string functions are
given below.
String
S.no Description
functions
50
DAVINCI [C PROGRAMMING]
Same as strcmp() function. But, this function negotiates case. “A” and
7 strcmpi_(.)
“a” are treated as same.
C – strcat() function
strcat( ) function in C language concatenates two given strings. It concatenates source string at the end of
destination string. Syntax for strcat( ) function is given below.
char * strcat ( char * destination, const char * source );
Example :
strcat ( str2, str1 ); - str1 is concatenated at the end of str2.
strcat ( str1, str2 ); - str2 is concatenated at the end of str1.
51
DAVINCI [C PROGRAMMING]
In this program, two strings “fresh2refresh” and “C tutorial” are concatenated using strcat( )
function and result is displayed as “C tutorial fresh2refresh”.
#include <stdio.h>
#include <string.h>
int main( )
Output:
C – strcpy() function
strcpy( ) function copies contents of one string into another string. Syntax for strcpy function is given below.
char * strcpy ( char * destination, const char * source );
Example:
strcpy ( str1, str2) – It copies contents of str2 into str1.
strcpy ( str2, str1) – It copies contents of str1 into str2.
If destination string length is less than source string, entire source string value won’t be copied into
destination string.
For example, consider destination string length is 20 and source string length is 30. Then, only 20 characters
from source string will be copied into destination string and remaining 10 characters won’t be copied and will be
truncated.
Example program for strcpy( ) function in C:
In this program, source string “fresh2refresh” is copied into target string using strcpy( )
function.
52
DAVINCI [C PROGRAMMING]
#include <stdio.h>
#include <string.h>
int main( )
return 0;
Output:
C – strlen() function
strlen( ) function in C gives the length of the given string. Syntax for strlen( ) function is given below.
size_t strlen ( const char * str );
strlen( ) function counts the number of characters in a given string and returns the integer value.
It stops counting the character when null character is found. Because, null character indicates the end of the
string in C.
Example program for strlen() function in C:
In below example program, length of the string “fresh2refres.com” is determined by strlen( ) function as
below. Length of this string 17 is displayed as output.
#include <stdio.h>
#include <string.h>
int main( )
int len;
char array[20]="fresh2refresh.com" ;
len = strlen(array) ;
53
DAVINCI [C PROGRAMMING]
return 0;
Output:
string length = 17
C – strcmp() function
strcmp( ) function in C compares two given strings and returns zero if they are same.
If length of string1 < string2, it returns < 0 value. If length of string1 > string2, it returns > 0 value. Syntax for
strcmp( ) function is given below.
int strcmp ( const char * str1, const char * str2 );
strcmp( ) function is case sensitive. i.e, “A” and “a” are treated as different characters.
Example program for strcmp( ) function in C:
In this program, strings “fresh” and “refresh” are compared. 0 is returned when strings are
equal. Negative value is returned when str1 < str2 and positive value is returned when str1 > str2.
#include <stdio.h>
#include <string.h>
int main( )
int i, j, k ;
return 0;
Output:
0 -1 1
54
DAVINCI [C PROGRAMMING]
C – strlwr() function
strlwr( ) function converts a given string into lowercase. Syntax for strlwr( ) function is given below.
char *strlwr(char *string);
strlwr( ) function is non standard function which may not available in standard library in C.
In this program, string ”MODIFY This String To LOwer” is converted into lower case using
strlwr( ) function and result is displayed as “modify this string to lower”.
#include<stdio.h>
#include<string.h>
int main()
printf("%s\n",strlwr (str));
return 0;
Output:
C – strupr() function
strupr( ) function converts a given string into uppercase. Syntax for strupr( ) function is given below.
char *strupr(char *string);
strupr( ) function is non standard function which may not available in standard library in C.
Example program for strupr() function in C:
In this program, string ”Modify This String To Upper” is converted into uppercase using
strupr( ) function and result is displayed as “MODIFY THIS STRING TO UPPER”.
#include<stdio.h>
#include<string.h>
int main()
printf("%s\n",strupr(str));
return 0;
55
DAVINCI [C PROGRAMMING]
Output:
C – strrev() function
strrev( ) function reverses a given string in C language. Syntax for strrev( ) function is given below.
char *strrev(char *string);
strrev( ) function is non standard function which may not available in standard library in C.
Example program for strrev() function in C:
In below program, string “Hello” is reversed using strrev( ) function and output is displayed as “olleH”.
#include<stdio.h>
#include<string.h>
int main()
return 0;
Output:
C – Pointer
C Pointer is a variable that stores/points the address of the another variable.
C Pointer is used to allocate memory dynamically i.e. at run time.
The variable might be any of the data type such as int, float, char, double, short etc.
Syntax data_type *var_name;
Example : int *p; char *p;
Where, * is used to denote that “p” is pointer variable and not a normal variable.
Key points to remember about pointers in C:
Normal variable stores the value whereas pointer variable stores the address of the variable.
The content of the C pointer always be a whole number i.e. address.
Always C pointer is initialized to null, i.e. int *p = null.
56
DAVINCI [C PROGRAMMING]
#include <stdio.h>
int main()
int *ptr, q;
q = 50;
ptr = &q;
printf("%d", *ptr);
return 0;
Output:
50
C – Function
C functions are basic building blocks in a program. All C programs are written using functions to improve re-usability,
understandability and to keep track on them. You can learn below concepts of C functions in this section in detail.
1. What is C function?
2. Uses of C functions
3. C function declaration, function call and definition with example program
4. How to call C functions in a program?
Call by value
Call by reference
5. C function arguments and return values
C function with arguments and with return value
C function with arguments and without return value
C function without arguments and without return value
C function without arguments and with return value
6. Types of C functions
57
DAVINCI [C PROGRAMMING]
Library functions in C
User defined functions in C
Creating/Adding user defined function in C library
7. Command line arguments in C
8. Variable length arguments in C
1. What is C function?
A large C program is divided into basic building blocks called C function. C function contains set of instructions enclosed
by “{ }” which performs specific operation in a C program. Actually, Collection of these functions creates a C program.
2. Uses of C functions:
C functions are used to avoid rewriting same logic/code again and again in a program.
There is no limit in calling C functions to make use of same functionality wherever required.
We can call functions any number of times in a program and from any place in a program.
A large C program can easily be tracked when it is divided into functions.
The core concept of C functions are, re-usability, dividing a big task into small pieces to
achieve the functionality and to improve understandability of very large C programs.
3. C function declaration, function call and function definition:
Function declaration or prototype - This informs compiler about the function name, function
parameters and return value’s data type.
Function call – This calls the actual function
Function definition – This contains all the statements to be executed.
S.no C function aspects syntax
As you know, functions should be declared and defined before calling in a C program.
In the below program, function “square” is called from main function.
The value of “m” is passed as argument to the function “square”. This value is multiplied by
itself in this function and multiplied value “p” is returned to main function from function “square”.
#include<stdio.h>
58
DAVINCI [C PROGRAMMING]
float m, n ;
float p ;
p = x * x ;
return ( p ) ;
Output:
There are two ways that a C function can be called from a program. They are,
1. Call by value
2. Call by reference
1. Call by value:
In call by value method, the value of the variable is passed to the function as parameter.
The value of the actual parameter can not be modified by formal parameter.
Different Memory is allocated for both actual and formal parameters. Because, value of actual
parameter is copied to formal parameter.
Note:
59
DAVINCI [C PROGRAMMING]
In this program, the values of the variables “m” and “n” are passed to the function “swap”.
These values are copied to formal parameters “a” and “b” in swap function and used.
#include<stdio.h>
int main()
swap(m, n);
int tmp;
tmp = a;
a = b;
b = tmp;
Output:
2. Call by reference:
In call by reference method, the address of the variable is passed to the function as parameter.
The value of the actual parameter can be modified by formal parameter.
60
DAVINCI [C PROGRAMMING]
Same memory is used for both actual and formal parameters since only address is used by both
parameters.
Example program for C function (using call by reference):
In this program, the address of the variables “m” and “n” are passed to the function “swap”.
These values are not copied to formal parameters “a” and “b” in swap function.
Because, they are just holding the address of those variables.
This address is used to access and change the values of the variables.
#include<stdio.h>
int main()
swap(&m, &n);
}
int tmp;
tmp = *a;
*a = *b;
*b = tmp;
Output:
and n = 44
values after swap a = 44
and b = 22
61
DAVINCI [C PROGRAMMING]
Note:
If the return data type of a function is “void”, then, it can’t return any values to the calling
function.
If the return data type of the function is other than void such as “int, float, double etc”, then, it
can return values to the calling function.
1. Example program for with arguments & with return value:
In this program, integer, array and string are passed as arguments to the function. The return type of this
function is “int” and value of the variable “a” is returned from the function. The values for array and string are
modified inside the function itself.
#include<stdio.h>
#include<string.h>
62
DAVINCI [C PROGRAMMING]
int main()
int i, a = 20;
printf("value of a is %d\n",a);
for (i=0;i<5;i++)
{
}
printf("value of a is %d\n",a);
for (i=0;i<5;i++)
{
}
return 0;
int i;
a = a+20;
arr[0] = arr[0]+50;
63
DAVINCI [C PROGRAMMING]
arr[1] = arr[1]+50;
arr[2] = arr[2]+50;
arr[3] = arr[3]+50;
arr[4] = arr[4]+50;
strcpy(str,"\"modified string\"");
return a;
Output:
In this program, integer, array and string are passed as arguments to the function. The return type of this
function is “void” and no values can be returned from the function. All the values of integer, array and string are
manipulated and displayed inside the function itself.
#include<stdio.h>
int main()
int a = 20;
64
DAVINCI [C PROGRAMMING]
return 0;
int i;
printf("value of a is %d\n\n",a);
for (i=0;i<5;i++)
{
}
Output:
value of a is 20
value of arr[0] is 10
value of arr[1] is 20
value of arr[2] is 30
value of arr[3] is 40
value of arr[4] is 50
In this program, no values are passed to the function “test” and no values are returned from this function to
main function.
#include<stdio.h>
void test();
int main()
65
DAVINCI [C PROGRAMMING]
test();
return 0;
void test()
Output:
values : a = 50 and b = 80
In this program, no arguments are passed to the function “sum”. But, values are returned from this function to
main function. Values of the variable a and b are summed up in the function “sum” and the sum of these value is
returned to the main function.
#include<stdio.h>
int sum();
int main()
int addition;
addition = sum();
return 0;
int sum()
sum = a + b;
66
DAVINCI [C PROGRAMMING]
Output:
C – Structure
C Structure is a collection of different data types which are grouped together and each element in a C structure is
called member.
A normal C variable can hold only one data of one data type at a time.
An array can hold group of data of same data type.
A structure can hold group of data of different data types
Data types can be int, char, float, double and long double etc.
C variable C array C structure
Datatype
Syntax Example Syntax Example Syntax Example
a[0] = 10
a[1] = 20 struct student
int int a a = 20 int a[3] {
a[2] = 30 a = 10
a[3] = ‘\0′ int a;
b = “Hello”
char b[10];
}
char char b b=’Z’ char b[10] b=”Hello”
67
DAVINCI [C PROGRAMMING]
Declaring
struct student report; struct student *report, rep;
structure variable
This program is used to store and access “id, name and percentage” for one student. We can also store
and access these data for many students using array of structures. You can check “C – Array of Structures“ to
know how to store and access these data for many students.
#include <stdio.h>
#include <string.h>
struct student
};
int main()
record.id=1;
return 0;
68
DAVINCI [C PROGRAMMING]
Output:
Id is: 1
Name is: Raju
Percentage is: 86.500000
In this program, structure variable “record” is declared while declaring structure itself. In above structure
example program, structure variable “struct student record” is declared inside main function which is after
declaring structure.
#include <stdio.h>
#include <string.h>
struct student
int id;
char name[20];
float percentage;
} record;
int main()
record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;
return 0;
Output:
Id is: 1
Name is: Raju
69
DAVINCI [C PROGRAMMING]
In above structure programs, C structure is declared in main source file. Instead of declaring C structure in
main source file, we can have this structure declaration in another file called “header file” and we can include that
header file in main source file as shown below.
Before compiling and executing below C program, create a file named “structure.h” and declare the below
structure.
struct student
{
int id;
char name[20];
float percentage;
} record;
In this program, above created header file is included in “structure.c” source file as #include “Structure.h”.
So, the structure declared in “structure.h” file can be used in “structure.c” source file.
#include <stdio.h>
#include <string.h>
declared */
int main()
record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;
return 0;
70
DAVINCI [C PROGRAMMING]
Output:
Id is: 1
Name is: Raju
Percentage is: 86.500000
Uses of C structures:
2nd way :
When we use “typedef” keyword before struct <tag_name> like above, after that we can simply use type
definition “status” in the C program to declare structure variable.
Now, structure variable declaration will be, “status record”.
This is equal to “struct student record”. Type definition for “struct student” is status. i.e. status = “struct
student”
An alternative way for structure declaration using typedef in C:
71
DAVINCI [C PROGRAMMING]
#include <stdio.h>
#include <string.h>
int id;
char name[20];
float percentage;
} status;
int main()
status record;
record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;
return 0;
Output:
Id is: 1
Name is: Raju
Percentage is: 86.500000
Typedef can be used to simplify the real commands as per our need.
72
DAVINCI [C PROGRAMMING]
In above statement, LLI is the type definition for the real C command “long long int”. We can use type
definition LLI instead of using full command “long long int” in a C program once it is defined.
Another example program for C typedef:
#include <stdio.h>
#include <limits.h>
int main()
return 0;
Output:
C – Union
C Union is also like structure, i.e. collection of different data types which are grouped together. Each element in a
union is called member.
Union and structure in C are same in concepts, except allocating memory for their members.
Structure allocates storage space for all its members separately.
Whereas, Union allocates one common storage space for all its members
We can access only one member of union at a time. We can’t access all member values at the same time in
union. But, structure can access all member values at the same time. This is because, Union allocates one common
storage space for all its members. Where as Structure allocates storage space for all its members separately.
Many union variables can be created in a program and memory will be allocated for each union variable
separately.
Below table will help you how to form a C union, declare a union, initializing and accessing the members of
the union.
Type Using normal variable Using pointer variable
73
DAVINCI [C PROGRAMMING]
union student union student
{ {
int mark; int mark;
Example
char name[10]; char name[10];
float average; float average;
}; };
Declaring
union student report; union student *report, rep;
union variable
#include <stdio.h>
#include <string.h>
union student
char name[20];
char subject[20];
float percentage;
};
int main()
74
DAVINCI [C PROGRAMMING]
return 0;
Output:
There are 2 union variables declared in this program to understand the difference in accessing values of union members.
“Raju” is assigned to union member “record1.name” . The memory location name is “record1.name” and the
value stored in this location is “Raju”.
Then, “Maths” is assigned to union member “record1.subject”. Now, memory location name is changed to
“record1.subject” with the value “Maths” (Union can hold only one member at a time).
Then, “86.50” is assigned to union member “record1.percentage”. Now, memory location name is changed to
“record1.percentage” with value “86.50”.
Like this, name and value of union member is replaced every time on the common storage space.
So, we can always access only one union member for which value is assigned at last. We can’t access other
member values.
75
DAVINCI [C PROGRAMMING]
So, only “record1.percentage” value is displayed in output. “record1.name” and “record1.percentage” are
empty.
Record2 union variable:
If we want to access all member values using union, we have to access the member before assigning values to
other members as shown in record2 union variable in this program.
Each union members are accessed in record2 example immediately after assigning values to them.
If we don’t access them before assigning values to other member, member name and value will be over
written by other member as all members are using same memory.
We can’t access all members in union at same time but structure can do that.
Example program – Another way of declaring C union:
In this program, union variable “record” is declared while declaring union itself as shown in the below program.
#include <stdio.h>
#include <string.h>
union student
char name[20];
char subject[20];
float percentage;
}record;
int main()
strcpy(record.name, "Raju");
strcpy(record.subject, "Maths");
record.percentage = 86.50;
return 0;
Output:
Name :
Subject :
76
DAVINCI [C PROGRAMMING]
Percentage : 86.500000
Note:
We can access only one member of union at a time. We can’t access all member values at the same time in union. But,
structure can access all member values at the same time. This is because, Union allocates one common storage space for all
its members. Where as Structure allocates storage space for all its members separately.
77