C Programming Arrays
C Programming Arrays
In C programming, one of the frequently arising problem is to handle similar types of data.
For example: If the user want to store marks of 100 students. This can be done by creating
100 variable individually but, this process is rather tedious and impracticable. These type of
problem can be handled in C programming using arrays.
An array is a sequence of data item of homogeneous value(same type).
Arrays are of two types:
1. One-dimensional arrays
2. Multidimensional arrays( will be discussed in next chapter )
Here, the name of array is age. The size of array is 5,i.e., there are 5 items(elements) of array
age. All element in an array are of the same type (int, in this case).
Array elements
Size of array defines the number of elements in an array. Each element of array can be
accessed and used by user according to the need of program. For example:
int age[5];
In this case, the compiler determines the size of array by calculating the number of elements
of an array.
Output
Enter number of students: 3
Enter marks of student1: 12
In this tutorial you will learn about Initializing Strings, Reading Strings from the terminal,
Writing strings to screen, Arithmetic operations on characters, String operations (string.h),
Strlen() function, strcat() function, strcmp function, strcmpi() function, strcpy() function,
strlwr () function, strrev() function and strupr() function.
In C language, strings are stored in an array of char type along with the null terminating
character "\0" at the end. In other words to create a string in C you create an array of chars
and set each element in the array to a char value that makes up the string. When sizing the
string array you need to add plus one to the actual size of the string to make space for the null
terminating character, "\0"
Syntax to declare a string in C:
Sample Code
1.
char fname[4];
Copyright exforsys.com
The above statement declares a string called fname that can take up to 3 characters. It can be
indexed just as a regular array as well.
fname[] = {'t','w','o'};
Character
\0
ASCII Code
116
119
41
The last character is the null character having ASCII value zero.
Initializing Strings
To initialize our fname string from above to store the name Brian,
Sample Code
1.
You can observe from the above statement that initializing a string is same as with any array.
However we also need to surround the string with quotes.
The above statement prints the prompt in the quotes and moves the cursor to the next line.
If you wanted to print a string from a variable, such as our fname string above you can do
this:
Sample Code
1.
You can insert more than one variable, hence the "..." in the prototype for printf but this is
sufficient. Use %s to insert a string and then list the variables that go to each %s in your
string you are printing. It goes in order of first to last. Let's use a first and last name printing
example to show this:
Sample Code
1.
The first name would be displayed first and the last name would be after the space between
the %s's.
2.
3. void main() {
4.
5.
char fname[30];
6.
char lname[30];
7.
8.
9.
scanf("%s", fname);
10.
11.
12.
scanf("%s", lname);
13.
14.
15. }
Copyright exforsys.com
We declare two strings fname and lname. Then we use the printf function to prompt the user
for a first name. The scanf function takes the input from stdin and automatically exits once
the user presses enter. Then we repeat the above sequence except using the last name this
time. Finally we print the full name that was typed back to stdout. Should look something like
this:
Characters in C can be used just like integers when used with arithmetic operators. This is
nice, for example, in low memory applications because unsigned chars take up less memory
than do regular integers as long as your value does not exceed the rather limited range of an
unsigned char.
Let us cut to our example,
charmath.c:
Sample Code
1.
#include <stdio.h>
2.
void main() {
3.
4.
5.
int answer;
6.
7.
printf("%d\n", val1);
8.
printf("%d\n", val2);
9.
10.
11.
12.
13.
val1 = 'a';
14.
15.
16.
17.
First we make two unsigned character variables and give them (rather low) number values.
We then add them together and put the answer into an integer variable. We can do this
without a cast because characters are an alphanumeric data type. Next we set var1 to an
expected character value, the letter lowercase a. Now this next addition adds 97 to 30, why?
Because the ASCII value of lowercase a is 97. So it adds 97 to 30, the current value in var2.
Notice it did not require casting the characters to integers or having the compiler complain.
This is because the compiler knows when to automatically change between characters and
integers or other numeric types.
String Operations
Character arrays are a special type of array that uses a "\0" character at the end. As such it has
it is own header library called string.h that contains built-in functions for performing
operations on these specific array types.
You must include the string header file in your programs to utilize this functionality.
Sample Code
1.
#include <string.h>
Copyright exforsys.com
We will cover the essential functions from this library over the next few sections.
Length of a String
Use the strlen function to get the length of a string minus the null terminating character.
Sample Code
1.
int strlen(string);
Copyright exforsys.com
If we had a string, and called the strlen function on it we could get its length.
Sample Code
1.
2.
Concatenation of Strings
The first string gets the second string appended to it. So for example to print a full name from
a first and last name string we could do the following:
Sample Code
1.
2.
3.
The return value indicates how the 2 strings relate to each other. if they are equal strcmp
returns 0. The value will be negative if string1 is less than string2, or positive in the opposite
case.
For example if we add the following line to the end of our getname.c program:
Sample Code
1.
When run on a Linux computer with the following first and last name combinations, the
program will yield the following output.
Sample Code
1.
2.
3.
Imagine using this function in place of strcmp in the above example, all of the first and last
combinations would output 0.
Copy Strings
To copy one string to another string variable, you use the strcpy function. This makes up for
not being able to use the "=" operator to set the value of a string variable.
Sample Code
1.
strcpy(string1, string2);
Copyright exforsys.com
To set the first name of our running example in code rather than terminal input we would use
the following:
Sample Code
1.
strcpy(fname, "Bob");
Copyright exforsys.com
strlwr(string);
Copyright exforsys.com
This will convert uppercase characters in string to lowercase. So "BOBBY" would become
"bobby".
strrev(string);
Copyright exforsys.com
Will reverse the order of string. So if string was "bobby", it would become "ybbob".
C Arithmetic Operators
Arithmetic operators include the familiar addition (+), subtraction (-), multiplication (*) and
division (/) operations. In addition there is the modulus operator (%) which gives the
remainder left over from a division operation. Let us look at some examples:
Sample Code
1.
#include <stdio.h>
2.
3.
void main()
4.
5.
int a = 100;
6.
int b = 3;
7.
int c;
8.
9.
c = a + b;
10.
11.
12.
c = a - b;
13.
14.
15.
16.
17.
18.
c = a / b;
19.
20.
21.
c = 100 % 3;
22.
23. }
Copyright exforsys.com
Note Though the usual definition of the main() function is int main(), few compilers allow
the main() function to return void. The C standard allows for implementation defined
versions of main() that do not return int. If your compiler does not allow that, change line 3 to
int main() and put a return statement return 0; at the end just before line 23.
+
*
/
%
b
b
b
b
b
=
=
=
=
=
103
97
300
33
1
In this example you can see on line 16 that it is not always necessary to assign the result of an
operation to a variable. The multiplication is performed first, then the result is passed to the
printf() function. On line 21 we see an example of using an operator on constants, with the
100 and 3 replacing the variables a and b.
If the modulus operator on line 21 is new to you, it is the remainder left over when one
integral number is divided by another. For example 45 % 6 is 3 since 6 * 7 is 42 and the
remainder is 3. The modulus operator works only with integral types (char, short, int, etc.). If
you try to use it with other types such as a float or double the compiler will give an error.
So far we have only used integers in our examples. When you use an operator on mixed types
they will be implicitly converted into a common type before the operation is performed. The
result of the operation will also be in the common type. The common type is derived using a
few rules, but generally, a smaller operand is converted to the larger operand's type. If the
result of the operation is assigned to another variable, the result is converted from the
common type to the type of that variable. Let us look at some examples:
Sample Code
1.
#include <stdio.h>
2.
3.
void main()
4.
5.
int a = 65000;
6.
char c = 120;
7.
int iresult;
8.
char cresult;
9.
10.
iresult = a + c;
11.
12.
13.
cresult = a + c;
14.
15. }
16.
Copyright exforsys.com
On the system where this example was run, an int type is a signed 32 bit number, and a char
type is a signed 8 bit number. When the a + c operation is performed, c is converted to an int
and then added to a, resulting in an another int.
On line 10 this integer is assigned to iresult, which is also an int so no conversion is
necessary.
On line 13 the result is assigned to a char, which means the int result must be converted into a
char. The binary representation of 65120 is 1111111001100000. Truncating this to just the
first 8 bits (since a char is 8 bits on this machine) gives 01100000 which is 96 in decimal.
Another example:
Sample Code
1.
#include <stdio.h>
2.
3.
void main()
4.
5.
int a = 4;
6.
float b = 3.14159;
7.
int iresult;
8.
float fresult;
9.
10.
fresult = a * b;
11.
12.
13.
iresult = a * b;
14.
15. }
Copyright exforsys.com
A similar process happens in this example. The integer a is converted to a float since a float is
capable of holding integers but not vice-versa. The result of the multiplication is a float,
which must be converted back to an int on line 13. This is done by truncating the fractional
part of the float.
This conversion process happens for constants too.
Sample Code
1.
#include <stdio.h>
2.
3.
void main()
4.
5.
double d = 15 / 6;
6.
7.
8.
d = 15.0 / 6;
9.
10.
}
Copyright exforsys.com
On line 5 both the constants are integers, so an integer division is performed and then the
result converted to a double. On line 8 the 15.0 is a double constant which forces the division
to be done using double precision floating point numbers, and then the result assigned to d.
C Relational Operators
Relational operators compare operands and return 1 for true or 0 for false. The following
relational operators are available:
Symbol
<
>
<=
>=
==
!=
Meaning
Less than
Greater than
Less than or equal to
Greater than or equal to
Equal to
Not equal to
Here is an example of how to use these operators. This program is a simple number guessing
game:
Sample Code
1. #include <stdio.h>
2.
#include <stdlib.h>
3.
#include <time.h>
4.
5.
void main()
6.
7.
int mynum;
8.
9.
char buffer[64];
10.
11.
srand( time(0) );
12.
13.
14.
15.
16.
17.
18.
19.
20.
break;
21.
22.
23.
24.
25.
26.
continue;
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
if ( guess == mynum )
printf( "You guessed correctly.n" );
37. }
Copyright exforsys.com
The output from a typical run is shown here (user entered values in red):
I have picked a number between 1-100.
Enter your guess: 300
Your guess is out of bounds.
Enter your guess: 50
Your guess is too high.
Enter your guess: 25
Your guess is too low.
Enter your guess: 37
Your guess is too high.
Enter your guess: 31
Your guess is too high.
Enter your guess: 28
Your guess is too high.
Enter your guess: 26
You guessed correctly.
When the program is first run, the condition in the while loop on line 16 is satisfied because
guess was initialized to -1 on line 8 and lines 11-12 initialize mynum with a random number
between 1 and 100. Lines 18-21 tell the user to enter their guess and read the input from the
user.
The if statement on line 23 uses the or operator || which will be covered later it basically
says if the user enters a number greater than or equal to 101 or less than or equal to 0 then tell
the user the guess is invalid. The program will keep looping until the user guesses the right
value or there is an error reading input from the user (the break statement on line 20 breaks
out of the loop in that case).
You can compare values of different types. Just like with arithmetic operations, the operands
are converted to a common type and then compared.
Sample Code
1.
#include <stdio.h>
2.
3.
void main()
4.
5.
6.
7.
if ( ( dnum > 5 ) == 1 )
8.
9.
else
The integer constant 5 on line 7 is converted to a double and compared with dnum. The
comparison returns the integer 1 for true, which is then compared for equality with the integer
1. This is a convoluted example just to show comparison of different types and that the
relational operators return an integer result. Line 7 could have been written simply as if
( dnum > 5 ).
Loops are group of instructions executed repeatedly while certain condition remains true.
There are two types of loops, counter controlled and sentinel controlled loops (repetition).
Counter controlled repetitions are the loops which the number of repetitions needed for the
loop is known before the loop begins; these loops have control variables to count repetitions.
Counter controlled repetitions need initialized control variable (loop counter), an increment
(or decrement) statement and a condition used to terminate the loop (continuation condition).
Sentinel controlled repetitions are the loops with an indefinite repetitions; this type of loops
use sentinel value to indicate end of iteration.
Loops are mostly used to output the data stored in arrays, however they are also used for
sorting and searching of data.
For Loop
For loops is a counter controlled repetition; therefore the number iterations must be known
before the loop starts.
Sample Code
1. for(control-variable; continuation-condition;increment/decrement-control) {
2. code to iterate
3. }
Copyright exforsys.com
Hint: if the code to iterate is only a single line then the braces ({ }) can be ignored.
Diagram 1 illustrates for statement operation.
3.
Hint: test-expression must be initialized otherwise errors will be generated when trying to
compile the code.
Diagram 3 illustrates how while statement operates
3. }while(test-expression)
Copyright exforsys.com
11. }
12. while(input !=0);
Copyright exforsys.com
Sample Code
1. int counter;
2. for(counter=1;counter<=10;counter++)
3. {
4. printf("nnumber: %d before break",counter);
5. if(counter==2)
6.
break;
7.
8. }
9. printf("nloop was escaped at %d",counter);
Copyright exforsys.com
C Programming - Pointers
Author: Brian Moriya
25th Mar 2011
Pointers are widely used in programming; they are used to refer to memory location of
another variable without using variable identifier itself. They are mainly used in linked lists
and call by reference functions.
Diagram 1 illustrates the idea of pointers. As you can see below; Yptr is pointing to memory
address 100.
Declaring pointers can be very confusing and difficult at times (working with structures and
pointer to pointers). To declare pointer variable we need to use * operator
(indirection/dereferencing operator) before the variable identifier and after data type. Pointer
can only point to variable of the same data type.
Syntax
Sample Code
1. Datatype * identifier;
Copyright exforsys.com
Example
Character Pointer
Sample Code
1. #include <stdio.h>
2. int main()
3. {
4. char a='b';
5. char *ptr;
6. printf("%cn",a);
7. ptr=&a;
8. printf("%pn",ptr);
9. *ptr='d';
10. printf("%cn",a);
11. return 0;
12. }
Copyright exforsys.com
Output
Address operator (&) is used to get the address of the operand. For example if variable x is
stored at location 100 of memory; &x will return 100.
This operator is used to assign value to the pointer variable. It is important to remember that
you MUST NOT use this operator for arrays, no matter what data type the array is holding.
This is because array identifier (name) is pointer variable itself. When we call for ArrayA[2];
ArrayA returns the address of first item in that array so ArrayA[2] is the same as saying
ArrayA+=2; and will return the third item in that array.
Pointer arithmetic
Pointers can be added and subtracted. However pointer arithmetic is quite meaningless unless
performed on arrays. Addition and subtraction are mainly for moving forward and backward
in an array.
Note: you have to be very careful NOT to exceed the array elements when you use arithmetic;
otherwise you will get horrible errors such as access violation. This error is caused because
your code is trying to access a memory location which is registered to another program.
Operator
Result
++
--
-= or -
+= or +
Example:
Sample Code
1. #include <stdio.h>
2. int main()
3. {
4. int ArrayA[3]={1,2,3};
5. int *ptr;
6. ptr=ArrayA;
7. printf("address: %p - array value:%d n",ptr,*ptr);
8. ptr++;
9. printf("address: %p - array value:%d n",ptr,*ptr);
10. return 0;
11. }
Copyright exforsys.com
Output
Note: & notation should not be used with arrays because arrays identifier is pointer to the
first element of the array.
Pointers and functions
Pointers can be used with functions. The main use of pointers is call by reference functions.
Call by reference function is a type of function that has pointer/s (reference) as parameters to
that function. All calculation of that function will be directly performed on referred variables.
Sample Code
1. #include <stdio.h>
2. void DoubleIt(int *num)
3. {
4.
*num*=2;
5. }
6. int main()
7. {
8.
int number=2;
9.
10.
DoubleIt(&number);
printf("%d",number);
11. return 0;
12. }
Copyright exforsys.com
Output
Array identifier is a pointer itself. Therefore & notation shouldnt be used with arrays. The
example of this can be found at code 3. When working with arrays and pointers always
remember the following:
When passing array to function you dont need * for your declaration.
Pointers and structures is broad topic and it can be very complex to include it all in one single
tutorial. However pointers and structures are great combinations; linked lists, stacks, queues
and etc are all developed using pointers and structures in advanced systems.
Example:
Number Structure
Sample Code
1. #include <stdio.h>
2.
3. struct details {
4. int num;
5. };
6.
7. int main()
8. {
9.
10. struct details MainDetails;
11. struct details *structptr;
12. structptr=&MainDetails;
13. structptr->num=20;
14. printf("n%d",MainDetails.num);
15.
16.
17. return 0;
18. }
Copyright exforsys.com
Output
Pointers can point to other pointers; there is no limit whatsoever on how many pointer to
pointer links you can have in your program. It is entirely up to you and your programming
skills to decide how far you can go before you get confused with the links. Here we will only
look at simple pointer to pointer link. Pointing to pointer can be done exactly in the same way
as normal pointer. Diagram below can help you understand pointer to pointer relationship.