#include <stdio.h>
#include <conio.h>
void main()
{
int i=0;
clrscr();
while(i<255)
{
printf("%d\t%c",i,i);
i=i+1;
}
getch();
}
Wednesday, February 27, 2013
Sunday, February 24, 2013
The C Preprocessor
The job of the C Preprocessor is to process the source code before it is passed to the compiler. The preprocessor command is also known as directive.
The C Program is often called as source code. Before the program is compiled, the source code goes through one process called preprocessor.
The preprocessor gets the source code (pr.C file) as input and creates expanded source code (pr.I file). This expanded source code is then passed to the compiler for compilation.
Following are the preprocessor directives:
Macro expansion
File inclusion
Conditional Compilation
Miscellaneous directives
Lets discuss these preprocessor directive one by one.
Macro expansion
Let us understand the macro expansion using an example.
Example:
#include<stdio.h>
#define TEN 10
void main()
{
int a = 10;
if (a == TEN)
{
printf("The value of a is 10");
}
}
If we run the above example, we will get the output as "The value of a is 10".
In the above example, we have used macro definition. As we learnt before, before compilation process the Source code goes through preprocessing process. During preprocessing, the program is scanned from top to bottom. Every occurrence of TEN in the source code is replaced by 10.
Thus, after preprocessing the program looks like give below,
#include<stdio.h>
void main()
{
int a = 10;
if (a == 10)
{
printf("The value of a is 10");
}
}
The preprocessor directive ‘#define’ can also be used to define operators as shown below.
#define AND &&
#define OR ||
After the definition of these operators we can use AND instead of && and OR instead of || within the program. This increases the readability of the program.
The above explained macro is called as ‘Simple macro’. There is another form of macro called ‘Macros with Arguments’.
Let us understand ‘Macros with Arguments’ with the help of an example.
Example:
#include<stdio.h>
#define AREA (3.14 * a * a)
void main()
{
int ar = AREA(10);
printf("Area = %f", ar);
}
If we run the above example, we will get the output as “AREA = 314.000000”.
In the above example, we have used macros with arguments. As we learnt, before compilation process the Source code goes through preprocessing process. During preprocessing, the program is scanned from top to bottom. Every occurrence of AREA(10) in the source code is replaced by (3.14 * 10 * 10).
Thus, after preprocessing the program looks like give below.
#include<stdio.h>
void main()
{
int ar = 3.14 * 10 * 10;
printf("Area = %f", ar);
}
Macros can be split into multiple lines using back slash (‘\’) as shown below.
#define DISPLAY for(i=0;i<10;i++) \
printf("This is a macro split into multiple lines");
File Inclusion
File inclusion directive causes one file to be included in another. We have already used file inclusion directive before. The preprocessor command for file inclusion looks like this:
#include “File name”
OR
#include <file name>
E.g. #include<stdio.h>
The above statement in C will include the file “stdio.h” in the program.
If the filename is enclosed within angle brackets, the file is searched for in the standard compiler include paths. If the filename is enclosed within double quotes, the search path is expanded to include the current source directory.
Conditional Compilation
The #if, #ifdef, #ifndef, #else, #elif and #endif directives can be used for conditional compilation.
If the macroname has been #defined, the block of code will be processed as usual.
If we use #if, #ifdef, #ifndef, #else, #elif or #endif directives, it will not be processed as usual. Using these directives we can have compiler to skip over part of a source code.
Let us understand the conditional compilation directives using an example.
Example:
#include<stdio.h>
void main()
{
#ifdef YES
Statement 1;
Statement 2;
#endif
Statement 3;
}
In the above example, statement 1 and statement 2 would be processed only if we define macro ‘YES’ else it won’t be processed.
As seen in the above program, macro ‘YES’ has not been defined. Hence, only statement 3 would be processed.
Example:
#include<stdio.h>
#define YES
void main()
{
#ifdef YES
Statement 1;
Statement 2;
#endif
Statement 3;
}
In the above example, statement 1, Statement 2 and Statement 3 would be processed as we have defined macro ‘YES’.
Example:
#include<stdio.h>
#define YES
void main()
{
#ifdef YES
Statement 1;
Statement 2;
#else
Statement 3;
#endif
}
The above example can be read as follows:
If macro ‘YES’ is defined then
Process Statement 1 and Statement 2
Else
Process Statement 3
The above example will process Statement 1 and Statement 2.
#ifndef (if not defined) is exactly opposite to #ifdef.
Example:
#include<stdio.h>
#define YES
void main()
{
#ifndef YES
Statement 1;
Statement 2;
#else
Statement 3;
#endif
}
The above example can be read as follows:
If macro ‘YES’ is not defined then
Process Statement 1 and Statement 2
Else
Process Statement 3
The above example will process Statement 3.
The #if directive can be used to test whether an expression evaluates to non zero or not. If the expression evaluates to non zero then the subsequent lines upto #else, #elif or #endif are compiled, otherwise they are skipped.
Example:
#include<stdio.h>
#define VALUE 5
void main()
{
#if VALUE == 5
Statement 1;
#elif VALUE <=10
Statement 2;
#else
Statement 3;
#endif
}
In the above program, if VALUE == 5 returns true then Statement 1 would be processed, else if VALUE <= 10 returns true then Statement 2 would be processed else Statement 3 would be processed.
Miscellaneous directive
#undef directive causes a defined name to become undefined. In order to undefined the macro that has been defined earlier, the directive, #undef macro name can be used. Thus, #undef VALUE would cause the definition of VALUE to be removed from the system.
#pragma directive is another very special and useful directive. This directive is used to specify diverse options to the compiler. These options are specific for the platform and the compiler you use.
If the compiler does not support a specific argument for #pragma, it is ignored - no error is generated. #pragma startup and #pragma exit are most commonly used pragma directives.
#pragma startup allows you to specify a particular function that are called upon program startup (before the execution of main()).
#pragma exit allows you to specify a function that can be called just before the program terminates.
Example:
void display1();
void display2();
#pragma startup display1
#pragma exit display2
void main()
{
printf(“I am in main”);
}
void display1()
{
printf(“I am in function1”);
}
void display2()
{
printf(“I am in function2”);
}
Output:
I am in function1
I am in main
I am in function2
Please provide your valuable comments about this article or anything related to this website. It would really help me in improving the website.
The C Program is often called as source code. Before the program is compiled, the source code goes through one process called preprocessor.
The preprocessor gets the source code (pr.C file) as input and creates expanded source code (pr.I file). This expanded source code is then passed to the compiler for compilation.
Following are the preprocessor directives:
Macro expansion
File inclusion
Conditional Compilation
Miscellaneous directives
Lets discuss these preprocessor directive one by one.
Macro expansion
Let us understand the macro expansion using an example.
Example:
#include<stdio.h>
#define TEN 10
void main()
{
int a = 10;
if (a == TEN)
{
printf("The value of a is 10");
}
}
If we run the above example, we will get the output as "The value of a is 10".
In the above example, we have used macro definition. As we learnt before, before compilation process the Source code goes through preprocessing process. During preprocessing, the program is scanned from top to bottom. Every occurrence of TEN in the source code is replaced by 10.
Thus, after preprocessing the program looks like give below,
#include<stdio.h>
void main()
{
int a = 10;
if (a == 10)
{
printf("The value of a is 10");
}
}
The preprocessor directive ‘#define’ can also be used to define operators as shown below.
#define AND &&
#define OR ||
After the definition of these operators we can use AND instead of && and OR instead of || within the program. This increases the readability of the program.
The above explained macro is called as ‘Simple macro’. There is another form of macro called ‘Macros with Arguments’.
Let us understand ‘Macros with Arguments’ with the help of an example.
Example:
#include<stdio.h>
#define AREA (3.14 * a * a)
void main()
{
int ar = AREA(10);
printf("Area = %f", ar);
}
If we run the above example, we will get the output as “AREA = 314.000000”.
In the above example, we have used macros with arguments. As we learnt, before compilation process the Source code goes through preprocessing process. During preprocessing, the program is scanned from top to bottom. Every occurrence of AREA(10) in the source code is replaced by (3.14 * 10 * 10).
Thus, after preprocessing the program looks like give below.
#include<stdio.h>
void main()
{
int ar = 3.14 * 10 * 10;
printf("Area = %f", ar);
}
Macros can be split into multiple lines using back slash (‘\’) as shown below.
#define DISPLAY for(i=0;i<10;i++) \
printf("This is a macro split into multiple lines");
File Inclusion
File inclusion directive causes one file to be included in another. We have already used file inclusion directive before. The preprocessor command for file inclusion looks like this:
#include “File name”
OR
#include <file name>
E.g. #include<stdio.h>
The above statement in C will include the file “stdio.h” in the program.
If the filename is enclosed within angle brackets, the file is searched for in the standard compiler include paths. If the filename is enclosed within double quotes, the search path is expanded to include the current source directory.
Conditional Compilation
The #if, #ifdef, #ifndef, #else, #elif and #endif directives can be used for conditional compilation.
If the macroname has been #defined, the block of code will be processed as usual.
If we use #if, #ifdef, #ifndef, #else, #elif or #endif directives, it will not be processed as usual. Using these directives we can have compiler to skip over part of a source code.
Let us understand the conditional compilation directives using an example.
Example:
#include<stdio.h>
void main()
{
#ifdef YES
Statement 1;
Statement 2;
#endif
Statement 3;
}
In the above example, statement 1 and statement 2 would be processed only if we define macro ‘YES’ else it won’t be processed.
As seen in the above program, macro ‘YES’ has not been defined. Hence, only statement 3 would be processed.
Example:
#include<stdio.h>
#define YES
void main()
{
#ifdef YES
Statement 1;
Statement 2;
#endif
Statement 3;
}
In the above example, statement 1, Statement 2 and Statement 3 would be processed as we have defined macro ‘YES’.
Example:
#include<stdio.h>
#define YES
void main()
{
#ifdef YES
Statement 1;
Statement 2;
#else
Statement 3;
#endif
}
The above example can be read as follows:
If macro ‘YES’ is defined then
Process Statement 1 and Statement 2
Else
Process Statement 3
The above example will process Statement 1 and Statement 2.
#ifndef (if not defined) is exactly opposite to #ifdef.
Example:
#include<stdio.h>
#define YES
void main()
{
#ifndef YES
Statement 1;
Statement 2;
#else
Statement 3;
#endif
}
The above example can be read as follows:
If macro ‘YES’ is not defined then
Process Statement 1 and Statement 2
Else
Process Statement 3
The above example will process Statement 3.
The #if directive can be used to test whether an expression evaluates to non zero or not. If the expression evaluates to non zero then the subsequent lines upto #else, #elif or #endif are compiled, otherwise they are skipped.
Example:
#include<stdio.h>
#define VALUE 5
void main()
{
#if VALUE == 5
Statement 1;
#elif VALUE <=10
Statement 2;
#else
Statement 3;
#endif
}
In the above program, if VALUE == 5 returns true then Statement 1 would be processed, else if VALUE <= 10 returns true then Statement 2 would be processed else Statement 3 would be processed.
Miscellaneous directive
#undef directive causes a defined name to become undefined. In order to undefined the macro that has been defined earlier, the directive, #undef macro name can be used. Thus, #undef VALUE would cause the definition of VALUE to be removed from the system.
#pragma directive is another very special and useful directive. This directive is used to specify diverse options to the compiler. These options are specific for the platform and the compiler you use.
If the compiler does not support a specific argument for #pragma, it is ignored - no error is generated. #pragma startup and #pragma exit are most commonly used pragma directives.
#pragma startup allows you to specify a particular function that are called upon program startup (before the execution of main()).
#pragma exit allows you to specify a function that can be called just before the program terminates.
Example:
void display1();
void display2();
#pragma startup display1
#pragma exit display2
void main()
{
printf(“I am in main”);
}
void display1()
{
printf(“I am in function1”);
}
void display2()
{
printf(“I am in function2”);
}
Output:
I am in function1
I am in main
I am in function2
Please provide your valuable comments about this article or anything related to this website. It would really help me in improving the website.
Demo on Structures in C
The Structure is a special type of C data type. A structure contains a number of data types grouped together. Structure in C allows multiple data types to be grouped together.
The below mentioned program is to demonstrate structures in C Programming Language.
#include<stdio.h>
#include<conio.h>
void main(){
struct animal{
int age;
char name[10];
char gender;
}a[10];
int no,i;
clrscr();
printf("Enter the number of animals: ");
scanf("%d",&no);
for(i=0;i<no;i++){
printf("\nEnter the age of animal %d: ", i+1);
scanf("%d",&a[i].age);
printf("\nEnter the name of animal %d: ",i+1);
scanf("%s",&a[i].name);
printf("\nEnter the gender(M/F) of animal %d: ",i+1);
scanf("%s",&a[i].gender);
}
for(i=0;i<no;i++){
printf("\n%d",a[i].age);
printf("\t%s",a[i].name);
printf("\t%c",a[i].gender);
}
getch();
}
Output:
Enter the number of animals: 2
Enter the age of animal 1: 06
Enter the name of animal 1: Sam
Enter the gender(M/F) of animal 1: M
Enter the age of animal 2: 05
Enter the name of animal 2: Maxie
Enter the gender(M/F) of animal 2: F
6 Sam M
5 Maxie F
The below mentioned program is to demonstrate structures in C Programming Language.
#include<stdio.h>
#include<conio.h>
void main(){
struct animal{
int age;
char name[10];
char gender;
}a[10];
int no,i;
clrscr();
printf("Enter the number of animals: ");
scanf("%d",&no);
for(i=0;i<no;i++){
printf("\nEnter the age of animal %d: ", i+1);
scanf("%d",&a[i].age);
printf("\nEnter the name of animal %d: ",i+1);
scanf("%s",&a[i].name);
printf("\nEnter the gender(M/F) of animal %d: ",i+1);
scanf("%s",&a[i].gender);
}
for(i=0;i<no;i++){
printf("\n%d",a[i].age);
printf("\t%s",a[i].name);
printf("\t%c",a[i].gender);
}
getch();
}
Output:
Enter the number of animals: 2
Enter the age of animal 1: 06
Enter the name of animal 1: Sam
Enter the gender(M/F) of animal 1: M
Enter the age of animal 2: 05
Enter the name of animal 2: Maxie
Enter the gender(M/F) of animal 2: F
6 Sam M
5 Maxie F
Structures in C Programming Language
The Structure is a special type of C data type. A structure contains a number of data types grouped together. Structure in C is one of the excellent functionality provided in C. Structure makes C Programming language easy and simpler up to certain extent. Structure is most widely used in Programming.
Structure in C allows multiple data types to be grouped together. As a programmer I have used structures in C a lot and find this feature interesting too. Just go through this article and you too will find structures in C interesting.
Let us suppose you want to store basic information about animal such as age, name, gender and birth place. There are two approaches that can be followed.
1) Use one array each to store properties of animal as shown below.
int age[10];
char name[10][20] ;
char gender[10];
char bPlace[10][20];
This approach is very tedious as number of characteristics related to animal might increase. Also, we need to keep the track of index of each and every variable. Hence, it becomes very difficult to handle such C programs.
2) Second approach is using structures in C.
At the end of this article you will understand the ease of using structures and its importance.
Declaring a Structure in C:
Structure in C is declared using the keyword ‘struct’.
Syntax:
struct <structure name>
{
Element 1;
Element 2;
Element 3;
.
.
.
Element n;
};
Please don’t forget to include semicolon (;) at the end of structure declaration as shown above.
For example, we can declare structure as follows:
struct animal
{
int age;
char *name;
char gender;
char *bPlace;
};
Here,
animal is the name given to structure.
age, name, gender and bPlace are the elements of the structure animal. We can call it as properties of the structure animal.
Declaring Structure variables:
Once the new structure data type has been defined, we can declare one or more variables of that type as shown below:
struct animal a1, a2;
This statement set aside space in memory.
Following are the ways in which we can declare structure variables.
1)
struct animal
{
int age;
char *name;
char gender;
char *bPlace;
}a1,a2;
2)
struct animal
{
int age;
char *name;
char gender;
char *bPlace;
};
struct animal a1, a2;
3)
struct animal
{
int age;
char *name;
char gender;
char *bPlace;
};
struct animal a1={12,”Sam”,’M’,”North America”};
struct animal a2={18,”Maxie”,’M’,”Amsterdam”};
Accessing structure Elements:
Now is the time to access structure elements after declaration of structure type and structure variables.
Syntax:
<structure variable>.<structure element>
Consider,
struct animal
{
int age;
char *name ;
char gender;
char *bPlace;
}a1,a2;
Now, element ‘age’ for the variable ‘a1’ can be accessed using the statement,
a1.age;
Similarly, element ‘name’ for the variable ‘a1’ can be accessed using the statement,
a1.name;
Array of Structures:
We can create array of structure variables as follows:
struct animal
{
int age;
char *name ;
char gender;
char *bPlace;
}a[100];
The above declaration can store information of not more than 100 animals.
The values can be accessed as follows:
a[0].age =10;
The above statement will assign value 10 to the element ‘age’ of structure variable a[0].
Similarly,
We can assign values to the elements of other structure variables too.
a[1].age=12;
We can print the values as follows:
printf(“%d”,a[1].age);
The above statement will display 12.
Structure in C allows multiple data types to be grouped together. As a programmer I have used structures in C a lot and find this feature interesting too. Just go through this article and you too will find structures in C interesting.
Let us suppose you want to store basic information about animal such as age, name, gender and birth place. There are two approaches that can be followed.
1) Use one array each to store properties of animal as shown below.
int age[10];
char name[10][20] ;
char gender[10];
char bPlace[10][20];
This approach is very tedious as number of characteristics related to animal might increase. Also, we need to keep the track of index of each and every variable. Hence, it becomes very difficult to handle such C programs.
2) Second approach is using structures in C.
At the end of this article you will understand the ease of using structures and its importance.
Declaring a Structure in C:
Structure in C is declared using the keyword ‘struct’.
Syntax:
struct <structure name>
{
Element 1;
Element 2;
Element 3;
.
.
.
Element n;
};
Please don’t forget to include semicolon (;) at the end of structure declaration as shown above.
For example, we can declare structure as follows:
struct animal
{
int age;
char *name;
char gender;
char *bPlace;
};
Here,
animal is the name given to structure.
age, name, gender and bPlace are the elements of the structure animal. We can call it as properties of the structure animal.
Declaring Structure variables:
Once the new structure data type has been defined, we can declare one or more variables of that type as shown below:
struct animal a1, a2;
This statement set aside space in memory.
Following are the ways in which we can declare structure variables.
1)
struct animal
{
int age;
char *name;
char gender;
char *bPlace;
}a1,a2;
2)
struct animal
{
int age;
char *name;
char gender;
char *bPlace;
};
struct animal a1, a2;
3)
struct animal
{
int age;
char *name;
char gender;
char *bPlace;
};
struct animal a1={12,”Sam”,’M’,”North America”};
struct animal a2={18,”Maxie”,’M’,”Amsterdam”};
Accessing structure Elements:
Now is the time to access structure elements after declaration of structure type and structure variables.
Syntax:
<structure variable>.<structure element>
Consider,
struct animal
{
int age;
char *name ;
char gender;
char *bPlace;
}a1,a2;
Now, element ‘age’ for the variable ‘a1’ can be accessed using the statement,
a1.age;
Similarly, element ‘name’ for the variable ‘a1’ can be accessed using the statement,
a1.name;
Array of Structures:
We can create array of structure variables as follows:
struct animal
{
int age;
char *name ;
char gender;
char *bPlace;
}a[100];
The above declaration can store information of not more than 100 animals.
The values can be accessed as follows:
a[0].age =10;
The above statement will assign value 10 to the element ‘age’ of structure variable a[0].
Similarly,
We can assign values to the elements of other structure variables too.
a[1].age=12;
We can print the values as follows:
printf(“%d”,a[1].age);
The above statement will display 12.
Storage Classes in C Programming Language
A storage class is an attribute that tells us where the variable would be stored, what will be the initial value of the variable if no value is assigned to that variable, life time of the variable and scope of the variable.
There are four storage classes in C:
1) Automatic storage class
2) Register storage class
3) Static storage class
4) External storage class
Automatic storage class:
The keyword used for Automatic storage class is 'auto'.
The variable declared as auto is stored in the memory.
Default value of that variable is garbage value.
Scope of that variable is local to the block in which the variable is defined.
Variable is alive till the control remains within the block in which the variable id defined.
Example:
#include<stdio.h>
#include<conio.h>
Void main(){
auto int a;
printf(“%d”,a)
}
Output:
1285
As seen above, the output is garbage value.
Register storage class:
The keyword used for Register storage class is 'register'.
The variable declared as register is stored in the CPU register.
Default value of that variable is garbage value.
Scope of that variable is local to the block in which the variable is defined.
Variable is alive till the control remains within the block in which the variable id defined.
Main difference between auto and register is that variable declared as auto is stored in memory whereas variable declared as register is stored in CPU register. Since the variable is stored in CPU register, it takes very less time to access that variable. Hence it becomes very time efficient.
It is not necessary that variable declared as register would be stored in CPU registers. The number of CPU registers is limited. If the CPU register is busy doing some other task then variable might act as automatic variable.
Example:
#include<stdio.h>
#include<conio.h>
Void main(){
register int a;
printf(“%d”,a)
}
Output:
4587
As seen above, the output is garbage value.
Static storage class:
The keyword used for Static storage class is 'static'.
The variable declared as static is stored in the memory.
Default value of that variable is zero.
Scope of that variable is local to the block in which the variable is defined.
Life of variable persists between different function calls.
External storage class:
The keyword used for External storage class is 'extern'.
The variable declared as static is stored in the memory.
Default value of that variable is zero.
Scope of that variable is global.
Variable is alive as long as the program’s execution doesn’t come to an end.
External variable can be declared outside all the functions or inside function using 'extern' keyword.
Example:
#include<stdio.h>
#include<conio.h>
int a;
Void main(){
extern int b;
printf(“%d %d”,a,b)
}
int b=10;
Output:
0 10
There are four storage classes in C:
1) Automatic storage class
2) Register storage class
3) Static storage class
4) External storage class
Automatic storage class:
The keyword used for Automatic storage class is 'auto'.
The variable declared as auto is stored in the memory.
Default value of that variable is garbage value.
Scope of that variable is local to the block in which the variable is defined.
Variable is alive till the control remains within the block in which the variable id defined.
Example:
#include<stdio.h>
#include<conio.h>
Void main(){
auto int a;
printf(“%d”,a)
}
Output:
1285
As seen above, the output is garbage value.
Register storage class:
The keyword used for Register storage class is 'register'.
The variable declared as register is stored in the CPU register.
Default value of that variable is garbage value.
Scope of that variable is local to the block in which the variable is defined.
Variable is alive till the control remains within the block in which the variable id defined.
Main difference between auto and register is that variable declared as auto is stored in memory whereas variable declared as register is stored in CPU register. Since the variable is stored in CPU register, it takes very less time to access that variable. Hence it becomes very time efficient.
It is not necessary that variable declared as register would be stored in CPU registers. The number of CPU registers is limited. If the CPU register is busy doing some other task then variable might act as automatic variable.
Example:
#include<stdio.h>
#include<conio.h>
Void main(){
register int a;
printf(“%d”,a)
}
Output:
4587
As seen above, the output is garbage value.
Static storage class:
The keyword used for Static storage class is 'static'.
The variable declared as static is stored in the memory.
Default value of that variable is zero.
Scope of that variable is local to the block in which the variable is defined.
Life of variable persists between different function calls.
External storage class:
The keyword used for External storage class is 'extern'.
The variable declared as static is stored in the memory.
Default value of that variable is zero.
Scope of that variable is global.
Variable is alive as long as the program’s execution doesn’t come to an end.
External variable can be declared outside all the functions or inside function using 'extern' keyword.
Example:
#include<stdio.h>
#include<conio.h>
int a;
Void main(){
extern int b;
printf(“%d %d”,a,b)
}
int b=10;
Output:
0 10
sscanf and sprintf functions
sscanf() function is used to extract strings from the given string.
Consider,
Char *str = "Online C Program";
If we want to extract " Online", "C" and " Program " in a different variable then it can be done using sscanf function.
Syntax:
sscanf(characterArray, "Conversion specifier", address of variables);
This will extract the data from the character array according to the conversion specifier and store into the respective variables.
sscanf() will read subsequent characters until a whitespace is found (whitespace characters are blank, newline and tab).
Let us understand this using an example.
char *str = " Online C Program ";
char *first, *second, *third;
sscanf(str, "%s %s %s",first,second,third);
In the above example,
" Online" will get stored in variable first
"C" will get stored in variable second
"Program" will get stored in variable third
sprintf() function is exactly opposite to sscanf() function. Sprint() function writes the formatted text to a character array.
Syntax:
sprintf (CharacterArray,"Conversion Specifier", variables);
Let us understand this using an example.
char *str;
char *first = " Online", *second = "C", *third = "Program";
sprintf(str, "%s %s %s",first,second,third);
In the above example, “ Online C Program ” will get stored in the character array str.
Consider,
Char *str = "Online C Program";
If we want to extract " Online", "C" and " Program " in a different variable then it can be done using sscanf function.
Syntax:
sscanf(characterArray, "Conversion specifier", address of variables);
This will extract the data from the character array according to the conversion specifier and store into the respective variables.
sscanf() will read subsequent characters until a whitespace is found (whitespace characters are blank, newline and tab).
Let us understand this using an example.
char *str = " Online C Program ";
char *first, *second, *third;
sscanf(str, "%s %s %s",first,second,third);
In the above example,
" Online" will get stored in variable first
"C" will get stored in variable second
"Program" will get stored in variable third
sprintf() function is exactly opposite to sscanf() function. Sprint() function writes the formatted text to a character array.
Syntax:
sprintf (CharacterArray,"Conversion Specifier", variables);
Let us understand this using an example.
char *str;
char *first = " Online", *second = "C", *third = "Program";
sprintf(str, "%s %s %s",first,second,third);
In the above example, “ Online C Program ” will get stored in the character array str.
String Handling Functions
Following are some of the useful string handling functions supported by C.
1) strlen()
2) strcpy()
3) strncpy()
4) strcat()
5) strncat()
6) strcmp()
7) strncmp()
8) strcmpi()
9) strncmpi()
These functions are defined in string.h header file. Hence you need to include this header file whenever you use these string handling functions in your program.
All these functions take either character pointer or character arrays as arguments.
strlen()
strlen() function returns the length of the string. strlen() function returns integer value.
Example:
char *str = "Learn C Online";
int strLength;
strLength = strlen(str); //strLength contains the length of the string i.e. 14
strcpy()
strcpy() function is used to copy one string to another. The Destination_String should be a variable and Source_String can either be a string constant or a variable.
Syntax:
strcpy(Destination_String,Source_String);
Example:
char *Destination_String;
char *Source_String = "Learn C Online";
strcpy(Destination_String,Source_String);
printf("%s", Destination_String);
Output:
Learn C Online
strncpy()
strncpy() is used to copy only the left most n characters from source to destination. The Destination_String should be a variable and Source_String can either be a string constant or a variable.
Syntax:
strncpy(Destination_String, Source_String,no_of_characters);
strcat()
strcat() is used to concatenate two strings.
The Destination_String should be a variable and Source_String can either be a string constant or a variable.
Syntax:
strcat(Destination_String, Source_String);
Example:
char *Destination_String ="Learn ";
char *Source_String = "C Online";
strcat(Destination_String, Source_String);
puts( Destination_String);
Output:
Learn C Online
strncat()
strncat() is used to concatenate only the leftmost n characters from source with the destination string.
The Destination_String should be a variable and Source_String can either be a string constant or a variable.
Syntax:
strncat(Destination_String, Source_String,no_of_characters);
Example:
char *Destination_String="Visit ";
char *Source_String = "Learn C Online is a great site";
strncat(Destination_String, Source_String,14);
puts( Destination_String);
Output:
Visit Learn C Online
strcmp()
strcmp() function is use two compare two strings. strcmp() function does a case sensitive comparison between two strings. The Destination_String and Source_String can either be a string constant or a variable.
Syntax:
int strcmp(string1, string2);
This function returns integer value after comparison.
Value returned is 0 if two strings are equal.
If the first string is alphabetically greater than the second string then, it returns a positive value.
If the first string is alphabetically less than the second string then, it returns a negative value
Example:
char *string1 = "Learn C Online";
char *string2 = "Learn C Online";
int ret;
ret=strcmp(string1, string2);
printf("%d",ret);
Output:
0
strncmp()
strncmp() is used to compare only left most ‘n’ characters from the strings.
Syntax:
int strncmp(string1, string2,no_of_chars);
This function returns integer value after comparison.
Value returned is 0 if left most ‘n’ characters of two strings are equal.
If the left most ‘n’ characters of first string is alphabetically greater than the left most ‘n’ characters of second string then, it returns a positive value.
If the left most ‘n’ characters of first string is alphabetically less than the left most ‘n’ characters of second string then, it returns a negative value
Example:
char *string1 = "Learn C Online is a great site";
char *string2 = "Learn C Online";
int ret;
ret=strncmp(string1, string2,7);
printf("%d",ret);
Output:
0
strcmpi()
strcmpi() function is use two compare two strings. strcmp() function does a case insensitive comparison between two strings. The Destination_String and Source_String can either be a string constant or a variable.
Syntax:
int strcmpi(string1, string2);
This function returns integer value after comparison.
Example:
char *string1 = “Learn C Online”;
char *string2 = “LEARN C ONLINE”;
int ret;
ret=strcmpi(string1, string2);
printf("%d",ret);
Output:
0
strncmpi()
strncmpi() is used to compare only left most ‘n’ characters from the strings. strncmpi() function does a case insensitive comparison.
Syntax:
int strncmpi(string1, string2,no_of_chars);
This function returns integer value after comparison.
Example:
char *string1 = "Learn C Online is a great site";
char *string2 = "LEARN C ONLINE";
int ret;
ret=strncmpi(string1, string2,7);
printf("%d",ret);
Output:
0
1) strlen()
2) strcpy()
3) strncpy()
4) strcat()
5) strncat()
6) strcmp()
7) strncmp()
8) strcmpi()
9) strncmpi()
These functions are defined in string.h header file. Hence you need to include this header file whenever you use these string handling functions in your program.
All these functions take either character pointer or character arrays as arguments.
strlen()
strlen() function returns the length of the string. strlen() function returns integer value.
Example:
char *str = "Learn C Online";
int strLength;
strLength = strlen(str); //strLength contains the length of the string i.e. 14
strcpy()
strcpy() function is used to copy one string to another. The Destination_String should be a variable and Source_String can either be a string constant or a variable.
Syntax:
strcpy(Destination_String,Source_String);
Example:
char *Destination_String;
char *Source_String = "Learn C Online";
strcpy(Destination_String,Source_String);
printf("%s", Destination_String);
Output:
Learn C Online
strncpy()
strncpy() is used to copy only the left most n characters from source to destination. The Destination_String should be a variable and Source_String can either be a string constant or a variable.
Syntax:
strncpy(Destination_String, Source_String,no_of_characters);
strcat()
strcat() is used to concatenate two strings.
The Destination_String should be a variable and Source_String can either be a string constant or a variable.
Syntax:
strcat(Destination_String, Source_String);
Example:
char *Destination_String ="Learn ";
char *Source_String = "C Online";
strcat(Destination_String, Source_String);
puts( Destination_String);
Output:
Learn C Online
strncat()
strncat() is used to concatenate only the leftmost n characters from source with the destination string.
The Destination_String should be a variable and Source_String can either be a string constant or a variable.
Syntax:
strncat(Destination_String, Source_String,no_of_characters);
Example:
char *Destination_String="Visit ";
char *Source_String = "Learn C Online is a great site";
strncat(Destination_String, Source_String,14);
puts( Destination_String);
Output:
Visit Learn C Online
strcmp()
strcmp() function is use two compare two strings. strcmp() function does a case sensitive comparison between two strings. The Destination_String and Source_String can either be a string constant or a variable.
Syntax:
int strcmp(string1, string2);
This function returns integer value after comparison.
Value returned is 0 if two strings are equal.
If the first string is alphabetically greater than the second string then, it returns a positive value.
If the first string is alphabetically less than the second string then, it returns a negative value
Example:
char *string1 = "Learn C Online";
char *string2 = "Learn C Online";
int ret;
ret=strcmp(string1, string2);
printf("%d",ret);
Output:
0
strncmp()
strncmp() is used to compare only left most ‘n’ characters from the strings.
Syntax:
int strncmp(string1, string2,no_of_chars);
This function returns integer value after comparison.
Value returned is 0 if left most ‘n’ characters of two strings are equal.
If the left most ‘n’ characters of first string is alphabetically greater than the left most ‘n’ characters of second string then, it returns a positive value.
If the left most ‘n’ characters of first string is alphabetically less than the left most ‘n’ characters of second string then, it returns a negative value
Example:
char *string1 = "Learn C Online is a great site";
char *string2 = "Learn C Online";
int ret;
ret=strncmp(string1, string2,7);
printf("%d",ret);
Output:
0
strcmpi()
strcmpi() function is use two compare two strings. strcmp() function does a case insensitive comparison between two strings. The Destination_String and Source_String can either be a string constant or a variable.
Syntax:
int strcmpi(string1, string2);
This function returns integer value after comparison.
Example:
char *string1 = “Learn C Online”;
char *string2 = “LEARN C ONLINE”;
int ret;
ret=strcmpi(string1, string2);
printf("%d",ret);
Output:
0
strncmpi()
strncmpi() is used to compare only left most ‘n’ characters from the strings. strncmpi() function does a case insensitive comparison.
Syntax:
int strncmpi(string1, string2,no_of_chars);
This function returns integer value after comparison.
Example:
char *string1 = "Learn C Online is a great site";
char *string2 = "LEARN C ONLINE";
int ret;
ret=strncmpi(string1, string2,7);
printf("%d",ret);
Output:
0
Strings in C
A string is a series of characters in a group that occupy contiguous memory. A group of characters (Alphabets, digits and special characters) is called as a string.
Example 1:
“Thank you for visiting www.learnconline.com”
“www.learnconline.com is excellent site for beginners.”
A string should always be enclosed with in double quotes (").
If single quote is used then it is treated as character. Hence 'A' is different from "A". Every string ends with a null character ('\0'). Note that \0 is a single character. So when it has to be explicitly assigned to a string, it has to be written with in single quotes as '\0'.
A null character occupies 1 byte of memory.
Syntax:
char str[num_of_characters];
Example 2:
char name[20];
The above statement declares an array named “name” capable of holding 20 characters. The 20th character is null character. Hence we can store 19 characters. The 20th character is reserved for null character.
Example 3:
char name[15]=”LearnCOnline”;
Here,
‘L’ is stored at name[0]
‘e’ is stored at name[1]
‘a’ is stored at name[2]
‘r’ is stored at name[3]
.
.
.
.
‘e’ is stored at name[11]
And finally,
‘\0’ is stored at name[12].
name[14] and name[15] will contain garbage value.
Example 4:
char name[]=”Learn C Online”;
Here the size of an array is calculated automatically (15 characters).
We can also declare string as character pointer as follows:
char *name = “Learn C Online”;
Printing Strings:
Using Character pointer:
char *name = “Learn C Online”;
printf(name);
printf(“%s”, name);
printf(“%s”,&name[0]);
Using Character Array:
char name[]=”Learn C Online”;
printf(name);
printf(“%s”, name);
printf(“%s”,& name[0]);
printf function can be used to print a string. Similarly, puts function can be used to print a string as shown below.
char name[]=”Learn C Online”;
puts(name);
Accepting String as input:
We can use scanf or gets to accepts string from the user.
Using scanf:
scanf(“%s”,name);
The above statement passes the base address implicitly.
scanf(“%s”,&name[0]);
In the above statement, we are passing the address of the first element.
Using gets:
gets(name);
gets(&name[0]);
Although scanf and gets seems to be the same, there is a big difference between them. Let’s understand this difference.
Program using scanf:
char *str;
printf(“Enter the string: ”);
scanf(“%s”,str);
printf(“\n%s”,str);
Output:
Enter the string: Learn C Online
Learn
Program using gets:
char *str;
printf(“Enter the string: ”);
gets(str);
printf(“\n%s”,str);
Output:
Enter the string: Learn C Online
Learn C Online
When a string is accepted using scanf function, if a space is encountered then it will treat it as null character(‘\0’). In the above example, a space encountered after “Learn” is treated as null character. Hence while printing, only “Learn” is printed.
This problem can be resolved using gets function.
Example 1:
“Thank you for visiting www.learnconline.com”
“www.learnconline.com is excellent site for beginners.”
A string should always be enclosed with in double quotes (").
If single quote is used then it is treated as character. Hence 'A' is different from "A". Every string ends with a null character ('\0'). Note that \0 is a single character. So when it has to be explicitly assigned to a string, it has to be written with in single quotes as '\0'.
A null character occupies 1 byte of memory.
Syntax:
char str[num_of_characters];
Example 2:
char name[20];
The above statement declares an array named “name” capable of holding 20 characters. The 20th character is null character. Hence we can store 19 characters. The 20th character is reserved for null character.
Example 3:
char name[15]=”LearnCOnline”;
Here,
‘L’ is stored at name[0]
‘e’ is stored at name[1]
‘a’ is stored at name[2]
‘r’ is stored at name[3]
.
.
.
.
‘e’ is stored at name[11]
And finally,
‘\0’ is stored at name[12].
name[14] and name[15] will contain garbage value.
Example 4:
char name[]=”Learn C Online”;
Here the size of an array is calculated automatically (15 characters).
We can also declare string as character pointer as follows:
char *name = “Learn C Online”;
Printing Strings:
Using Character pointer:
char *name = “Learn C Online”;
printf(name);
printf(“%s”, name);
printf(“%s”,&name[0]);
Using Character Array:
char name[]=”Learn C Online”;
printf(name);
printf(“%s”, name);
printf(“%s”,& name[0]);
printf function can be used to print a string. Similarly, puts function can be used to print a string as shown below.
char name[]=”Learn C Online”;
puts(name);
Accepting String as input:
We can use scanf or gets to accepts string from the user.
Using scanf:
scanf(“%s”,name);
The above statement passes the base address implicitly.
scanf(“%s”,&name[0]);
In the above statement, we are passing the address of the first element.
Using gets:
gets(name);
gets(&name[0]);
Although scanf and gets seems to be the same, there is a big difference between them. Let’s understand this difference.
Program using scanf:
char *str;
printf(“Enter the string: ”);
scanf(“%s”,str);
printf(“\n%s”,str);
Output:
Enter the string: Learn C Online
Learn
Program using gets:
char *str;
printf(“Enter the string: ”);
gets(str);
printf(“\n%s”,str);
Output:
Enter the string: Learn C Online
Learn C Online
When a string is accepted using scanf function, if a space is encountered then it will treat it as null character(‘\0’). In the above example, a space encountered after “Learn” is treated as null character. Hence while printing, only “Learn” is printed.
This problem can be resolved using gets function.
2-Dimensional Array in C Programming Language
An array is a collective name given to a group of similar variables. An array can be 1-Dimensional, 2-Dimensional, 3-Dimensional and so on. In this topic, we will discuss 2-Dimensional arrays in C Programming Language.
Let us understand what two dimensional arrays are. Consider the following matrix.
11 12 13
A= 14 15 16
17 18 19
The above mentioned matrix is 3 by 3. The matrix elements can be accessed using the formula A[m,n], where m represents row number and n represents column number.
Thus, the first element i.e. 11 is represented as A[0,0].
Similarly,
A[0,1] = 12
A[0,2] = 13
A[1,0] = 14
A[1,1] = 15 and so on.
The 2-dimensional array follows the similar concept. So we can declare 2-dimensional array for above matrix as A[3][3].
We can define 2-dimensional array as follows.
int A[3][3]={11,12,13,14,15,16,17,18,19}
Element 11 can be referred as A[0][0]
Element 12 can be referred as A[0][1]
Element 13 can be referred as A[0][2]
Element 14 can be referred as A[1][0]
Element 15 can be referred as A[1][1] and so on.
Another way to define 2-D array is:
int A[3][3]={
{11,12,13},
{14,15,16},
{17,18,19}
}
The above mentioned method increases the readability of the matrix.
int A[][] and A[3][] are invalid. We cannot skip the column index in 2-D arrays.
int A[][3] and A[3][3] are both valid.
SAMPLE PROGRAM:
Program that accept values in 2-Dimensional 3 by 3 array and displays the sum of all the elements.
void main(){
int arr[3][3], i, j, sum=0;
/*Accepts input from the user and stores it in 2-D array*/
for(i=0;i<3;i++){
for(j=0;j<3;j++){
printf(“\nEnter the value for A[%d][%d]: “,i,j);
scanf(“%d”,&arr[i][j]);
}
}
/*Calculate sum of elements in 2-D array*/
for(i=0;i<3;i++){
for(j=0;j<3;j++){
sum=sum+arr[i][j];
}
}
/*Display the value of sum*/
printf(“\nThe sum of the elements of 2-D array is %d”, sum);
}
Output:
Enter the value for A[0][0]: 1
Enter the value for A[0][1]: 2
Enter the value for A[0][2]: 3
Enter the value for A[1][0]: 4
Enter the value for A[1][1]: 5
Enter the value for A[1][2]: 6
Enter the value for A[2][0]: 7
Enter the value for A[2][1]: 8
Enter the value for A[2][2]: 9
The sum of the elements of 2-D array is 45
Explanation:
There are two for loops. The first one accepts input from the user and stores it in 2-D array.
The second one Calculates the sum of the elements present in 2-D array.
for(i=0;i<3;i++){
for(j=0;j<3;j++){
printf(“\nEnter the value for A[%d][%d]: “,i,j);
scanf(“%d”,&arr[i][j]);
}
}
Let us understand the above for loop iteration wise.
1st Iteration of Outer for loop:
Value of i=0. Condition i<3 is satisfied. Hence it enters this for loop.
1st Iteration of Inner for loop:
Value of j=0. Condition j<3 is satisfied. Hence it enters this for loop.
Here the value entered by the user is assigned to the variable arr[i][j] i.e. arr[0][0].
2nd Iteration of Inner for loop:
Value of j is incremented. Hence j=1. Condition j<3 is satisfied. Hence it enters this for loop.
Here the value entered by the user is assigned to the variable arr[i][j] i.e. arr[0][1].
3rd Iteration of Inner for loop:
Value of j is incremented. Hence j=2. Condition j<3 is satisfied. Hence it enters this for loop.
Here the value entered by the user is assigned to the variable arr[i][j] i.e. arr[0][2].
Now the value of j is again incremented. Hence j=3. But, the condition j<3 is not satisfied.
Hence it exits this inner for loop.
2nd Iteration of Outer for loop:
Value of i=1. Condition i<3 is satisfied. Hence it enters this for loop.
1st Iteration of Inner for loop:
Value of j=0. Condition j<3 is satisfied. Hence it enters this for loop.
Here the value entered by the user is assigned to the variable arr[i][j] i.e. arr[1][0].
2nd Iteration of Inner for loop:
Value of j is incremented. Hence j=1. Condition j<3 is satisfied. Hence it enters this for loop.
Here the value entered by the user is assigned to the variable arr[i][j] i.e. arr[1][1].
3rd Iteration of Inner for loop:
Value of j is incremented. Hence j=2. Condition j<3 is satisfied. Hence it enters this for loop.
Here the value entered by the user is assigned to the variable arr[i][j] i.e. arr[1][2].
Now the value of j is again incremented. Hence j=3. But, the condition j<3 is not satisfied.
Hence it exits this inner for loop.
3rd Iteration of Outer for loop:
Value of i=2. Condition i<3 is satisfied. Hence it enters this for loop.
1st Iteration of Inner for loop:
Value of j=0. Condition j<3 is satisfied. Hence it enters this for loop.
Here the value entered by the user is assigned to the variable arr[i][j] i.e. arr[2][0].
2nd Iteration of Inner for loop:
Value of j is incremented. Hence j=1. Condition j<3 is satisfied. Hence it enters this for loop.
Here the value entered by the user is assigned to the variable arr[i][j] i.e. arr[2][1].
3rd Iteration of Inner for loop:
Value of j is incremented. Hence j=2. Condition j<3 is satisfied. Hence it enters this for loop.
Here the value entered by the user is assigned to the variable arr[i][j] i.e. arr[2][2].
Now the value of j is again incremented. Hence j=3. But, the condition j<3 is not satisfied.
Hence it exits this inner for loop.
Now the value of i is again incremented. Hence i=3. But, the condition i<3 is not satisfied. Hence it exits this outer for loop.
Similar logic applies while calculating the addition of the array elements.
Let us understand what two dimensional arrays are. Consider the following matrix.
11 12 13
A= 14 15 16
17 18 19
The above mentioned matrix is 3 by 3. The matrix elements can be accessed using the formula A[m,n], where m represents row number and n represents column number.
Thus, the first element i.e. 11 is represented as A[0,0].
Similarly,
A[0,1] = 12
A[0,2] = 13
A[1,0] = 14
A[1,1] = 15 and so on.
The 2-dimensional array follows the similar concept. So we can declare 2-dimensional array for above matrix as A[3][3].
We can define 2-dimensional array as follows.
int A[3][3]={11,12,13,14,15,16,17,18,19}
Element 11 can be referred as A[0][0]
Element 12 can be referred as A[0][1]
Element 13 can be referred as A[0][2]
Element 14 can be referred as A[1][0]
Element 15 can be referred as A[1][1] and so on.
Another way to define 2-D array is:
int A[3][3]={
{11,12,13},
{14,15,16},
{17,18,19}
}
The above mentioned method increases the readability of the matrix.
int A[][] and A[3][] are invalid. We cannot skip the column index in 2-D arrays.
int A[][3] and A[3][3] are both valid.
SAMPLE PROGRAM:
Program that accept values in 2-Dimensional 3 by 3 array and displays the sum of all the elements.
void main(){
int arr[3][3], i, j, sum=0;
/*Accepts input from the user and stores it in 2-D array*/
for(i=0;i<3;i++){
for(j=0;j<3;j++){
printf(“\nEnter the value for A[%d][%d]: “,i,j);
scanf(“%d”,&arr[i][j]);
}
}
/*Calculate sum of elements in 2-D array*/
for(i=0;i<3;i++){
for(j=0;j<3;j++){
sum=sum+arr[i][j];
}
}
/*Display the value of sum*/
printf(“\nThe sum of the elements of 2-D array is %d”, sum);
}
Output:
Enter the value for A[0][0]: 1
Enter the value for A[0][1]: 2
Enter the value for A[0][2]: 3
Enter the value for A[1][0]: 4
Enter the value for A[1][1]: 5
Enter the value for A[1][2]: 6
Enter the value for A[2][0]: 7
Enter the value for A[2][1]: 8
Enter the value for A[2][2]: 9
The sum of the elements of 2-D array is 45
Explanation:
There are two for loops. The first one accepts input from the user and stores it in 2-D array.
The second one Calculates the sum of the elements present in 2-D array.
for(i=0;i<3;i++){
for(j=0;j<3;j++){
printf(“\nEnter the value for A[%d][%d]: “,i,j);
scanf(“%d”,&arr[i][j]);
}
}
Let us understand the above for loop iteration wise.
1st Iteration of Outer for loop:
Value of i=0. Condition i<3 is satisfied. Hence it enters this for loop.
1st Iteration of Inner for loop:
Value of j=0. Condition j<3 is satisfied. Hence it enters this for loop.
Here the value entered by the user is assigned to the variable arr[i][j] i.e. arr[0][0].
2nd Iteration of Inner for loop:
Value of j is incremented. Hence j=1. Condition j<3 is satisfied. Hence it enters this for loop.
Here the value entered by the user is assigned to the variable arr[i][j] i.e. arr[0][1].
3rd Iteration of Inner for loop:
Value of j is incremented. Hence j=2. Condition j<3 is satisfied. Hence it enters this for loop.
Here the value entered by the user is assigned to the variable arr[i][j] i.e. arr[0][2].
Now the value of j is again incremented. Hence j=3. But, the condition j<3 is not satisfied.
Hence it exits this inner for loop.
2nd Iteration of Outer for loop:
Value of i=1. Condition i<3 is satisfied. Hence it enters this for loop.
1st Iteration of Inner for loop:
Value of j=0. Condition j<3 is satisfied. Hence it enters this for loop.
Here the value entered by the user is assigned to the variable arr[i][j] i.e. arr[1][0].
2nd Iteration of Inner for loop:
Value of j is incremented. Hence j=1. Condition j<3 is satisfied. Hence it enters this for loop.
Here the value entered by the user is assigned to the variable arr[i][j] i.e. arr[1][1].
3rd Iteration of Inner for loop:
Value of j is incremented. Hence j=2. Condition j<3 is satisfied. Hence it enters this for loop.
Here the value entered by the user is assigned to the variable arr[i][j] i.e. arr[1][2].
Now the value of j is again incremented. Hence j=3. But, the condition j<3 is not satisfied.
Hence it exits this inner for loop.
3rd Iteration of Outer for loop:
Value of i=2. Condition i<3 is satisfied. Hence it enters this for loop.
1st Iteration of Inner for loop:
Value of j=0. Condition j<3 is satisfied. Hence it enters this for loop.
Here the value entered by the user is assigned to the variable arr[i][j] i.e. arr[2][0].
2nd Iteration of Inner for loop:
Value of j is incremented. Hence j=1. Condition j<3 is satisfied. Hence it enters this for loop.
Here the value entered by the user is assigned to the variable arr[i][j] i.e. arr[2][1].
3rd Iteration of Inner for loop:
Value of j is incremented. Hence j=2. Condition j<3 is satisfied. Hence it enters this for loop.
Here the value entered by the user is assigned to the variable arr[i][j] i.e. arr[2][2].
Now the value of j is again incremented. Hence j=3. But, the condition j<3 is not satisfied.
Hence it exits this inner for loop.
Now the value of i is again incremented. Hence i=3. But, the condition i<3 is not satisfied. Hence it exits this outer for loop.
Similar logic applies while calculating the addition of the array elements.
1-Dimensional Array in C Programming Language
An array is a collective name given to a group of similar variables.
An array can be 1-Dimensional, 2-Dimensional, 3-Dimensional and so on. In this topic, we will discuss 1-Dimensional arrays in C Programming Language. So lets start with 1-Dimensional array.
Let us understand this with the help of an example.
void main(){
int arr[3],i;
printf(“Enter 3 values\n”);
for(i=0;i<3;i++){
scanf(“%d”,&arr[i])
}
printf(“The entered values are:\n”);
for(i=0;i<10;i++){
printf(“%d\t”,arr[i])
}
}
Explanation:
int arr[3] statement declares an array capable of holding 3 integer values. The first value can be accessed using arr[0]. Similarly second value can be accessed using arr[1]. Note that the number enclosed in [] is called index value. The index value of array in C always starts from 0.
So,
First element --> arr[0]
Second element --> arr[1]
Third element --> arr[2]
nth element --> arr[n-1]
When an array is declared, a garbage value is stored in it. Thus, accessing the value of array elements without defining it will give garbage value.
for(i=0;i<3;i++){
scanf(“%d”,&arr[i])
}
The above for loop accepts the value from the user and stores it in an array. The array that was declared before is getting defined here.
Thus,
First value corresponding to 1st iteration of for loop is stored in the element arr[0]
Second value corresponding to 2nd iteration of for loop is stored in the element arr[1]
Third value corresponding to 3rd iteration of for loop is stored in the element arr[2]
for(i=0;i<3;i++){
printf(“%d\t”,arr[i])
}
The above for loop displays the value stored in the array.
Thus,
1st iteration displays value stored in arr[0]
2nd iteration displays value stored in arr[1]
3rd iteration displays value stored in arr[2]
In the above program, we have used data type int for the array. Hence it is called integer array. We can also declare array as float. But then it will contain float values. An array element can only hold one type of data i.e. either integer or float or character.
Consider this program,
void main(){
int arr[3];
arr[0] = 1;
arr[1] = 2;
arr[2] = 3;
}
Let us suppose that base address of this array is 6000. So value 1 is stored at memory location 6000. Since it is integer array, 16 bit C compiler will assign 2 bytes of memory for its storage. Hence next value i.e. 2 will be stored at location 6002. Similarly, 3 will be stored at location 6004.
An array can be defined as follows:
int arr[3]={1,2,3};
i.e., arr[0] --> 1
arr[1] --> 2
arr[2] --> 3
An array can also be defined as:
int arr[]={1,2,3}
An array can be 1-Dimensional, 2-Dimensional, 3-Dimensional and so on. In this topic, we will discuss 1-Dimensional arrays in C Programming Language. So lets start with 1-Dimensional array.
Let us understand this with the help of an example.
void main(){
int arr[3],i;
printf(“Enter 3 values\n”);
for(i=0;i<3;i++){
scanf(“%d”,&arr[i])
}
printf(“The entered values are:\n”);
for(i=0;i<10;i++){
printf(“%d\t”,arr[i])
}
}
Explanation:
int arr[3] statement declares an array capable of holding 3 integer values. The first value can be accessed using arr[0]. Similarly second value can be accessed using arr[1]. Note that the number enclosed in [] is called index value. The index value of array in C always starts from 0.
So,
First element --> arr[0]
Second element --> arr[1]
Third element --> arr[2]
nth element --> arr[n-1]
When an array is declared, a garbage value is stored in it. Thus, accessing the value of array elements without defining it will give garbage value.
for(i=0;i<3;i++){
scanf(“%d”,&arr[i])
}
The above for loop accepts the value from the user and stores it in an array. The array that was declared before is getting defined here.
Thus,
First value corresponding to 1st iteration of for loop is stored in the element arr[0]
Second value corresponding to 2nd iteration of for loop is stored in the element arr[1]
Third value corresponding to 3rd iteration of for loop is stored in the element arr[2]
for(i=0;i<3;i++){
printf(“%d\t”,arr[i])
}
The above for loop displays the value stored in the array.
Thus,
1st iteration displays value stored in arr[0]
2nd iteration displays value stored in arr[1]
3rd iteration displays value stored in arr[2]
In the above program, we have used data type int for the array. Hence it is called integer array. We can also declare array as float. But then it will contain float values. An array element can only hold one type of data i.e. either integer or float or character.
Consider this program,
void main(){
int arr[3];
arr[0] = 1;
arr[1] = 2;
arr[2] = 3;
}
Let us suppose that base address of this array is 6000. So value 1 is stored at memory location 6000. Since it is integer array, 16 bit C compiler will assign 2 bytes of memory for its storage. Hence next value i.e. 2 will be stored at location 6002. Similarly, 3 will be stored at location 6004.
An array can be defined as follows:
int arr[3]={1,2,3};
i.e., arr[0] --> 1
arr[1] --> 2
arr[2] --> 3
An array can also be defined as:
int arr[]={1,2,3}
Pointer Operations Demo
#include<stdio.h>
#include<conio.h>
void main(){
int arr[5]={12,13,14,15,16};
int *ptrArr, *ptrArr1,i;
clrscr();
ptrArr = arr;
printf("\nPrinting the first element of array: %d\n\n",*ptrArr);
Pointer variable can be increased. If added 1 to it, it will point to the
next element of the same array
for(i=0;i<5;i++){
printf("%d\t", *ptrArr);
ptrArr++;
}
printf("\n\n");
Now the Pointer is pointing to a memory location that is not reserved
so if you will print the value at pointer location it will print garbage
and some times it show any RUN TIME error because C compiler will not
check array boundaries
printf("Printing value at pointer location that is not reserved by the program\n");
printf("%d This is garbage\n\n",*ptrArr);
Pointer varible can be decreased and if we are decreasing 1 to it,
it will start pointing to the previous element in the same array
for(i=0;i<5;i++){
ptrArr--;
printf("%d\t", *ptrArr);
}
printf("\n\n");
Now, ptrArr will point to 3rd element of array
ptrArr = &arr[2];
printf("\nThird element of an array : %d",*ptrArr);
One pointer can be subtracted from another if they are poining to
elements of same array and the operation will return no of elements
in between these two pointer locations
ptrArr1 = &arr[5];
printf("\n\nSubtraction of two pointers ptrArr1 - ptrArr : %d\n",ptrArr1 - ptrArr);
getch();
}
Note:
Two Pointers cannot be added
A pointer cannot be multipled with a number
A pointer cannot be divided by a number
Output:
Printing the first element of array: 12
12 13 14 15 16
Printing value at pointer location that is not reserved by the program
0 This is garbage
16 15 14 13 12
Third element of an array : 14
Subtraction of two pointers ptrArr1 - ptrArr : 2
#include<conio.h>
void main(){
int arr[5]={12,13,14,15,16};
int *ptrArr, *ptrArr1,i;
clrscr();
ptrArr = arr;
printf("\nPrinting the first element of array: %d\n\n",*ptrArr);
Pointer variable can be increased. If added 1 to it, it will point to the
next element of the same array
for(i=0;i<5;i++){
printf("%d\t", *ptrArr);
ptrArr++;
}
printf("\n\n");
Now the Pointer is pointing to a memory location that is not reserved
so if you will print the value at pointer location it will print garbage
and some times it show any RUN TIME error because C compiler will not
check array boundaries
printf("Printing value at pointer location that is not reserved by the program\n");
printf("%d This is garbage\n\n",*ptrArr);
Pointer varible can be decreased and if we are decreasing 1 to it,
it will start pointing to the previous element in the same array
for(i=0;i<5;i++){
ptrArr--;
printf("%d\t", *ptrArr);
}
printf("\n\n");
Now, ptrArr will point to 3rd element of array
ptrArr = &arr[2];
printf("\nThird element of an array : %d",*ptrArr);
One pointer can be subtracted from another if they are poining to
elements of same array and the operation will return no of elements
in between these two pointer locations
ptrArr1 = &arr[5];
printf("\n\nSubtraction of two pointers ptrArr1 - ptrArr : %d\n",ptrArr1 - ptrArr);
getch();
}
Note:
Two Pointers cannot be added
A pointer cannot be multipled with a number
A pointer cannot be divided by a number
Output:
Printing the first element of array: 12
12 13 14 15 16
Printing value at pointer location that is not reserved by the program
0 This is garbage
16 15 14 13 12
Third element of an array : 14
Subtraction of two pointers ptrArr1 - ptrArr : 2
Saturday, February 23, 2013
Pointers in C Programming
Pointers is one of the excellent feature introduced in C. It makes the programming very interesting.
Talking like a layman, pointers points to an object or something.
Let us understand the pointers in detail.
Before learning the basics of pointer, let us understand how the variable is stored in the memory.
When we declare a variable and assign a value to the variable, we are actually naming the memory location at which the value will be stored. The value will be stored at the memory location and not in the variable.
We can display this address using ampersand(&) as follows:
int a=10;
printf(“%u”,&a) ; //displays the address of the variable a
printf(“%d”,*(&a)); //displays the content at that address
In the above code snippet,
Value 10 is assigned to the variable a. Internally, a is the name give to the memory address.
Using ampersand we can print the address of a as shown above.
Similarly, we can display the content at that address using *. The ‘*(&a)’ is read as “content at address of a”.
This address can be stored in a variable as follows.
b = &a;
As we all know that we should declare a variable before using it, we cannot directly use it to assign an address.
As the variable b is pointing to the memory location, there is different way to declare this variable. This declaration can be done as follows:
int *b;
b = &a;
Here, b is pointing to the memory address. Hence, b is called a pointer.
After assigning the address to the pointer variable b, we can get the value at the address at which it is pointing using *.
Let us understand the pointer in detail using an example.
Example:
void main(){
int *b, a=10;
b=&a;
printf(“\nThe address of a : %u”, b);
printf(“\nThe address of a : %u”,&a);
printf("\nThe address of a : %u",*(&b));
printf(“\nThe value of a : %d”,a);
printf(“\nThe value of a : %d”,*b);
printf(“\nThe value of a : %d”,*(&a));
}
Output:
The address of a : 65524
The address of a : 65524
The address of a : 65524
The value of a : 10
The value of a : 10
The value of a : 10
Let us understand the concept of pointers to pointer. Pointers to pointer is a pointer that points to another pointer. Here pointer will store the address of another pointer.
Let us understand this using an example.
Example:
void main(){
int *b, a=10, **c;
clrscr();
b=&a;
c=&b;
printf("\nThe address of a : %u", b);
printf("\nThe address of a : %u",&a);
printf("\nThe address of a : %u",*(&b));
printf("\nThe address of a : %u",*c);
printf("\nThe value of a : %d",a);
printf("\nThe value of a : %d",*b);
printf("\nThe value of a : %d",*(&a));
printf("\nThe value of a : %d",*(*c));
getch();
}
Output:
The address of a : 65524
The address of a : 65524
The address of a : 65524
The address of a : 65524
The value of a : 10
The value of a : 10
The value of a : 10
The value of a : 10
Talking like a layman, pointers points to an object or something.
Let us understand the pointers in detail.
Before learning the basics of pointer, let us understand how the variable is stored in the memory.
When we declare a variable and assign a value to the variable, we are actually naming the memory location at which the value will be stored. The value will be stored at the memory location and not in the variable.
We can display this address using ampersand(&) as follows:
int a=10;
printf(“%u”,&a) ; //displays the address of the variable a
printf(“%d”,*(&a)); //displays the content at that address
In the above code snippet,
Value 10 is assigned to the variable a. Internally, a is the name give to the memory address.
Using ampersand we can print the address of a as shown above.
Similarly, we can display the content at that address using *. The ‘*(&a)’ is read as “content at address of a”.
This address can be stored in a variable as follows.
b = &a;
As we all know that we should declare a variable before using it, we cannot directly use it to assign an address.
As the variable b is pointing to the memory location, there is different way to declare this variable. This declaration can be done as follows:
int *b;
b = &a;
Here, b is pointing to the memory address. Hence, b is called a pointer.
After assigning the address to the pointer variable b, we can get the value at the address at which it is pointing using *.
Let us understand the pointer in detail using an example.
Example:
void main(){
int *b, a=10;
b=&a;
printf(“\nThe address of a : %u”, b);
printf(“\nThe address of a : %u”,&a);
printf("\nThe address of a : %u",*(&b));
printf(“\nThe value of a : %d”,a);
printf(“\nThe value of a : %d”,*b);
printf(“\nThe value of a : %d”,*(&a));
}
Output:
The address of a : 65524
The address of a : 65524
The address of a : 65524
The value of a : 10
The value of a : 10
The value of a : 10
Let us understand the concept of pointers to pointer. Pointers to pointer is a pointer that points to another pointer. Here pointer will store the address of another pointer.
Let us understand this using an example.
Example:
void main(){
int *b, a=10, **c;
clrscr();
b=&a;
c=&b;
printf("\nThe address of a : %u", b);
printf("\nThe address of a : %u",&a);
printf("\nThe address of a : %u",*(&b));
printf("\nThe address of a : %u",*c);
printf("\nThe value of a : %d",a);
printf("\nThe value of a : %d",*b);
printf("\nThe value of a : %d",*(&a));
printf("\nThe value of a : %d",*(*c));
getch();
}
Output:
The address of a : 65524
The address of a : 65524
The address of a : 65524
The address of a : 65524
The value of a : 10
The value of a : 10
The value of a : 10
The value of a : 10
Prototype
As we all know, before using a variable we need to declare it. Similarly, before using a function we need to declare the function. This declaration of the function is called as function prototyping.
Consider the above program. There is one statement before the main() function.
The statement is: float fnGetAverage(int, int);
This statement is called function prototype. By doing this we are telling the compiler that we will use the function having following features:
1) The function name would be fnGetAverage
2) The function will return float value
3) The function will contain two int arguments.
If we do not wish to use function prototyping then we need to define the function before calling it. This can be done as follows:
float fnGetAverage(int a, int b){ //function definition
float c;
c = (a+b)/2; //calculating average
return c; //returning the value
}
void main(){
int x,y;
float z;
printf(“\nEnter the values for x and y”);
scanf(“%d %d”, &x, &y);
z = fnGetAverage(x, y); //function call
printf(“\nThe average is %d”, z);
}
Consider the above program. There is one statement before the main() function.
The statement is: float fnGetAverage(int, int);
This statement is called function prototype. By doing this we are telling the compiler that we will use the function having following features:
1) The function name would be fnGetAverage
2) The function will return float value
3) The function will contain two int arguments.
If we do not wish to use function prototyping then we need to define the function before calling it. This can be done as follows:
float fnGetAverage(int a, int b){ //function definition
float c;
c = (a+b)/2; //calculating average
return c; //returning the value
}
void main(){
int x,y;
float z;
printf(“\nEnter the values for x and y”);
scanf(“%d %d”, &x, &y);
z = fnGetAverage(x, y); //function call
printf(“\nThe average is %d”, z);
}
Function declaration and Prototype
By default, any C function returns an int value. If we want that the function should return a value other than int then we need to explicitly mention it in the function definition. Let us understand this using an example.
Example 1:
float fnGetAverage(int, int); //function prototype
void main(){
int x,y;
float z;
printf(“\nEnter the values for x and y\n”);
scanf(“%d %d”, &x, &y);
z = fnGetAverage(x,y); //function call
printf(“\nThe average is %f”, z);
}
float fnGetAverage(int a, int b){ //function definition
float c;
c = (a+b)/2; //calculating average
return c; //returning the value
}
Output:
Enter the values for x and y
3 2
The average is 2.500000
Example 1:
float fnGetAverage(int, int); //function prototype
void main(){
int x,y;
float z;
printf(“\nEnter the values for x and y\n”);
scanf(“%d %d”, &x, &y);
z = fnGetAverage(x,y); //function call
printf(“\nThe average is %f”, z);
}
float fnGetAverage(int a, int b){ //function definition
float c;
c = (a+b)/2; //calculating average
return c; //returning the value
}
Output:
Enter the values for x and y
3 2
The average is 2.500000
Functions in C Programming
Let us suppose that we want to write a program that will perform all the operations required for banking. So we will have to write a program that will have following steps:
• Accept account number and other personal details of the customer as a input
• Accept the details of the transactions to be performed
• If the customer wants to withdraw the money, then program should fetch the balance amount and perform eligibility check.
• After performing eligibility check, the money is deducted from that person’s account and the details of the transaction are updated in the database.
If we write the code for the above mentioned steps, it becomes very lengthy code. The solution to get rid of such lengthy code is the use of functions.
A function is a self contained block of statements that perform a particular task. For the above example we can write following functions:
• Accept the personal details from the customer
• Verify the details
• Withdraw the amount
Thus, function increases the readability of the program. Also, in case if we need to modify particular part of the program it becomes very easy to identify that part and modify it.
Example 1:
void main(){
fnCallingFunction1();
}
void fnCallingFunction1(){
printf(“You are in fnCallingFunction1”);
}
Output:
You are in fnCallingFunction1
As we all know, the execution of the program always starts from the main() function of the program.
Inside the main() function there is a function call to function fnCallingFunction1(). When the statement fnCallingFunction1() is encountered, the control is transferred to the function fnCallingFunction1 written just after the main() function. Now, all the statements written inside the fnCallingFunction1() is executed. There is a printf statement inside the body of fnCallingFunction1(). Hence the output “You are in fnCallingFunction1”.
A function cannot be defined inside the body of another function.
Example:
float fnGetAverage(int, int); //function prototype
void main(){
int x,y;
float z;
printf(“\nEnter the values for x and y”);
scanf(“%d %d”, &x, &y);
z = fnGetAverage(x,y); //function call
printf(“\nThe average is %d”, z);
}
float fnGetAverage(int a, int b){ //function definition
float c;
c = (a+b)/2; //calculating average
return c; //returning the value
}
Here, the value of x and y is taken as input from the user. This value is then passed to the function fnGetAverage as shown below:
fnGetAverage(x,y);
Now, the control is transferred to the function definition. The value of x and y are taken in the variables a and b respectively. The average of a and b is performed in the function body and the result is stored in the variable c. This value is then returned back using the statement return c. Now the control is transferred to the main() function and the value is assigned to the variable z.
The variables x and y are called ‘actual arguments/actual parameters’ and the variables a and b are called ‘formal arguments/formal parameters’. We can pass n numbers of arguments. But the type, order and the number of arguments must be same.
In the above program, the value of x and y is not known to the function "fnGetAverage".
When return statement is encountered the control is transferred back to the calling program.
It returns the value present in the parentheses or the variable.
Example:
return 8;
return (8);
• Accept account number and other personal details of the customer as a input
• Accept the details of the transactions to be performed
• If the customer wants to withdraw the money, then program should fetch the balance amount and perform eligibility check.
• After performing eligibility check, the money is deducted from that person’s account and the details of the transaction are updated in the database.
If we write the code for the above mentioned steps, it becomes very lengthy code. The solution to get rid of such lengthy code is the use of functions.
A function is a self contained block of statements that perform a particular task. For the above example we can write following functions:
• Accept the personal details from the customer
• Verify the details
• Withdraw the amount
Thus, function increases the readability of the program. Also, in case if we need to modify particular part of the program it becomes very easy to identify that part and modify it.
Example 1:
void main(){
fnCallingFunction1();
}
void fnCallingFunction1(){
printf(“You are in fnCallingFunction1”);
}
Output:
You are in fnCallingFunction1
As we all know, the execution of the program always starts from the main() function of the program.
Inside the main() function there is a function call to function fnCallingFunction1(). When the statement fnCallingFunction1() is encountered, the control is transferred to the function fnCallingFunction1 written just after the main() function. Now, all the statements written inside the fnCallingFunction1() is executed. There is a printf statement inside the body of fnCallingFunction1(). Hence the output “You are in fnCallingFunction1”.
A function cannot be defined inside the body of another function.
Example:
float fnGetAverage(int, int); //function prototype
void main(){
int x,y;
float z;
printf(“\nEnter the values for x and y”);
scanf(“%d %d”, &x, &y);
z = fnGetAverage(x,y); //function call
printf(“\nThe average is %d”, z);
}
float fnGetAverage(int a, int b){ //function definition
float c;
c = (a+b)/2; //calculating average
return c; //returning the value
}
Here, the value of x and y is taken as input from the user. This value is then passed to the function fnGetAverage as shown below:
fnGetAverage(x,y);
Now, the control is transferred to the function definition. The value of x and y are taken in the variables a and b respectively. The average of a and b is performed in the function body and the result is stored in the variable c. This value is then returned back using the statement return c. Now the control is transferred to the main() function and the value is assigned to the variable z.
The variables x and y are called ‘actual arguments/actual parameters’ and the variables a and b are called ‘formal arguments/formal parameters’. We can pass n numbers of arguments. But the type, order and the number of arguments must be same.
In the above program, the value of x and y is not known to the function "fnGetAverage".
When return statement is encountered the control is transferred back to the calling program.
It returns the value present in the parentheses or the variable.
Example:
return 8;
return (8);
The break Statement in C Language
Here, break is the keyword known to the compiler.
The break statement is used to break from any kind of loop. Let us understand the use of break statement using an example.
Example:
for(i=0;i<10;i++){
/*block of statement*/
}
Let us suppose that we want to come out of for loop when the value of I equals to 5. The solution to this is using break statement. The problem can be solved using break loop as follows:
for(i=0;i<10;i++){
/*block of statement*/
if(i==5)
break;
}
When the break statement is executed the control is transferred to the statement present immediately after the for loop.
The break statement is used to break from any kind of loop. Let us understand the use of break statement using an example.
Example:
for(i=0;i<10;i++){
/*block of statement*/
}
Let us suppose that we want to come out of for loop when the value of I equals to 5. The solution to this is using break statement. The problem can be solved using break loop as follows:
for(i=0;i<10;i++){
/*block of statement*/
if(i==5)
break;
}
When the break statement is executed the control is transferred to the statement present immediately after the for loop.
The continue Statement in C Language
Sometimes there arises a situation where we don’t want to execute the certain statements within the loop but we want to continue the execution of the loop till the condition is satisfied. This can be done using continue statement.
Consider the below example,
for(i=0;i<10;i++){
/*statement1*/
/*statement2*/
/*statement3*/
/*statement4*/
}
Let us suppose that, when the value of i equals to 5 we want to skip the execution of statement3 and statement4. Then, we can use the continue statement to perform the above task as follows.
for(i=0;i<10;i++){
/*statement1*/
/*statement2*/
if(i ==5)
continue;
/*statement3*/
/*statement4*/
}
Here, when value of i equals to 5, statement3 and statement4 are skipped and control gets transferred to the increment part of for loop and for loop is executed as normal.
Consider the below example,
for(i=0;i<10;i++){
/*statement1*/
/*statement2*/
/*statement3*/
/*statement4*/
}
Let us suppose that, when the value of i equals to 5 we want to skip the execution of statement3 and statement4. Then, we can use the continue statement to perform the above task as follows.
for(i=0;i<10;i++){
/*statement1*/
/*statement2*/
if(i ==5)
continue;
/*statement3*/
/*statement4*/
}
Here, when value of i equals to 5, statement3 and statement4 are skipped and control gets transferred to the increment part of for loop and for loop is executed as normal.
C Program To Sort Elements Of An Array In Ascending Order.
Sort array in ascending order
#include<stdio.h>
#include<conio.h>
void main(){
int arr[100],i,j,element,no,temp;
clrscr();
printf("\nEnter the no of Elements: ");
scanf("%d", &no);
for(i=0;i<no;i++){
printf("\n Enter Element %d: ", i+1);
scanf("%d",&arr[i]);
}
for(i=0;i<no;i++){
for(j=i;j<no;j++){
if(arr[i] > arr[j]){
temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
}
printf("\nSorted array:");
for(i=0;i<no;i++){
printf("\t%d",arr[i]);
}
getch();
}
Output:
Enter the no of Elements: 5
Enter Element 1: 2
Enter Element 2: 5
Enter Element 3: 2
Enter Element 4: 5
Enter Element 5: 3
Sorted array: 2 2 3 5 5
Follow Us On Facebook !!!
#include<stdio.h>
#include<conio.h>
void main(){
int arr[100],i,j,element,no,temp;
clrscr();
printf("\nEnter the no of Elements: ");
scanf("%d", &no);
for(i=0;i<no;i++){
printf("\n Enter Element %d: ", i+1);
scanf("%d",&arr[i]);
}
for(i=0;i<no;i++){
for(j=i;j<no;j++){
if(arr[i] > arr[j]){
temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
}
printf("\nSorted array:");
for(i=0;i<no;i++){
printf("\t%d",arr[i]);
}
getch();
}
Output:
Enter the no of Elements: 5
Enter Element 1: 2
Enter Element 2: 5
Enter Element 3: 2
Enter Element 4: 5
Enter Element 5: 3
Sorted array: 2 2 3 5 5
Follow Us On Facebook !!!
C Program To Find Out Smallest Number In An Array.
#include<stdio.h>
#include<conio.h>
void main ()
{
int ar[100],n,i,small;
clrscr ();
printf("\n Enter The Size Of The Array");
scanf("%d",&n);
printf("\n Enetr The Elements Of The Array:");
for(i=0;i<n;i++)
{
scanf("%d",&ar[i]);
}
small=ar[0];
for(i=0;i<n;i++)
{
if(ar[i]<=small)
{
small=ar[i];
}
}
printf("\n Smallest Number Of The Array Is %d",small);
getch ();
}
Follow Us On Facebook !!!
#include<conio.h>
void main ()
{
int ar[100],n,i,small;
clrscr ();
printf("\n Enter The Size Of The Array");
scanf("%d",&n);
printf("\n Enetr The Elements Of The Array:");
for(i=0;i<n;i++)
{
scanf("%d",&ar[i]);
}
small=ar[0];
for(i=0;i<n;i++)
{
if(ar[i]<=small)
{
small=ar[i];
}
}
printf("\n Smallest Number Of The Array Is %d",small);
getch ();
}
Follow Us On Facebook !!!
for statement in C Programming
In while and do while statement we need to write logic to repeatedly execute a block of statement by initializing a counter and incrementing it after a particular steps. This sometime looks tedious and decreases the readability of the program. The readability of the program can be improved by using for statement. Using for statement we can merge all the three parts i.e. assignment, condition checking and increment/decrementing.
Syntax:
for(initialization; test condition; increment/decrement){
/*block of statement*/
}
Initialization: setting up a loop counter to initial value
test condition: Testing the loop counter to determine whether the loop needs to be executed or not.
increment/decrement: Increment or decrement the loop counter value
Explanation:
The for loop is executed as follows:
1) The initial counter value is initialized. This initialization is done only once for the entire for loop.
2) After the initialization, test condition is checked. Test condition can be any relational or logical expression. If the test condition is satisfied i.e. the condition evaluates to true then the block of statement inside the for loop is executed.
3) After the execution of the block of statement, increment/decrement of the counter is done. After performing this, the test condition is again evaluated. The step 2 and 3 are repeated till the test condition returns false.
The above example for while loop can re-written as follows:
#include<stdio.h>
#include<conio.h>
void main(){
int i;
clrscr();
for(i=1; i<=5;i++){ printf("%d This will be repeated 5 times\n", i); } printf("End of the program"); getch(); } Output:
1 This will be repeated 5 times
2 This will be repeated 5 times
3 This will be repeated 5 times
4 This will be repeated 5 times
5 This will be repeated 5 times
End of the program
In the above program, value 1 is assigned to i. The for loop would be executed till the value of i is less than or equal to 5.
Note: It is necessary to write the semicolon in for loop as shown in the below:
for(i=0; i<10; i++)
Consider,
for(i=0; i<10;){
printf(“Interment/decrement not used above”)
i=i+1;
}
In the above program, Increment is done within the body of for loop. Still semicolon is necessary after the test condition.
Consider,
i=0;
for(; i<10;i++){
printf(“Interment/decrement not used above”)
}
In the above program, Initialization is done before the start of for loop. Still semicolon is necessary before the test condition.
Note:
We can initialize multiple variables in initialization section but only one test condition is allowed.
Syntax:
for(initialization; test condition; increment/decrement){
/*block of statement*/
}
Initialization: setting up a loop counter to initial value
test condition: Testing the loop counter to determine whether the loop needs to be executed or not.
increment/decrement: Increment or decrement the loop counter value
Explanation:
The for loop is executed as follows:
1) The initial counter value is initialized. This initialization is done only once for the entire for loop.
2) After the initialization, test condition is checked. Test condition can be any relational or logical expression. If the test condition is satisfied i.e. the condition evaluates to true then the block of statement inside the for loop is executed.
3) After the execution of the block of statement, increment/decrement of the counter is done. After performing this, the test condition is again evaluated. The step 2 and 3 are repeated till the test condition returns false.
The above example for while loop can re-written as follows:
#include<stdio.h>
#include<conio.h>
void main(){
int i;
clrscr();
for(i=1; i<=5;i++){ printf("%d This will be repeated 5 times\n", i); } printf("End of the program"); getch(); } Output:
1 This will be repeated 5 times
2 This will be repeated 5 times
3 This will be repeated 5 times
4 This will be repeated 5 times
5 This will be repeated 5 times
End of the program
In the above program, value 1 is assigned to i. The for loop would be executed till the value of i is less than or equal to 5.
Note: It is necessary to write the semicolon in for loop as shown in the below:
for(i=0; i<10; i++)
Consider,
for(i=0; i<10;){
printf(“Interment/decrement not used above”)
i=i+1;
}
In the above program, Increment is done within the body of for loop. Still semicolon is necessary after the test condition.
Consider,
i=0;
for(; i<10;i++){
printf(“Interment/decrement not used above”)
}
In the above program, Initialization is done before the start of for loop. Still semicolon is necessary before the test condition.
Note:
We can initialize multiple variables in initialization section but only one test condition is allowed.
do-while Statement in C
Syntax:
do{
/*block of statement*/
}while(condition);
Explanation:
Here, while and do are the keywords which is know to the compiler.
Condition can be any expression
This is very similar to while loop.
Here, the block of statement enclosed in the opening and closing braces after the keyword do is executed at least once. After the execution of the block of statement for the first time, the condition in the while is executed.
If the condition is satisfied then the block of statement inside the do block is executed. After the execution of block of statement, again condition is check. If the conditional expression returns true, the block of statement is executed again. This process is followed till the conditional expression returns false value.
Note:
It is necessary to write semicolon (;) after the while(condition) as shown in the syntax else you will get an error.
The above example for while loop can re-written as follows:
#include<stdio.h>
#include<conio.h>
void main(){
int i=0;
clrscr();
do{
i=i+1;
printf("%d This will be repeated 5 times\n", i);
}while(i!=5);
printf("End of the program");
getch();
}
Output:
1 This will be repeated 5 times
2 This will be repeated 5 times
3 This will be repeated 5 times
4 This will be repeated 5 times
5 This will be repeated 5 times
End of the program
do{
/*block of statement*/
}while(condition);
Explanation:
Here, while and do are the keywords which is know to the compiler.
Condition can be any expression
This is very similar to while loop.
Here, the block of statement enclosed in the opening and closing braces after the keyword do is executed at least once. After the execution of the block of statement for the first time, the condition in the while is executed.
If the condition is satisfied then the block of statement inside the do block is executed. After the execution of block of statement, again condition is check. If the conditional expression returns true, the block of statement is executed again. This process is followed till the conditional expression returns false value.
Note:
It is necessary to write semicolon (;) after the while(condition) as shown in the syntax else you will get an error.
The above example for while loop can re-written as follows:
#include<stdio.h>
#include<conio.h>
void main(){
int i=0;
clrscr();
do{
i=i+1;
printf("%d This will be repeated 5 times\n", i);
}while(i!=5);
printf("End of the program");
getch();
}
Output:
1 This will be repeated 5 times
2 This will be repeated 5 times
3 This will be repeated 5 times
4 This will be repeated 5 times
5 This will be repeated 5 times
End of the program
while Statement in C Language
Let us suppose you want to execute a block of statement 5 times. There is one approach using goto statement as shown below.
#include<stdio.h>
#include<conio.h>
void main(){
int i=0;
clrscr();
label1:
i=i+1;
printf("%d This will be repeated 5 times\n", i);
if(i!=5)
goto label1;
printf("End of the program");
getch();
}
Output:
1 This will be repeated 5 times
2 This will be repeated 5 times
3 This will be repeated 5 times
4 This will be repeated 5 times
5 This will be repeated 5 times
End of the program
The above mentioned approach solves our purpose. But it is very tedious job to take care of labels. It also decreases the readability of the program. Hence there is another approach to perform the above task very effectively. We will use while loop.
Syntax:
while(condition){
/*block of statement*/
}
Explanation:
Here, while is the keyword which is know to the compiler.
Condition can be any expression
Here, when while is encountered, condition is checked first by the compiler. If the condition is satisfied then the block of statement inside the while loop is executed. After the execution of block of statement, again condition is check. If the conditional expression returns true, the block of statement is executed again. This process is followed till the conditional expression returns false value.
Let us write the above program using while loop.
#include<stdio.h>
#include<conio.h>
void main(){
int i=0;
clrscr();
while(i!=5){
i=i+1;
printf("%d This will be repeated 5 times\n", i);
}
printf("End of the program");
getch();
}
Output:
1 This will be repeated 5 times
2 This will be repeated 5 times
3 This will be repeated 5 times
4 This will be repeated 5 times
5 This will be repeated 5 times
End of the program
As you can see, the out of the above program is same as the one with goto statement in it.
We can also see that the readability of the program increases. Using while loop is much easier than using goto statement as we don’t have worry about positioning of labels.
Thus, while loop would keep on getting executed till the condition being test remains true. When the condition becomes false then the control goes to the first statement immediately after the boy of while loop.
The condition being tested can be relational or logical operators.
#include<stdio.h>
#include<conio.h>
void main(){
int i=0;
clrscr();
label1:
i=i+1;
printf("%d This will be repeated 5 times\n", i);
if(i!=5)
goto label1;
printf("End of the program");
getch();
}
Output:
1 This will be repeated 5 times
2 This will be repeated 5 times
3 This will be repeated 5 times
4 This will be repeated 5 times
5 This will be repeated 5 times
End of the program
The above mentioned approach solves our purpose. But it is very tedious job to take care of labels. It also decreases the readability of the program. Hence there is another approach to perform the above task very effectively. We will use while loop.
Syntax:
while(condition){
/*block of statement*/
}
Explanation:
Here, while is the keyword which is know to the compiler.
Condition can be any expression
Here, when while is encountered, condition is checked first by the compiler. If the condition is satisfied then the block of statement inside the while loop is executed. After the execution of block of statement, again condition is check. If the conditional expression returns true, the block of statement is executed again. This process is followed till the conditional expression returns false value.
Let us write the above program using while loop.
#include<stdio.h>
#include<conio.h>
void main(){
int i=0;
clrscr();
while(i!=5){
i=i+1;
printf("%d This will be repeated 5 times\n", i);
}
printf("End of the program");
getch();
}
Output:
1 This will be repeated 5 times
2 This will be repeated 5 times
3 This will be repeated 5 times
4 This will be repeated 5 times
5 This will be repeated 5 times
End of the program
As you can see, the out of the above program is same as the one with goto statement in it.
We can also see that the readability of the program increases. Using while loop is much easier than using goto statement as we don’t have worry about positioning of labels.
Thus, while loop would keep on getting executed till the condition being test remains true. When the condition becomes false then the control goes to the first statement immediately after the boy of while loop.
The condition being tested can be relational or logical operators.
Loops in C Programming Language
Loops are used to change the sequence or flow of the program. The basic behavior of the program is that it starts it from the beginning of the program, executes the particular statement only once and proceeds to the next statement. This behavior is continued till the end of the program is reached. But sometimes we need to execute a particular statement more than once. At this point Loops plays an important role.
Following are the types of Loops we can use in the program:
1) while statement
2) do-while statement
3) for statement
Following are the types of Loops we can use in the program:
1) while statement
2) do-while statement
3) for statement
The goto Keyword in C Language
The goto statement is used for unconditional jump from one part of the program to another part of the program. It is always suggested not to use goto statement as this reduces the readability of the program. Using goto statement is considered as poor programming approach.
The goto statement consists of two parts: label and goto keyword.
Example:
/*use of goto statement*/
#include<stdio.h>
#include<conio.h>
void main(){
int a;
goto label;
a = 10;
printf(“%d”, a);
label:
a = 20;
printf(“%d”, a);
}
Output:
20
The goto statement consists of two parts: label and goto keyword.
Example:
/*use of goto statement*/
#include<stdio.h>
#include<conio.h>
void main(){
int a;
goto label;
a = 10;
printf(“%d”, a);
label:
a = 20;
printf(“%d”, a);
}
Output:
20
The switch Statement in C Language
The switch statement is very powerful decision making statement. It reduces the complexity of the program. Hence increases the readability of the program. Switch statement accepts single input from the user and based on that input executes a particular block of statements.
Syntax of switch statement:
switch(expression){
case constant 1:
perform this;
case constant 2:
perform this;
case constant 3:
perform this;
case constant 4:
perform this;
.
.
.
default:
perform this;
}
Control passes to the statement whose case constant-expression matches the value of switch ( expression ). The switch statement can include any number of case instances, but no two case constants within the same switch statement can have the same value. Execution of the statement body begins at the selected statement and proceeds until the end of the body or until a break statement transfers control out of the body. Please make a note that using default case is optional.
Example 1:
int a = 2;
switch(a){
case 1:
printf(“1”);
case 2:
printf(“2”);
}
Output:
2
Example 2:
int a = 2;
switch(a){
case 1:
printf(“1\n”);
break;
case 2:
printf(“2\n”);
break;
default:
printf(“No match”)
}
Output:
2
Example 3:
char a = ‘A’;
switch(a){
case ‘B’:
printf(“B\n”);
break;
case ‘A’:
printf(“A\n”);
break;
default:
printf(“No match”)
}
Output:
A
Syntax of switch statement:
switch(expression){
case constant 1:
perform this;
case constant 2:
perform this;
case constant 3:
perform this;
case constant 4:
perform this;
.
.
.
default:
perform this;
}
Control passes to the statement whose case constant-expression matches the value of switch ( expression ). The switch statement can include any number of case instances, but no two case constants within the same switch statement can have the same value. Execution of the statement body begins at the selected statement and proceeds until the end of the body or until a break statement transfers control out of the body. Please make a note that using default case is optional.
Example 1:
int a = 2;
switch(a){
case 1:
printf(“1”);
case 2:
printf(“2”);
}
Output:
2
Example 2:
int a = 2;
switch(a){
case 1:
printf(“1\n”);
break;
case 2:
printf(“2\n”);
break;
default:
printf(“No match”)
}
Output:
2
Example 3:
char a = ‘A’;
switch(a){
case ‘B’:
printf(“B\n”);
break;
case ‘A’:
printf(“A\n”);
break;
default:
printf(“No match”)
}
Output:
A
The Conditional Operator in C Language
The conditional operator is also known as ternary operator. It is called ternary operator because it takes three arguments. The conditional operator evaluates an expression returning a value if that expression is true and different one if the expression is evaluated as false.
Syntax:
condition ? result1 : result2
If the condition is true, result1 is returned else result2 is returned.
Examples:
10==5 ? 11: 12 // returns 12, since 10 not equal to 5.
10!=5 ? 4 : 3 // returns 4, since 10 not equal to 5.
12>8 ? a : b // returns the value of a, since 12 is greater than 8.
/*Conditional operator*/
#include
#include
void main(){
int a = 10, b = 11;
int c;
c = (a < b)? a : b
printf(“%d”, c);
}
Output:
10
Syntax:
condition ? result1 : result2
If the condition is true, result1 is returned else result2 is returned.
Examples:
10==5 ? 11: 12 // returns 12, since 10 not equal to 5.
10!=5 ? 4 : 3 // returns 4, since 10 not equal to 5.
12>8 ? a : b // returns the value of a, since 12 is greater than 8.
/*Conditional operator*/
#include
#include
void main(){
int a = 10, b = 11;
int c;
c = (a < b)? a : b
printf(“%d”, c);
}
Output:
10
The if-else Statement in C Programming Language
Here, if and else are the keywords in C.
Syntax:
if (condition is true){
/*1st block of statements*/
}
else{
/*2nd block of statements*/
}
The keyword if tells the compiler that what follows is decision control statement. The block of statements to be executed must be enclosed in opening and closing braces. If only one statement needs to be executed then braces need not be used. Let us understand if-else statement using an example.
Example:
int a = 10;
if (a == 10){
printf(“You are in 1st block\n”);
printf(“The value of a is %d\n”, a);
}
else{
printf(“You are in 2nd block\n”);
printf(“The value of a is not equal to %d\n”, a);
}
In the above example we have assigned value 10 to a. In the next line, there is an if statement. It is read as “If a is equal to 10 then perform the block of statements enclosed within the braces of if part else perform the block of statements enclosed within the braces of else part”. After the execution of if-else statement normal sequence flow of the program is followed.
The output of the above example is:
You are in if block
You are in 1st block
The value of a is 10
The else-if statement
The else-if statement is nothing but the rearrangement of else with the if that follows.
Consider the below program.
if(condition)
perform this
else{
if(condition)
perform this;
}
The above program can be re-written as,
if(condition)
perform this
else if(condition)
perform this;
Here, the else-if statement is used. Else if reduces the complexity of the program making it easier to understand.
Syntax:
if (condition is true){
/*1st block of statements*/
}
else{
/*2nd block of statements*/
}
The keyword if tells the compiler that what follows is decision control statement. The block of statements to be executed must be enclosed in opening and closing braces. If only one statement needs to be executed then braces need not be used. Let us understand if-else statement using an example.
Example:
int a = 10;
if (a == 10){
printf(“You are in 1st block\n”);
printf(“The value of a is %d\n”, a);
}
else{
printf(“You are in 2nd block\n”);
printf(“The value of a is not equal to %d\n”, a);
}
In the above example we have assigned value 10 to a. In the next line, there is an if statement. It is read as “If a is equal to 10 then perform the block of statements enclosed within the braces of if part else perform the block of statements enclosed within the braces of else part”. After the execution of if-else statement normal sequence flow of the program is followed.
The output of the above example is:
You are in if block
You are in 1st block
The value of a is 10
The else-if statement
The else-if statement is nothing but the rearrangement of else with the if that follows.
Consider the below program.
if(condition)
perform this
else{
if(condition)
perform this;
}
The above program can be re-written as,
if(condition)
perform this
else if(condition)
perform this;
Here, the else-if statement is used. Else if reduces the complexity of the program making it easier to understand.
The if statement in C Programming Language
Here, if is the keyword in C.
Syntax:
if (condition is true){
/*block of statements to be executed*/
}
The keyword if tells the compiler that what follows is decision control statement. The block of statements to be executed must be enclosed in opening and closing braces. If only one statement needs to be executed then braces need not be used. Let us understand if statement using an example.
Example:
int a = 10;
if (a == 10){
printf(“You are in if block\n”);
printf(“The value of a is %d\n”, a);
}
printf(“You are out of if block”);
In the above example we have assigned value 10 to a. In the next line, there is an if statement. It is read as “If a is equal to 10 then perform the block of statements enclosed within the braces”. After the execution of this block normal sequence flow of the program is executed.
The output of the above example is:
You are in if block
The value of a is 10
You are out of if block
Lets have a look at different expressions that can be used in if statement.
a == b read as a is equal to b
a!=b read as a is not equal to b
a < b read as a is less than b a > b read as a is greater than b
a<=b read as a is less than or equal to b a>=b read as a is greater than or equal to b
Example:
/*Demonstration of if statement*/
int marks;
printf(“Enter the marks:”);
scanf(“%d”, &marks);
if(marks>=35){
printf(“Congrats!!!”);
}
In the above program, it will prompt you to enter the marks. If you enter marks greater than or equal to 35, it will display Congrats!!! on the screen else it will do nothing.
Syntax:
if (condition is true){
/*block of statements to be executed*/
}
The keyword if tells the compiler that what follows is decision control statement. The block of statements to be executed must be enclosed in opening and closing braces. If only one statement needs to be executed then braces need not be used. Let us understand if statement using an example.
Example:
int a = 10;
if (a == 10){
printf(“You are in if block\n”);
printf(“The value of a is %d\n”, a);
}
printf(“You are out of if block”);
In the above example we have assigned value 10 to a. In the next line, there is an if statement. It is read as “If a is equal to 10 then perform the block of statements enclosed within the braces”. After the execution of this block normal sequence flow of the program is executed.
The output of the above example is:
You are in if block
The value of a is 10
You are out of if block
Lets have a look at different expressions that can be used in if statement.
a == b read as a is equal to b
a!=b read as a is not equal to b
a < b read as a is less than b a > b read as a is greater than b
a<=b read as a is less than or equal to b a>=b read as a is greater than or equal to b
Example:
/*Demonstration of if statement*/
int marks;
printf(“Enter the marks:”);
scanf(“%d”, &marks);
if(marks>=35){
printf(“Congrats!!!”);
}
In the above program, it will prompt you to enter the marks. If you enter marks greater than or equal to 35, it will display Congrats!!! on the screen else it will do nothing.
C Program Using While Loop To Reverse The Digits Of The Number.
#include<stdio.h>
#include<conio.h>
void main ()
{
int num,r,reverse=0;
clrscr ();
printf("\n Enter Any Number:");
scanf("%d",&num);
while(num)
{
r=num%10;
reverse=reverse*10+r;
num=num/10;
}
printf("\n Reversed of Number: %d", reverse);
getch ();
}
Follow Us On Facebook !!!
#include<conio.h>
void main ()
{
int num,r,reverse=0;
clrscr ();
printf("\n Enter Any Number:");
scanf("%d",&num);
while(num)
{
r=num%10;
reverse=reverse*10+r;
num=num/10;
}
printf("\n Reversed of Number: %d", reverse);
getch ();
}
Follow Us On Facebook !!!
C Program To Find The Cubes Of 1 to 10 Numbers Using Any Loop.
#include<stdio.h>
#include<conio.h>
void main ()
{
int i, j=1;
clrscr ();
printf("\n Enter the Number from 1 to 10:-");
printf("\nNumber \tcube");
for(i=1;i<=10; i++)
{
printf("\n%d\t",i);
j=i*i*i;
printf("%d\n\t", j);
}
getch();
}
Follow Us On Facebook !!!
#include<conio.h>
void main ()
{
int i, j=1;
clrscr ();
printf("\n Enter the Number from 1 to 10:-");
printf("\nNumber \tcube");
for(i=1;i<=10; i++)
{
printf("\n%d\t",i);
j=i*i*i;
printf("%d\n\t", j);
}
getch();
}
Follow Us On Facebook !!!
Friday, February 22, 2013
Instructions in C Programming Language
There are three types of instructions in C. They are as follows:
1) Type Declaration Instruction
2) Arithmetic Instruction
3) Control instruction
Type Declaration instruction is used to declare the type of variables used in C. Any variable we want to use in the program must be declared before using it. This declaration is done using Type declaration instruction. This declaration is done at the beginning of the main() function.
E.g.:
int pr, rt;
float amt;
Arithmetic instructions are used to perform arithmetic operations on variables and constants. Here we will learn some new terms. These are operands and operators. The variables and constants on which arithmetic operation is done by arithmetic operators are called operands.
Example 1:
int a = 5, b = 10, c;
c = a + b;
Here,
a, b and c are called operands
=, + are called as operators
Example 2:
int a;
float b, c, d;
a = 10;
b = 0.05;
c = 1.5;
d = a +b * c;
Here,
a is integer variable.
b, c and d are real variables.
= is the assignment operator.
+ and * are arithmetic operators.
10 is integer constant.
0.05 and 1.5 are real constants.
Control instruction is used to control the sequence (flow) of the program.
We write a program to perform a particular task. The program might be addition of two numbers, subtraction of two number or division of two numbers. Let us suppose that we need to write a program to perform all the above three operations i.e. addition, subtraction and multiplication. Writing three different programs is not feasible. If we do so, then for addition, subtraction and division we need to run the program separately. Instead of doing this, we can include decision control statement. Using this we can decide within the program whether to perform addition, subtraction or division. Thus program becomes efficient and user friendly too.
Using decision control statement, we can perform different actions based on the circumstances.
Decision control instructions:
1) The if statement
2) The if-else statement
3) The conditional operators
4) The switch statement
1) Type Declaration Instruction
2) Arithmetic Instruction
3) Control instruction
Type Declaration instruction is used to declare the type of variables used in C. Any variable we want to use in the program must be declared before using it. This declaration is done using Type declaration instruction. This declaration is done at the beginning of the main() function.
E.g.:
int pr, rt;
float amt;
Arithmetic instructions are used to perform arithmetic operations on variables and constants. Here we will learn some new terms. These are operands and operators. The variables and constants on which arithmetic operation is done by arithmetic operators are called operands.
Example 1:
int a = 5, b = 10, c;
c = a + b;
Here,
a, b and c are called operands
=, + are called as operators
Example 2:
int a;
float b, c, d;
a = 10;
b = 0.05;
c = 1.5;
d = a +b * c;
Here,
a is integer variable.
b, c and d are real variables.
= is the assignment operator.
+ and * are arithmetic operators.
10 is integer constant.
0.05 and 1.5 are real constants.
Control instruction is used to control the sequence (flow) of the program.
We write a program to perform a particular task. The program might be addition of two numbers, subtraction of two number or division of two numbers. Let us suppose that we need to write a program to perform all the above three operations i.e. addition, subtraction and multiplication. Writing three different programs is not feasible. If we do so, then for addition, subtraction and division we need to run the program separately. Instead of doing this, we can include decision control statement. Using this we can decide within the program whether to perform addition, subtraction or division. Thus program becomes efficient and user friendly too.
Using decision control statement, we can perform different actions based on the circumstances.
Decision control instructions:
1) The if statement
2) The if-else statement
3) The conditional operators
4) The switch statement
Understanding the program in C
1) /*
2) Program:
3) Addition of two numbers
4) */
5) //Here it starts
6) #include<stdio.h>
7) #include<conio.h>
8) Void main()
9) {
10) int a, b, c;
11) /*Assign the values to the variable a and b */
12) a = 5;
13) b = 4;
14) /*Perform addition of a and b */
15) c = a + b;
16) printf(“\nAddition of a and b is %d”, c);
17) }
Let us learn the above program in detail.
Line 1 thru 4:
This is the comments in the program. It is called multiline comment. The text written within /*...*/ are ignored by the compiler.
Line 5:
This is another way to comment a text or statement. It is called single line comment. The entire line following the tag // is ignored by the compiler.
Line 6 and 7: #include is known as pre- processor directives. It tell the compiler to include text from another file, stuffing it right into your source code.
is a file name enclosed within angle brackets. The whole statement #include tells the compiler to take text from the file stdio.h and stick it into your source code before the source
code is compiled.
Line 8:
This is the start of the main function. The program execution starts from this function. main() is the name given to a set of statements. This name has to be main(). The statement that belongs to main() are enclosed within a pair of braces {}.
Line 10: Any variable that we need to use must be declared before using it.
Line 12 thru 15:
Here the values are getting assigned to the variables.
Line 16:
Once the value of a+b is assigned to c, it needs to be displayed on the screen. We can use readymade library function to display the value on the screen. One such function is printf().
The general form of the printf() function is:
printf(“”,);
can contain,
%d for printing integer values
%f for printing real values
%c for printing character values
\n is a newline character. It takes the cursor to the new line. It is one of the several escape sequences available in C.
Line 9 and 17:
The function body should be enclosed in opening and closing braces.
Note:
Though comments are not necessary, it is a good programming practice to include comments in the program. Adding comments in the program increases the readability of the program.
WE can include as many comments as possible.
A comment can be split over more than one line as shown in the above program (Line 1 thru 4).
Any C statement always ends with a ;
Receiving Input
In the above program, we have assigned the value 5 and 4 to a and b respectively. But, every time we cant do so. A situation might arise wherein we need to take input from the user. Here we will learn how to receive input from the user.
scanf() – It is a standard library function in C. This function will accept the input from the user and stores it in a particular user defined variable.
The syntax of this function is:
scanf( “”, &);
can contain,
%d for printing integer values
%f for printing real values
%c for printing character values
‘&’ before the variable name is a must. ‘&’ is the ‘address of’ operator. It gives the address used by the variable in memory.
Let us consider an example
scanf(“%d”,&a);
When we execute this statement, it will ask for input. Suppose the input given is 5. 5 will be stored as integer at the address of variable a. we can print the value stored at that address using simple printf() statement as shown below.
printf(“%d”, a);
Example:
1) /*
2) Program to accept three numbers and prints the sum of these numbers
3) */
4) #include<stdio.h>
5) #include<conio.h>
6) Void main()
7) {
8) int a, b, c;
9) /*Assign the values to the variable a and b */
10) scanf(“%d %d”, &a, &b);
11) /*Perform addition of a and b */
12) c = a + b;
13) printf(“\nAddition of a and b is %d”, c);
14) }
2) Program:
3) Addition of two numbers
4) */
5) //Here it starts
6) #include<stdio.h>
7) #include<conio.h>
8) Void main()
9) {
10) int a, b, c;
11) /*Assign the values to the variable a and b */
12) a = 5;
13) b = 4;
14) /*Perform addition of a and b */
15) c = a + b;
16) printf(“\nAddition of a and b is %d”, c);
17) }
Let us learn the above program in detail.
Line 1 thru 4:
This is the comments in the program. It is called multiline comment. The text written within /*...*/ are ignored by the compiler.
Line 5:
This is another way to comment a text or statement. It is called single line comment. The entire line following the tag // is ignored by the compiler.
Line 6 and 7: #include is known as pre- processor directives. It tell the compiler to include text from another file, stuffing it right into your source code.
is a file name enclosed within angle brackets. The whole statement #include tells the compiler to take text from the file stdio.h and stick it into your source code before the source
code is compiled.
Line 8:
This is the start of the main function. The program execution starts from this function. main() is the name given to a set of statements. This name has to be main(). The statement that belongs to main() are enclosed within a pair of braces {}.
Line 10: Any variable that we need to use must be declared before using it.
Line 12 thru 15:
Here the values are getting assigned to the variables.
Line 16:
Once the value of a+b is assigned to c, it needs to be displayed on the screen. We can use readymade library function to display the value on the screen. One such function is printf().
The general form of the printf() function is:
printf(“”,);
can contain,
%d for printing integer values
%f for printing real values
%c for printing character values
\n is a newline character. It takes the cursor to the new line. It is one of the several escape sequences available in C.
Line 9 and 17:
The function body should be enclosed in opening and closing braces.
Note:
Though comments are not necessary, it is a good programming practice to include comments in the program. Adding comments in the program increases the readability of the program.
WE can include as many comments as possible.
A comment can be split over more than one line as shown in the above program (Line 1 thru 4).
Any C statement always ends with a ;
Receiving Input
In the above program, we have assigned the value 5 and 4 to a and b respectively. But, every time we cant do so. A situation might arise wherein we need to take input from the user. Here we will learn how to receive input from the user.
scanf() – It is a standard library function in C. This function will accept the input from the user and stores it in a particular user defined variable.
The syntax of this function is:
scanf( “”, &);
can contain,
%d for printing integer values
%f for printing real values
%c for printing character values
‘&’ before the variable name is a must. ‘&’ is the ‘address of’ operator. It gives the address used by the variable in memory.
Let us consider an example
scanf(“%d”,&a);
When we execute this statement, it will ask for input. Suppose the input given is 5. 5 will be stored as integer at the address of variable a. we can print the value stored at that address using simple printf() statement as shown below.
printf(“%d”, a);
Example:
1) /*
2) Program to accept three numbers and prints the sum of these numbers
3) */
4) #include<stdio.h>
5) #include<conio.h>
6) Void main()
7) {
8) int a, b, c;
9) /*Assign the values to the variable a and b */
10) scanf(“%d %d”, &a, &b);
11) /*Perform addition of a and b */
12) c = a + b;
13) printf(“\nAddition of a and b is %d”, c);
14) }
Data Types in C
Data types determine the following:
• Range of the data
• Type of the data stored
• Number of bytes it occupies in memory
C supports following data types:
• int – occupies 2 (16-bit compiler) or 4 bytes (32-bit compiler) of memory
• float - occupies 4 byes of memory
• double – occupies 8 bytes of memory
• char – occupies 1 byte of memory
int is used to define integer numbers. It occupies 2 bytes of memory (16-bit compiler)
{
int amount;
amount = 5;
}
float is used to define floating type numbers. It occupies 4 bytes of memory (16-bit compiler)
{
float amount;
amount = 1.200000;
}
double is used to store big floating point numbers. It reserves 8 bytes of memory (16-bit compiler)
{
double amount;
amount = 1.200000000000;
}
char is used to store characters. It occupies 1 byte of memory (16-bit compiler)
{
char alp;
alp = ‘A’;
}
The modifiers define the amount of storage allocated to the variable.
int, float and double have the following four modifiers.
· short
· long
· signed
· unsigned
long is used to store long int
short is used to store short int
long double is used to store long double
Using signed int is redundant as int is signed by default.
Modifier long can be applied to double data type.
Following are the valid combinations:
long int or long (For 16 bit compiler: 4 byte)
short int or short (For 16 bit compiler: 2 byte)
signed int or int (For 16 bit compiler: 2 byte)
unsigned int (For 16 bit compiler: 2 byte)
short unsigned int
long unsigned int
char (Occupies 1 byte of memory)
signed char or char (Range: -128 to +127, Occupies 1 byte of memory)
unsigned char (Range: 0 to 255, Occupies 1 byte of memory)
long double (Occupies 10 bytes of memory)
Following rule applies:
short int <= int <= long int
float <= double <=long double
Summary:
Following table is applicable for 16-bit compiler.
Data Type Bytes
short int 2
short unsigned int 2
short signed int 2
signed int 2
unsigned int 2
long int 4
long unsigned int 4
long signed int 4
float 4
double 8
long double 10
char 1
signed char 1
unsigned char 1
• Range of the data
• Type of the data stored
• Number of bytes it occupies in memory
C supports following data types:
• int – occupies 2 (16-bit compiler) or 4 bytes (32-bit compiler) of memory
• float - occupies 4 byes of memory
• double – occupies 8 bytes of memory
• char – occupies 1 byte of memory
int is used to define integer numbers. It occupies 2 bytes of memory (16-bit compiler)
{
int amount;
amount = 5;
}
float is used to define floating type numbers. It occupies 4 bytes of memory (16-bit compiler)
{
float amount;
amount = 1.200000;
}
double is used to store big floating point numbers. It reserves 8 bytes of memory (16-bit compiler)
{
double amount;
amount = 1.200000000000;
}
char is used to store characters. It occupies 1 byte of memory (16-bit compiler)
{
char alp;
alp = ‘A’;
}
The modifiers define the amount of storage allocated to the variable.
int, float and double have the following four modifiers.
· short
· long
· signed
· unsigned
long is used to store long int
short is used to store short int
long double is used to store long double
Using signed int is redundant as int is signed by default.
Modifier long can be applied to double data type.
Following are the valid combinations:
long int or long (For 16 bit compiler: 4 byte)
short int or short (For 16 bit compiler: 2 byte)
signed int or int (For 16 bit compiler: 2 byte)
unsigned int (For 16 bit compiler: 2 byte)
short unsigned int
long unsigned int
char (Occupies 1 byte of memory)
signed char or char (Range: -128 to +127, Occupies 1 byte of memory)
unsigned char (Range: 0 to 255, Occupies 1 byte of memory)
long double (Occupies 10 bytes of memory)
Following rule applies:
short int <= int <= long int
float <= double <=long double
Summary:
Following table is applicable for 16-bit compiler.
Data Type Bytes
short int 2
short unsigned int 2
short signed int 2
signed int 2
unsigned int 2
long int 4
long unsigned int 4
long signed int 4
float 4
double 8
long double 10
char 1
signed char 1
unsigned char 1
Rules for Constructing Variable Names in C Language
A variable is an entity whose value keeps on changing throughout the program execution. As we all know, data is stored in the memory of the computer. Actually, data is not stored in the variable. A variable is the name given to the memory location. A variable name is an entity that points to a particular memory location.
Variable can be of different types.
Rules for constructing variable names
1) A Variable name consists of any combination of alphabets, digits and underscores. Some compiler allows variable names whole length could be up to 247 characters. Still it would be safer to stick to the rule of 31 characters. Please avoid creating long variable name as it adds to your typing effort.
2) The first character of the variable name must either be alphabet or underscore. It should not start with the digit.
3) No commas and blanks are allowed in the variable name.
4) No special symbols other than underscore are allowed in the variable name.
We need to declare the type of the variable name before making use of that name in the program. Type declaration can be done as follows:
To declare a variable as integer, follow the below syntax:
int variable_name;
Here int is the type of the variable named variable_name. ‘int’ denotes integer type.
Following are the examples of type declaration statements:
E.g.: int p, n;
float r;
Labels: Rules for constructing variable names
Variable can be of different types.
Rules for constructing variable names
1) A Variable name consists of any combination of alphabets, digits and underscores. Some compiler allows variable names whole length could be up to 247 characters. Still it would be safer to stick to the rule of 31 characters. Please avoid creating long variable name as it adds to your typing effort.
2) The first character of the variable name must either be alphabet or underscore. It should not start with the digit.
3) No commas and blanks are allowed in the variable name.
4) No special symbols other than underscore are allowed in the variable name.
We need to declare the type of the variable name before making use of that name in the program. Type declaration can be done as follows:
To declare a variable as integer, follow the below syntax:
int variable_name;
Here int is the type of the variable named variable_name. ‘int’ denotes integer type.
Following are the examples of type declaration statements:
E.g.: int p, n;
float r;
Labels: Rules for constructing variable names
Rules for constructing Constants in C Language
There are rules to be followed in order to create a constant. Let us discuss the rules to create constants.
Rules for constructing Integer constant
1) An integer constant must have at least one digit.
2) It must not have a decimal point.
3) It can either be positive or negative.
4) No commas or blanks are allowed within an integer constant.
5) If no sign precedes an integer constant, it is assumed to be positive.
6) The allowable range for integer constants is -32768 to 32767
Actually, the range of the integer constant depends on the compiler. The above mentioned range is for 16-bit compiler. However, for a 32-bit compiler the range would be even greater.
The integer constants
• Whole Numbers
• E.g. 25, 35, -25, -46
• Computer allocates only 2 bytes in memory.
• 16th bit is sign bit. (if 0 then positive value, if 1 then negative value)
Decimal Integer constant:
• 0 to 9
• E.g.: 49, 58, -62 … (40000 cannot come because it is > 32767)
Octal Integer constant:
• 0 to 7
• Add “0” before the value.
• E.g.: 045, 056, 067
Hexadecimal Integer constant:
• 0 to 9 and A to F
• Add 0x before the value
• E.g.: 0x42, 0x56, 0x67
Rules for constructing Real constants
Rules for constructing Real constants (Fractional Form)
1) A real constant must have at least one digit
2) It must have a decimal point
3) It could be either positive or negative
4) If no sign precedes an integer constant, it is assumed to be positive.
5) No commas or blanks are allowed within a real constant.
E.g.: +867.9, -26.9876, 654.0
Rules for constructing Real constants (Exponential Form)
1) The mantissa part and the exponential part should be separated by the letter ‘e’
2) The mantissa may have a positive or negative sign(default sign is positive)
3) The exponent must have at least one digit
4) The exponent must be a positive or negative integer(default sign is positive)
5) The range of real constants in exponential form is -3.4e38 and -3.4e38
E.g.: +3.2e-4, 4.1e8, -0.2e+4, -3.2e-4
Rules for constructing Character constant
1) A character constant is an alphabet, a single digit or a single special symbol enclosed within inverted commas. Both the inverted commas should point to the left. For example, ’S’ is a valid character constant whereas ‘S’ is not.
2) The maximum length of a character constant can be 1 character. Allots 1 byte of memory
E.g.: ’B’, ’l’, ’#’
Rules for constructing Integer constant
1) An integer constant must have at least one digit.
2) It must not have a decimal point.
3) It can either be positive or negative.
4) No commas or blanks are allowed within an integer constant.
5) If no sign precedes an integer constant, it is assumed to be positive.
6) The allowable range for integer constants is -32768 to 32767
Actually, the range of the integer constant depends on the compiler. The above mentioned range is for 16-bit compiler. However, for a 32-bit compiler the range would be even greater.
The integer constants
• Whole Numbers
• E.g. 25, 35, -25, -46
• Computer allocates only 2 bytes in memory.
• 16th bit is sign bit. (if 0 then positive value, if 1 then negative value)
Decimal Integer constant:
• 0 to 9
• E.g.: 49, 58, -62 … (40000 cannot come because it is > 32767)
Octal Integer constant:
• 0 to 7
• Add “0” before the value.
• E.g.: 045, 056, 067
Hexadecimal Integer constant:
• 0 to 9 and A to F
• Add 0x before the value
• E.g.: 0x42, 0x56, 0x67
Rules for constructing Real constants
Rules for constructing Real constants (Fractional Form)
1) A real constant must have at least one digit
2) It must have a decimal point
3) It could be either positive or negative
4) If no sign precedes an integer constant, it is assumed to be positive.
5) No commas or blanks are allowed within a real constant.
E.g.: +867.9, -26.9876, 654.0
Rules for constructing Real constants (Exponential Form)
1) The mantissa part and the exponential part should be separated by the letter ‘e’
2) The mantissa may have a positive or negative sign(default sign is positive)
3) The exponent must have at least one digit
4) The exponent must be a positive or negative integer(default sign is positive)
5) The range of real constants in exponential form is -3.4e38 and -3.4e38
E.g.: +3.2e-4, 4.1e8, -0.2e+4, -3.2e-4
Rules for constructing Character constant
1) A character constant is an alphabet, a single digit or a single special symbol enclosed within inverted commas. Both the inverted commas should point to the left. For example, ’S’ is a valid character constant whereas ‘S’ is not.
2) The maximum length of a character constant can be 1 character. Allots 1 byte of memory
E.g.: ’B’, ’l’, ’#’
Constants, Variables and Keywords in C
A constant, Variable or a keyword can be formed from any combination of Alphabets, Digits and Special Symbols. A constant is an entity whose value does not change throughout the program execution.
A variable is an entity whose value keeps on changing throughout the program execution. However, it’s not a rule that the value of the variable will change. A variable value might remain same throughout the program execution. However the main difference between variable and constant is that we can’t change the value of constant in between the program, but we can change the value of the variable during program execution.
Let us take an example:
We define a variable named x in a program. Let us say x=3.
After some time during execution we change the value of x to 6. Now, x=6.
Here value of x is getting changed. But the value of 3 and 6 will never change. Hence, x is called a variable and 3 is called a constant.
Keywords are the words whose meaning has already been explained to the C compiler. The keyword cannot be used as the variable name. If we try to do so we are trying to assign new meaning to the keyword. The keywords are also known as ‘Reserved words’.
E.g.: for, if, static, while, do, break etc.
A variable is an entity whose value keeps on changing throughout the program execution. However, it’s not a rule that the value of the variable will change. A variable value might remain same throughout the program execution. However the main difference between variable and constant is that we can’t change the value of constant in between the program, but we can change the value of the variable during program execution.
Let us take an example:
We define a variable named x in a program. Let us say x=3.
After some time during execution we change the value of x to 6. Now, x=6.
Here value of x is getting changed. But the value of 3 and 6 will never change. Hence, x is called a variable and 3 is called a constant.
Keywords are the words whose meaning has already been explained to the C compiler. The keyword cannot be used as the variable name. If we try to do so we are trying to assign new meaning to the keyword. The keywords are also known as ‘Reserved words’.
E.g.: for, if, static, while, do, break etc.
Introduction to C Programming Language
C is a programming language developed by AT & T’s Bell Laboratories of USA in 1972. It was designed and written by a man named Dennis Ritchie. C is reliable, simple and easy to use. C has survived for more than 3 decades. C language is a base to learn different programming language. If you want to learn C++ or JAVA, without the knowledge of C it becomes very difficult to learn these programming languages. Many major components of popular operating systems like Windows, UNIX, LINUX is still written in C. Nothing beats C in terms of speed of execution.
Before starting with the programming, let’s have a look at the C Character set.
Any alphabet, digit or special symbol can be termed as a character. Below table shows list of valid alphabets, digits and symbols allowed in C.
Alphabets:
A, B, C, D, … ,X, Y, Z
a, b, c, d, … ,x, y, z
Digits : 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Special Symbols :
~ ‘ ! @ # % ^ & * ( ) _ - + = | \ { }
[ ] : ; " ' < > , . ? /
Following are the basic data types:
1) Numeric data type: deals with numeric data such as integer or float data type
2) Non-numeric data type: deals with non numeric data such as characters.
3) Integer data type: deals with integer or whole number
4) Real data type: deals with numeric data that includes fractions
5) Enumerated data type: These data types are defined by the user.
Before starting with the programming, let’s have a look at the C Character set.
Any alphabet, digit or special symbol can be termed as a character. Below table shows list of valid alphabets, digits and symbols allowed in C.
Alphabets:
A, B, C, D, … ,X, Y, Z
a, b, c, d, … ,x, y, z
Digits : 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Special Symbols :
~ ‘ ! @ # % ^ & * ( ) _ - + = | \ { }
[ ] : ; " ' < > , . ? /
Following are the basic data types:
1) Numeric data type: deals with numeric data such as integer or float data type
2) Non-numeric data type: deals with non numeric data such as characters.
3) Integer data type: deals with integer or whole number
4) Real data type: deals with numeric data that includes fractions
5) Enumerated data type: These data types are defined by the user.
2-Dimensional Array in C Programming Language
An array is a collective name given to a group of similar variables. An array can be 1-Dimensional, 2-Dimensional, 3-Dimensional and so on. In this topic, we will discuss 2-Dimensional arrays in C Programming Language.
Let us understand what two dimensional arrays are. Consider the following matrix.
11 12 13
A= 14 15 16
17 18 19
The above mentioned matrix is 3 by 3. The matrix elements can be accessed using the formula A[m,n], where m represents row number and n represents column number.
Thus, the first element i.e. 11 is represented as A[0,0].
Similarly,
A[0,1] = 12
A[0,2] = 13
A[1,0] = 14
A[1,1] = 15 and so on.
The 2-dimensional array follows the similar concept. So we can declare 2-dimensional array for above matrix as A[3][3].
We can define 2-dimensional array as follows.
int A[3][3]={11,12,13,14,15,16,17,18,19}
Element 11 can be referred as A[0][0]
Element 12 can be referred as A[0][1]
Element 13 can be referred as A[0][2]
Element 14 can be referred as A[1][0]
Element 15 can be referred as A[1][1] and so on.
Another way to define 2-D array is:
int A[3][3]={
{11,12,13},
{14,15,16},
{17,18,19}
}
The above mentioned method increases the readability of the matrix.
int A[][] and A[3][] are invalid. We cannot skip the column index in 2-D arrays.
int A[][3] and A[3][3] are both valid.
Program that accept values in 2-Dimensional 3 by 3 array and displays the sum of all the elements.
void main(){
int arr[3][3], i, j, sum=0;
/*Accepts input from the user and stores it in 2-D array*/
for(i=0;i<3;i++){
for(j=0;j<3;j++){
printf(“\nEnter the value for A[%d][%d]: “,i,j);
scanf(“%d”,&arr[i][j]);
}
}
/*Calculate sum of elements in 2-D array*/
for(i=0;i<3;i++){
for(j=0;j<3;j++){
sum=sum+arr[i][j];
}
}
/*Display the value of sum*/
printf(“\nThe sum of the elements of 2-D array is %d”, sum);
}
Output:
Enter the value for A[0][0]: 1
Enter the value for A[0][1]: 2
Enter the value for A[0][2]: 3
Enter the value for A[1][0]: 4
Enter the value for A[1][1]: 5
Enter the value for A[1][2]: 6
Enter the value for A[2][0]: 7
Enter the value for A[2][1]: 8
Enter the value for A[2][2]: 9
The sum of the elements of 2-D array is 45
Explanation:
There are two for loops. The first one accepts input from the user and stores it in 2-D array.
The second one Calculates the sum of the elements present in 2-D array.
for(i=0;i<3;i++){
for(j=0;j<3;j++){
printf(“\nEnter the value for A[%d][%d]: “,i,j);
scanf(“%d”,&arr[i][j]);
}
}
Let us understand the above for loop iteration wise.
1st Iteration of Outer for loop:
Value of i=0. Condition i<3 is satisfied. Hence it enters this for loop.
1st Iteration of Inner for loop:
Value of j=0. Condition j<3 is satisfied. Hence it enters this for loop.
Here the value entered by the user is assigned to the variable arr[i][j] i.e. arr[0][0].
2nd Iteration of Inner for loop:
Value of j is incremented. Hence j=1. Condition j<3 is satisfied. Hence it enters this for loop.
Here the value entered by the user is assigned to the variable arr[i][j] i.e. arr[0][1].
3rd Iteration of Inner for loop:
Value of j is incremented. Hence j=2. Condition j<3 is satisfied. Hence it enters this for loop.
Here the value entered by the user is assigned to the variable arr[i][j] i.e. arr[0][2].
Now the value of j is again incremented. Hence j=3. But, the condition j<3 is not satisfied.
Hence it exits this inner for loop.
2nd Iteration of Outer for loop:
Value of i=1. Condition i<3 is satisfied. Hence it enters this for loop.
1st Iteration of Inner for loop:
Value of j=0. Condition j<3 is satisfied. Hence it enters this for loop.
Here the value entered by the user is assigned to the variable arr[i][j] i.e. arr[1][0].
2nd Iteration of Inner for loop:
Value of j is incremented. Hence j=1. Condition j<3 is satisfied. Hence it enters this for loop.
Here the value entered by the user is assigned to the variable arr[i][j] i.e. arr[1][1].
3rd Iteration of Inner for loop:
Value of j is incremented. Hence j=2. Condition j<3 is satisfied. Hence it enters this for loop.
Here the value entered by the user is assigned to the variable arr[i][j] i.e. arr[1][2].
Now the value of j is again incremented. Hence j=3. But, the condition j<3 is not satisfied.
Hence it exits this inner for loop.
3rd Iteration of Outer for loop:
Value of i=2. Condition i<3 is satisfied. Hence it enters this for loop.
1st Iteration of Inner for loop:
Value of j=0. Condition j<3 is satisfied. Hence it enters this for loop.
Here the value entered by the user is assigned to the variable arr[i][j] i.e. arr[2][0].
2nd Iteration of Inner for loop:
Value of j is incremented. Hence j=1. Condition j<3 is satisfied. Hence it enters this for loop.
Here the value entered by the user is assigned to the variable arr[i][j] i.e. arr[2][1].
3rd Iteration of Inner for loop:
Value of j is incremented. Hence j=2. Condition j<3 is satisfied. Hence it enters this for loop.
Here the value entered by the user is assigned to the variable arr[i][j] i.e. arr[2][2].
Now the value of j is again incremented. Hence j=3. But, the condition j<3 is not satisfied.
Hence it exits this inner for loop.
Now the value of i is again incremented. Hence i=3. But, the condition i<3 is not satisfied. Hence it exits this outer for loop.
Similar logic applies while calculating the addition of the array elements.
Let us understand what two dimensional arrays are. Consider the following matrix.
11 12 13
A= 14 15 16
17 18 19
The above mentioned matrix is 3 by 3. The matrix elements can be accessed using the formula A[m,n], where m represents row number and n represents column number.
Thus, the first element i.e. 11 is represented as A[0,0].
Similarly,
A[0,1] = 12
A[0,2] = 13
A[1,0] = 14
A[1,1] = 15 and so on.
The 2-dimensional array follows the similar concept. So we can declare 2-dimensional array for above matrix as A[3][3].
We can define 2-dimensional array as follows.
int A[3][3]={11,12,13,14,15,16,17,18,19}
Element 11 can be referred as A[0][0]
Element 12 can be referred as A[0][1]
Element 13 can be referred as A[0][2]
Element 14 can be referred as A[1][0]
Element 15 can be referred as A[1][1] and so on.
Another way to define 2-D array is:
int A[3][3]={
{11,12,13},
{14,15,16},
{17,18,19}
}
The above mentioned method increases the readability of the matrix.
int A[][] and A[3][] are invalid. We cannot skip the column index in 2-D arrays.
int A[][3] and A[3][3] are both valid.
Program that accept values in 2-Dimensional 3 by 3 array and displays the sum of all the elements.
void main(){
int arr[3][3], i, j, sum=0;
/*Accepts input from the user and stores it in 2-D array*/
for(i=0;i<3;i++){
for(j=0;j<3;j++){
printf(“\nEnter the value for A[%d][%d]: “,i,j);
scanf(“%d”,&arr[i][j]);
}
}
/*Calculate sum of elements in 2-D array*/
for(i=0;i<3;i++){
for(j=0;j<3;j++){
sum=sum+arr[i][j];
}
}
/*Display the value of sum*/
printf(“\nThe sum of the elements of 2-D array is %d”, sum);
}
Output:
Enter the value for A[0][0]: 1
Enter the value for A[0][1]: 2
Enter the value for A[0][2]: 3
Enter the value for A[1][0]: 4
Enter the value for A[1][1]: 5
Enter the value for A[1][2]: 6
Enter the value for A[2][0]: 7
Enter the value for A[2][1]: 8
Enter the value for A[2][2]: 9
The sum of the elements of 2-D array is 45
Explanation:
There are two for loops. The first one accepts input from the user and stores it in 2-D array.
The second one Calculates the sum of the elements present in 2-D array.
for(i=0;i<3;i++){
for(j=0;j<3;j++){
printf(“\nEnter the value for A[%d][%d]: “,i,j);
scanf(“%d”,&arr[i][j]);
}
}
Let us understand the above for loop iteration wise.
1st Iteration of Outer for loop:
Value of i=0. Condition i<3 is satisfied. Hence it enters this for loop.
1st Iteration of Inner for loop:
Value of j=0. Condition j<3 is satisfied. Hence it enters this for loop.
Here the value entered by the user is assigned to the variable arr[i][j] i.e. arr[0][0].
2nd Iteration of Inner for loop:
Value of j is incremented. Hence j=1. Condition j<3 is satisfied. Hence it enters this for loop.
Here the value entered by the user is assigned to the variable arr[i][j] i.e. arr[0][1].
3rd Iteration of Inner for loop:
Value of j is incremented. Hence j=2. Condition j<3 is satisfied. Hence it enters this for loop.
Here the value entered by the user is assigned to the variable arr[i][j] i.e. arr[0][2].
Now the value of j is again incremented. Hence j=3. But, the condition j<3 is not satisfied.
Hence it exits this inner for loop.
2nd Iteration of Outer for loop:
Value of i=1. Condition i<3 is satisfied. Hence it enters this for loop.
1st Iteration of Inner for loop:
Value of j=0. Condition j<3 is satisfied. Hence it enters this for loop.
Here the value entered by the user is assigned to the variable arr[i][j] i.e. arr[1][0].
2nd Iteration of Inner for loop:
Value of j is incremented. Hence j=1. Condition j<3 is satisfied. Hence it enters this for loop.
Here the value entered by the user is assigned to the variable arr[i][j] i.e. arr[1][1].
3rd Iteration of Inner for loop:
Value of j is incremented. Hence j=2. Condition j<3 is satisfied. Hence it enters this for loop.
Here the value entered by the user is assigned to the variable arr[i][j] i.e. arr[1][2].
Now the value of j is again incremented. Hence j=3. But, the condition j<3 is not satisfied.
Hence it exits this inner for loop.
3rd Iteration of Outer for loop:
Value of i=2. Condition i<3 is satisfied. Hence it enters this for loop.
1st Iteration of Inner for loop:
Value of j=0. Condition j<3 is satisfied. Hence it enters this for loop.
Here the value entered by the user is assigned to the variable arr[i][j] i.e. arr[2][0].
2nd Iteration of Inner for loop:
Value of j is incremented. Hence j=1. Condition j<3 is satisfied. Hence it enters this for loop.
Here the value entered by the user is assigned to the variable arr[i][j] i.e. arr[2][1].
3rd Iteration of Inner for loop:
Value of j is incremented. Hence j=2. Condition j<3 is satisfied. Hence it enters this for loop.
Here the value entered by the user is assigned to the variable arr[i][j] i.e. arr[2][2].
Now the value of j is again incremented. Hence j=3. But, the condition j<3 is not satisfied.
Hence it exits this inner for loop.
Now the value of i is again incremented. Hence i=3. But, the condition i<3 is not satisfied. Hence it exits this outer for loop.
Similar logic applies while calculating the addition of the array elements.
Sunday, February 17, 2013
C Program To Check Whether the Number is EVEN No. or ODD No.
#include<stdio.h>
#include<conio.h>
void main ()
{
int num;
clrscr ();
printf("\n Enter Any Number");
scanf ("%d", &num);
if (num%2==0)
{
printf ("\n %d is Even No.", num);
}
else
{
printf ("\n %d is Odd No.", num);
}
getch();
}
Follow us on Facebook
#include<conio.h>
void main ()
{
int num;
clrscr ();
printf("\n Enter Any Number");
scanf ("%d", &num);
if (num%2==0)
{
printf ("\n %d is Even No.", num);
}
else
{
printf ("\n %d is Odd No.", num);
}
getch();
}
Follow us on Facebook
Wednesday, February 13, 2013
C Program To Convert Fahrenheit Temperature to Celsius Temperature
#include<stdio.h>
#include<conio.h>
void main()
{
int ftemp;
float ctemp;
clrscr();
printf("\n Enter Temp in Fahrenheit");
scanf("%d",&ftemp);
ctemp=(ftemp-32)/1.8;
printf("\n The Temp is in ctemp %f",ctemp);
getch();
}
Follow us on Facebook
#include<conio.h>
void main()
{
int ftemp;
float ctemp;
clrscr();
printf("\n Enter Temp in Fahrenheit");
scanf("%d",&ftemp);
ctemp=(ftemp-32)/1.8;
printf("\n The Temp is in ctemp %f",ctemp);
getch();
}
Follow us on Facebook
C Program To create a STAR Design in Decreament Form
#include<stdio.h>
#include<conio.h>
void main ()
{
int i=0, j=0, pos;
clrscr ();
printf ("\n Enter Position No. of Rows");
scanf ("%d", &pos);
for (i=10; i>=0; i--)
{
printf ("\n");
for (j=i; j>=0; j--)
{
printf ("*");
}
}
getch ();
}
Follow us on Facebook
#include<conio.h>
void main ()
{
int i=0, j=0, pos;
clrscr ();
printf ("\n Enter Position No. of Rows");
scanf ("%d", &pos);
for (i=10; i>=0; i--)
{
printf ("\n");
for (j=i; j>=0; j--)
{
printf ("*");
}
}
getch ();
}
Follow us on Facebook
Program to perform addition of two 2 by 2 matrix
#include<stdio.h>
#include<conio.h>
void main(){
int arr1[10][10], arr2[10][10];
int arr3[][3]={
{0,0,0},
{0,0,0},
{0,0,0}
};
int i, j;
clrscr();
printf("Enter 3x3 array 1:\n");
for(i=0;i<3;i++){
for(j=0;j<3;j++){
printf("Enter element %d x %d:",i,j);
scanf("%d",&arr1[i][j]);
}
}
printf("Enter 3x3 array 2:\n");
for(i=0;i<3;i++){
for(j=0;j<3;j++){
printf("Enter element %d x %d:",i,j);
scanf("%d",&arr2[i][j]);
}
}
for(i=0;i<3;i++){
for(j=0;j<3;j++){
arr3[i][j]=arr1[i][j] + arr2[i][j];
}
}
printf("Addition of Array 1 and Array 2 is: \n");
for(i=0;i<3;i++){
for(j=0;j<3;j++){
printf("\t%d",arr3[i][j]);
}
printf("\n");
}
getch();
}
Output:
Enter 3x3 array 1:
Enter element 0 x 0:1
Enter element 0 x 1:1
Enter element 0 x 2:1
Enter element 1 x 0:1
Enter element 1 x 1:1
Enter element 1 x 2:1
Enter element 2 x 0:1
Enter element 2 x 1:1
Enter element 2 x 2:1
Enter 3x3 array 2:
Enter element 0 x 0:1
Enter element 0 x 1:1
Enter element 0 x 2:1
Enter element 1 x 0:1
Enter element 1 x 1:1
Enter element 1 x 2:1
Enter element 2 x 0:1
Enter element 2 x 1:1
Enter element 2 x 2:1
Addition of Array 1 and Array 2 is:
2 2 2
2 2 2
2 2 2
Follow us on Facebook
#include<conio.h>
void main(){
int arr1[10][10], arr2[10][10];
int arr3[][3]={
{0,0,0},
{0,0,0},
{0,0,0}
};
int i, j;
clrscr();
printf("Enter 3x3 array 1:\n");
for(i=0;i<3;i++){
for(j=0;j<3;j++){
printf("Enter element %d x %d:",i,j);
scanf("%d",&arr1[i][j]);
}
}
printf("Enter 3x3 array 2:\n");
for(i=0;i<3;i++){
for(j=0;j<3;j++){
printf("Enter element %d x %d:",i,j);
scanf("%d",&arr2[i][j]);
}
}
for(i=0;i<3;i++){
for(j=0;j<3;j++){
arr3[i][j]=arr1[i][j] + arr2[i][j];
}
}
printf("Addition of Array 1 and Array 2 is: \n");
for(i=0;i<3;i++){
for(j=0;j<3;j++){
printf("\t%d",arr3[i][j]);
}
printf("\n");
}
getch();
}
Output:
Enter 3x3 array 1:
Enter element 0 x 0:1
Enter element 0 x 1:1
Enter element 0 x 2:1
Enter element 1 x 0:1
Enter element 1 x 1:1
Enter element 1 x 2:1
Enter element 2 x 0:1
Enter element 2 x 1:1
Enter element 2 x 2:1
Enter 3x3 array 2:
Enter element 0 x 0:1
Enter element 0 x 1:1
Enter element 0 x 2:1
Enter element 1 x 0:1
Enter element 1 x 1:1
Enter element 1 x 2:1
Enter element 2 x 0:1
Enter element 2 x 1:1
Enter element 2 x 2:1
Addition of Array 1 and Array 2 is:
2 2 2
2 2 2
2 2 2
Follow us on Facebook
Subscribe to:
Posts (Atom)