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
[Read More...]


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.
[Read More...]


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}
[Read More...]


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

Demonstration on Pointer Operations
[Read More...]


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);
}
[Read More...]


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
[Read More...]


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);
[Read More...]


 

Total Pageviews

Return to top of page Copyright © 2011 | Kuppam Engineering College Converted into Blogger Template by Mohan Murthy