fundamentals of C programming
C language Tutorial with programming approach for beginners and professionals, helps you to understand the C language tutorial easily. Our C tutorial explains each topic with programs.
The C Language is developed by Dennis Ritchie in 1972 for creating system applications that directly interact with the hardware devices such as drivers, kernels, etc.
C programming is considered as the base for other programming languages, that is why it is known as mother language.
It can be defined by the following ways:
- Mother language
- System programming language
- Procedure-oriented programming language
- Structured programming language
- Mid-level programming language
Learn the Basics:-
Most students of programming languages, start from the famous 'Hello World' code. This program prints 'Hello World' when executed. This simple example tries to make understand that how C programs are constructed and executed.
#include <stdio.h> int main() { printf("Hello World!"); return 0; }
The output of the program should be −
Hello World!
- Variables and Types
Let’s learn about variables and data types in C Programming. We will first look at Variables in C; Variables are used to store the value during the execution of a program. The name itself means, the value of variable can be changed hence the name “Variable“. The variables are stored in Main Memory i.e. RAM (size depending on the data type). In C Programming we always have to declare variable before we can use them. Note that the space is allocated to variable in memory during execution or run-time.
C is a strongly typed language. What this means it that, the type of a variable cannot be changed. Suppose we declared an integer type variable so we cannot store character or a decimal number in that variable.
There are set of rules to be followed while declaring variables and data types in C Programming:
- The 1st letter should be alphabet.
- Variables can be combination of alphabets and digits.
- Underscore (_) is the only special character allowed.
- Variables can be written in both Uppercase and Lowercase or combination of both.
- Variables are Case Sensitive.
- No Spaces allowed between Characters.
- Variable name should not make use to the C Reserved Keywords.
- Variable name should not start with a number.
EXAMPLE 1: Integer Variable in C
The %d is to tell printf() function to format the integer i as a decimal number. The output from this program would be This is my integer: 10.
EXAMPLE 2: Float Variable in C
The %f is to tell printf() function to format the float variable f as a decimal floating number. The output from this program would be This is my float: 3.1415. Now if we want to see only the first 2 numbers after the floating point, we would have to modify printf() function call to be as given below:
After replacing printf function in a given example. The output from this program would be This is my float: 3.14.
EXAMPLE 3: Character Variable in C
The %c is to tell printf() function to format the variable “c” as a character. The output from this program would be This is my character: b.
Data types in C Programming
All the data types defined by C are made up of units of memory called bytes. On most computer architectures a byte is made up of eight bits, each bit stores a one or a zero. These eight bits with two states give 256 combinations (28). So an integer which takes up four bytes can store a number between 0 to 4,294,967,295 (0 and 232). However, integer variables use the first bit to store whether the number is positive or negative so their value will be between -2,147,483,648 and + 2,147,483,647.
As we mentioned, there are eight basic data types defined in the C language. Five types for storing integers of varying sizes and three types for storing floating point values (values with a decimal point). C doesn’t provide a basic data type for text. Text is made up of individual characters and characters are represented by numbers. In the last example we used one of the integer types: int. This is the most commonly used type in the C language.
Data Type | Size | Value Range |
char | 1 byte | -128 to 127 or 0 to 255 |
unsigned char | 1 byte | 0 to 255 |
signed char | 1 byte | -128 to 127 |
int | 2 or 4 bytes | -32,768 to 32,767 or -2,147,483,648 to 2,147,483,647 |
unsigned int | 2 or 4 bytes | 0 to 65,535 or 0 to 4,294,967,295 |
short | 2 byte | -32,768 to 32,767 |
unsigned short | 2 byte | 0 to 65,535 |
long | 4 byte | -2,147,483,648 to 2,147,483,647 |
unsigned long | 4 byte | 0 to 4,294,967,295 |
The char data type is usually one byte, it is so called because they are commonly used to store single characters. The size of the other types is dependent on machine. Most desktop machines are “32-bit”, this refers to the size of data that they are designed for processing. On “32-bit” machines the int data type takes up 4 bytes (232). The short is usually smaller, the long can be larger or the same size as an int and finally the long long is for handling very large numbers.
The type of variable you use generally doesn’t have a big impact on the speed or memory usage of your application. Unless you have a special need you can just use int variables. We will try to point out the few different cases like. A decade ago, most machines had 16-bit processors, this limited the size of int variables to 2 bytes. At the time, short variables were usually also 2 bytes and long would be 4 bytes. Nowadays, with 32-bit machines, the default type (int) is usually large enough to satisfy what used to require a variable of type long. The long long type was introduced more recently to handle very large numeric values.
EXAMPLE 3: Calculate Size of Data type on Your Machine
To find out the size of each data type on your machine compile and run this program. It uses one new language construct sizeof(). This tells us how many bytes a data type takes up.
The output from this program would be:
Some computers are better at handling really big numbers, so the size of the data types will be bigger on these machines. Now we know most basic building blocks i.e. variables and data types in C Programming. In next lesson we will covers Operators in C Programming which allows us to solve many computing issues while programming.
- conditions
Decision Making
In life, we all have to make decisions. In order to make a decision we weigh out our options and so do our programs.
Here is the general form of the decision making structures found in C.
int target = 10;
if (target == 10) {
printf("Target is equal to 10");
}
The if
statement
The
if
statement allows us to check if an expression is true
or false
, and execute different code according to the result.
To evaluate whether two variables are equal, the
==
operator is used, just like in the first example.
Inequality operators can also be used to evaluate expressions. For example:
int foo = 1;
int bar = 2;
if (foo < bar) {
printf("foo is smaller than bar.");
}
if (foo > bar) {
printf("foo is greater than bar.");
}
We can use the
else
keyword to exectue code when our expression evaluates to false
.int foo = 1;
int bar = 2;
if (foo < bar) {
printf("foo is smaller than bar.");
} else {
printf("foo is greater than bar.");
}
Sometimes we will have more than two outcomes to choose from. In these cases, we can "chain" multiple
if
else
statements together.int foo = 1;
int bar = 2;
if (foo < bar) {
printf("foo is smaller than bar.");
} else if (foo == bar) {
printf("foo is equal to bar.");
} else {
printf("foo is greater than bar.");
}
You can also nest
if
else
statements if you like.int peanuts_eaten = 22;
int peanuts_in_jar = 100;
int max_peanut_limit = 50;
if (peanuts_in_jar > 80) {
if (peanuts_eaten < max_peanut_limit) {
printf("Take as many peanuts as you want!\n");
}
} else {
if (peanuts_eaten > peanuts_in_jar) {
printf("You can't have anymore peanuts!\n");
}
else {
printf("Alright, just one more peanut.\n");
}
}
Two or more expressions can be evaluated together using logical operators to check if two expressions evaluate to
true
together, or at least one of them. To check if two expressions both evaluate to true
, use the AND operator &&
. To check if at least one of the expressions evaluate to true
, use the OR operator ||
.int foo = 1;
int bar = 2;
int moo = 3;
if (foo < bar && moo > bar) {
printf("foo is smaller than bar AND moo is larger than bar.");
}
if (foo < bar || moo > bar) {
printf("foo is smaller than bar OR moo is larger than bar.");
}
The NOT operator
!
can also be used likewise:int target = 9;
if (target != 10) {
printf("Target is not equal to 10");
}
In programming, a loop is used to repeat a block of code until the specified condition is met.
C programming has three types of loops:
- for loop
- while loop
- do...while loop
for loops:-
We will learn about
for
loop in this tutorial. In the next tutorial, we will learn about while
and do...while
loop.
The syntax of the
for
loop is:for (initializationStatement; testExpression; updateStatement)
{
// statements inside the body of loop
}
How for loop works?
- The initialization statement is executed only once.
- Then, the test expression is evaluated. If the test expression is evaluated to false, the
for
loop is terminated. - However, if the test expression is evaluated to true, statements inside the body of
for
loop are executed, and the update expression is updated. - Again the test expression is evaluated.
This process goes on until the test expression is false. When the test expression is false, the loop terminates.
Example 1: for loop
// Print numbers from 1 to 10
#include <stdio.h>
int main() {
int i;
for (i = 1; i < 11; ++i)
{
printf("%d ", i);
}
return 0;
}
Output
1 2 3 4 5 6 7 8 9 10
Example 2: for loop
// Program to calculate the sum of first n natural numbers // Positive integers 1,2,3...n are known as natural numbers #include <stdio.h> int main() { int num, count, sum = 0; printf("Enter a positive integer: "); scanf("%d", &num); // for loop terminates when num is less than count for(count = 1; count <= num; ++count) { sum += count; } printf("Sum = %d", sum); return 0; }
While loops:-
The syntax of the
while
loop is:while (testExpression)
{
// statements inside the body of the loop
}
How while loop works?
- The
while
loop evaluates the test expression inside the parenthesis()
. - If the test expression is true, statements inside the body of
while
loop are executed. Then, the test expression is evaluated again. - The process goes on until the test expression is evaluated to false.
- If the test expression is false, the loop terminates (ends).
Example 1: while loop
// Print numbers from 1 to 5
#include <stdio.h>
int main()
{
int i = 1;
while (i <= 5)
{
printf("%d\n", i);
++i;
}
return 0;
}
Output
1 2 3 4 5
do...while loop:
Thedo..while
loop is similar to thewhile
loop with one important difference. The body ofdo...while
loop is executed at least once. Only then, the test expression is evaluated.The syntax of thedo...while
loop is:do { // statements inside the body of the loop } while (testExpression);
How do...while loop works?
- The body of do...while loop is executed once. Only then, the test expression is evaluated.
- If the test expression is true, the body of the loop is executed again and the test expression is evaluated.
- This process goes on until the test expression becomes false.
- If the test expression is false, the loop ends.
Example 2: do...while loop
// Program to add numbers until the user enters zero #include <stdio.h> int main() { double number, sum = 0; // the body of the loop is executed at least once do { printf("Enter a number: "); scanf("%lf", &number); sum += number; } while(number != 0.0); printf("Sum = %.2lf",sum); return 0; }
OutputEnter a number: 1.5 Enter a number: 2.4 Enter a number: -3.4 Enter a number: 4.2 Enter a number: 0 Sum = 4.70
c break & continue statement
C break
The break statement ends the loop immediately when it is encountered. Its syntax is:
break;
The break statement is almost always used with
if...else
statement inside the loop.How break statement works?
Example 1: break statement
// Program to calculate the sum of a maximum of 10 numbers
// If a negative number is entered, the loop terminates
# include <stdio.h>
int main()
{
int i;
double number, sum = 0.0;
for(i=1; i <= 10; ++i)
{
printf("Enter a n%d: ",i);
scanf("%lf",&number);
// If the user enters a negative number, the loop ends
if(number < 0.0)
{
break;
}
sum += number; // sum = sum + number;
}
printf("Sum = %.2lf",sum);
return 0;
}
Output
Enter a n1: 2.4 Enter a n2: 4.5 Enter a n3: 3.4 Enter a n4: -3 Sum = 10.30
This program calculates the sum of a maximum of 10 numbers. Why a maximum of 10 numbers? It's because if the user enters a negative number, the
break
statement is executed. This will end the for
loop, and the sum is displayed.
In C,
break
is also used with the switch
statement. This will be discussed in the next tutorial.C continue
The
continue
statement skips the current iteration of the loop and continues with the next iteration. Its syntax is:continue;
The
continue
statement is almost always used with the if...else
statement.How continue statement works?
Example 2: continue statement
// Program to calculate the sum of a maximum of 10 numbers
// Negative numbers are skipped from the calculation
# include <stdio.h>
int main()
{
int i;
double number, sum = 0.0;
for(i=1; i <= 10; ++i)
{
printf("Enter a n%d: ",i);
scanf("%lf",&number);
if(number < 0.0)
{
continue;
}
sum += number; // sum = sum + number;
}
printf("Sum = %.2lf",sum);
return 0;
}
Output
Enter a n1: 1.1 Enter a n2: 2.2 Enter a n3: 5.5 Enter a n4: 4.4 Enter a n5: -3.4 Enter a n6: -45.5 Enter a n7: 34.5 Enter a n8: -4.2 Enter a n9: -1000 Enter a n10: 12 Sum = 59.70
C switch Statement
The switch statement allows us to execute one code block among many alternatives.
You can do the same thing with the
if...else..if
ladder. However, the syntax of the switch
statement is much easier to read and write.Syntax of switch...case
switch (expression)
{
case constant1:
// statements
break;
case constant2:
// statements
break;
.
.
.
default:
// default statements
}
How does the switch statement work?
The expression is evaluated once and compared with the values of each case label.
- If there is a match, the corresponding statements after the matching label are executed. For example, if the value of the expression is equal to constant2, statements after
case constant2:
are executed untilbreak
is encountered. - If there is no match, the default statements are executed.
If we do not use
break
, all statements after the matching label are executed.
By the way, the
default
clause inside the switch
statement is optional.Example: Simple Calculator
// Program to create a simple calculator
#include <stdio.h>
int main() {
char operator;
double n1, n2;
printf("Enter an operator (+, -, *, /): ");
scanf("%c", &operator);
printf("Enter two operands: ");
scanf("%lf %lf",&n1, &n2);
switch(operator)
{
case '+':
printf("%.1lf + %.1lf = %.1lf",n1, n2, n1+n2);
break;
case '-':
printf("%.1lf - %.1lf = %.1lf",n1, n2, n1-n2);
break;
case '*':
printf("%.1lf * %.1lf = %.1lf",n1, n2, n1*n2);
break;
case '/':
printf("%.1lf / %.1lf = %.1lf",n1, n2, n1/n2);
break;
// operator doesn't match any case constant +, -, *, /
default:
printf("Error! operator is not correct");
}
return 0;
}
Output
Enter an operator (+, -, *,): - Enter two operands: 32.5 12.4 32.5 - 12.4 = 20.1
Array is a collection of homogenous data, arranged in sequential format. Learning the concept of arrays in C is very important as it is the basic data structure. Here, in this section, we shall look into some very useful array programs to give you insight of how C programming language deals with arrays.
Single Array Programs
These programs are basic and involves only a single array variable. We shall learn how to handle array variable in different situation.
1.A program to print an array
#include <stdio.h> int main() { int array[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0}; int loop; for(loop = 0; loop < 10; loop++) printf("%d ", array[loop]); return 0; }
The output should look like this −
1 2 3 4 5 6 7 8 9 0
#include <stdio.h> int main() { int array[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0}; int loop; for(loop = 9; loop >= 0; loop--) printf("%d ", array[loop]); return 0; }
The output should look like this −
0 9 8 7 6 5 4 3 2 1
3.Program to calculate sum of an array
#include <stdio.h> int main() { int array[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0}; int sum, loop; sum = 0; for(loop = 9; loop >= 0; loop--) { sum = sum + array[loop]; } printf("Sum of array is %d.", sum); return 0; }The output should look like this −Average of array values is 4.50
#include <stdio.h> int main() { int array[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0}; int sum, loop; float avg; sum = avg = 0; for(loop = 0; loop < 10; loop++) { sum = sum + array[loop]; } avg = (float)sum / loop; printf("Average of array values is %.2f", avg); return 0; }
The output should look like this −
Average of array values is 4.50
5.Program to find the largest element of an array
#include <stdio.h> int main() { int array[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0}; int loop, largest; largest = array[0]; for(loop = 1; loop < 10; loop++) { if( largest < array[loop] ) largest = array[loop]; } printf("Largest element of array is %d", largest); return 0; }
The output should look like this −
Largest element of array is 9
#include <stdio.h> int main() { int array[10] = {101, 11, 3, 4, 50, 69, 7, 8, 9, 0}; int loop, largest, second; if(array[0] > array[1]) { largest = array[0]; second = array[1]; } else { largest = array[1]; second = array[0]; } for(loop = 2; loop < 10; loop++) { if( largest < array[loop] ) { second = largest; largest = array[loop]; } else if( second < array[loop] ) { second = array[loop]; } } printf("Largest - %d \nSecond - %d \n", largest, second); return 0; }
The output should look like this −
Largest - 101 Second - 69
#include <stdio.h> int main() { int array[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0}; int loop, smallest; smallest = array[0]; for(loop = 1; loop < 10; loop++) { if( smallest > array[loop] ) smallest = array[loop]; } printf("Smallest element of array is %d", smallest); return 0; }
The output should look like this −
Smallest element of array is 0
#include <stdio.h> int main() { int array[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0}; int loop, smallest; smallest = array[0]; for(loop = 1; loop < 10; loop++) { if( smallest > array[loop] ) smallest = array[loop]; } printf("Smallest element of array is %d", smallest); return 0; }
The output should look like this −
Smallest element of array is 0
Multi Array Programs
These programs involve more than one array. This section should give you some easy techniques to handle more than one array variables in a program.
#include <stdio.h> int main() { int original[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0}; int copied[10]; int loop; for(loop = 0; loop < 10; loop++) { copied[loop] = original[loop]; } printf("original -> copied \n"); for(loop = 0; loop < 10; loop++) { printf(" %2d %2d\n", original[loop], copied[loop]); } return 0; }
The output should look like this −
original -> copied 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 0 0
#include <stdio.h> int main() { int original[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0}; int copied[10]; int loop, count; count = 9; for(loop = 0; loop < 10; loop++) { copied[count] = original[loop]; count--; } printf("original -> copied \n"); for(loop = 0; loop < 10; loop++) { printf(" %2d %2d\n", original[loop], copied[loop]); } return 0; }
The output should look like this −
original -> copied 1 0 2 9 3 8 4 7 5 6 6 5 7 4 8 3 9 2 0 1
#include <stdio.h> int main() { int array[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; int even[10], odd[10]; int loop, e, d; e = d = 0; for(loop = 0; loop < 10; loop++) { if(array[loop]%2 == 0) { even[e] = array[loop]; e++; } else { odd[d] = array[loop]; d++; } } printf(" original -> "); for(loop = 0; loop < 10; loop++) printf(" %d", array[loop]); printf("\n even -> "); for(loop = 0; loop < e; loop++) printf(" %d", even[loop]); printf("\n odd -> "); for(loop = 0; loop < d; loop++) printf(" %d", odd[loop]); return 0; }
The output should look like this −
original -> 0 1 2 3 4 5 6 7 8 9 even -> 0 2 4 6 8 odd -> 1 3 5 7 9
#include <stdio.h> int main() { int array[10]; int even[5] = {0, 2, 4, 6, 8}; int odd[5] = {1, 3, 5, 7, 9}; int loop, index, e_len, o_len; e_len = o_len = 5; index = 0; for(loop = 0; loop < e_len; loop++) { array[index] = even[loop]; index++; } for(loop = 0; loop < o_len; loop++) { array[index] = odd[loop]; index++; } printf("\nEven -> "); for(loop = 0; loop < e_len; loop++) printf(" %d", even[loop]); printf("\nOdd -> "); for(loop = 0; loop < o_len; loop++) printf(" %d", odd[loop]); printf("\nConcat -> "); for(loop = 0; loop < 10; loop++) printf(" %d", array[loop]); return 0; }
The output should look like this −
Even -> 0 2 4 6 8 Odd -> 1 3 5 7 9 Concat -> 0 2 4 6 8 1 3 5 7 9
C Multidimensional Arrays:-
In this tutorial, you will learn to work with multidimensional arrays (two-dimensional and three-dimensional arrays) with the help of examples.
In C programming, you can create an array of arrays. These arrays are known as multidimensional arrays. For example,
float x[3][4];
Here, x is a two-dimensional (2d) array. The array can hold 12 elements. You can think the array as a table with 3 rows and each row has 4 columns.
Similarly, you can declare a three-dimensional (3d) array. For example,
float y[2][4][3];
Here, the array y can hold 24 elements.
Initializing a multidimensional array
Here is how you can initialize two-dimensional and three-dimensional arrays:
Initialization of a 2d array
// Different ways to initialize two-dimensional array
int c[2][3] = {{1, 3, 0}, {-1, 5, 9}};
int c[][3] = {{1, 3, 0}, {-1, 5, 9}};
int c[2][3] = {1, 3, 0, -1, 5, 9};
Initialization of a 3d array
You can initialize a three-dimensional array in a similar way like a two-dimensional array. Here's an example,
int test[2][3][4] = {
{{3, 4, 2, 3}, {0, -3, 9, 11}, {23, 12, 23, 2}},
{{13, 4, 56, 3}, {5, 9, 3, 5}, {3, 1, 4, 9}}};
Example 1: Two-dimensional array to store and print values
// C program to store temperature of two cities of a week and display it.
#include <stdio.h>
const int CITY = 2;
const int WEEK = 7;
int main()
{
int temperature[CITY][WEEK];
// Using nested loop to store values in a 2d array
for (int i = 0; i < CITY; ++i)
{
for (int j = 0; j < WEEK; ++j)
{
printf("City %d, Day %d: ", i + 1, j + 1);
scanf("%d", &temperature[i][j]);
}
}
printf("\nDisplaying values: \n\n");
// Using nested loop to display vlues of a 2d array
for (int i = 0; i < CITY; ++i)
{
for (int j = 0; j < WEEK; ++j)
{
printf("City %d, Day %d = %d\n", i + 1, j + 1, temperature[i][j]);
}
}
return 0;
}
Output
City 1, Day 1: 33 City 1, Day 2: 34 City 1, Day 3: 35 City 1, Day 4: 33 City 1, Day 5: 32 City 1, Day 6: 31 City 1, Day 7: 30 City 2, Day 1: 23 City 2, Day 2: 22 City 2, Day 3: 21 City 2, Day 4: 24 City 2, Day 5: 22 City 2, Day 6: 25 City 2, Day 7: 26 Displaying values: City 1, Day 1 = 33 City 1, Day 2 = 34 City 1, Day 3 = 35 City 1, Day 4 = 33 City 1, Day 5 = 32 City 1, Day 6 = 31 City 1, Day 7 = 30 City 2, Day 1 = 23 City 2, Day 2 = 22 City 2, Day 3 = 21 City 2, Day 4 = 24 City 2, Day 5 = 22 City 2, Day 6 = 25 City 2, Day 7 = 26
Example 2: Sum of two matrices
// C program to find the sum of two matrices of order 2*2
#include <stdio.h>
int main()
{
float a[2][2], b[2][2], result[2][2];
// Taking input using nested for loop
printf("Enter elements of 1st matrix\n");
for (int i = 0; i < 2; ++i)
for (int j = 0; j < 2; ++j)
{
printf("Enter a%d%d: ", i + 1, j + 1);
scanf("%f", &a[i][j]);
}
// Taking input using nested for loop
printf("Enter elements of 2nd matrix\n");
for (int i = 0; i < 2; ++i)
for (int j = 0; j < 2; ++j)
{
printf("Enter b%d%d: ", i + 1, j + 1);
scanf("%f", &b[i][j]);
}
// adding corresponding elements of two arrays
for (int i = 0; i < 2; ++i)
for (int j = 0; j < 2; ++j)
{
result[i][j] = a[i][j] + b[i][j];
}
// Displaying the sum
printf("\nSum Of Matrix:");
for (int i = 0; i < 2; ++i)
for (int j = 0; j < 2; ++j)
{
printf("%.1f\t", result[i][j]);
if (j == 1)
printf("\n");
}
return 0;
}
Output
Enter elements of 1st matrix Enter a11: 2; Enter a12: 0.5; Enter a21: -1.1; Enter a22: 2; Enter elements of 2nd matrix Enter b11: 0.2; Enter b12: 0; Enter b21: 0.23; Enter b22: 23; Sum Of Matrix: 2.2 0.5 -0.9 25.0
Example 3: Three-dimensional array
// C Program to store and print 12 values entered by the user
#include <stdio.h>
int main()
{
int test[2][3][2];
printf("Enter 12 values: \n");
for (int i = 0; i < 2; ++i)
{
for (int j = 0; j < 3; ++j)
{
for (int k = 0; k < 2; ++k)
{
scanf("%d", &test[i][j][k]);
}
}
}
// Printing values with proper index.
printf("\nDisplaying values:\n");
for (int i = 0; i < 2; ++i)
{
for (int j = 0; j < 3; ++j)
{
for (int k = 0; k < 2; ++k)
{
printf("test[%d][%d][%d] = %d\n", i, j, k, test[i][j][k]);
}
}
}
return 0;
}
Output
Enter 12 values: 1 2 3 4 5 6 7 8 9 10 11 12 Displaying Values: test[0][0][0] = 1 test[0][0][1] = 2 test[0][1][0] = 3 test[0][1][1] = 4 test[0][2][0] = 5 test[0][2][1] = 6 test[1][0][0] = 7 test[1][0][1] = 8 test[1][1][0] = 9 test[1][1][1] = 10 test[1][2][0] = 11 test[1][2][1] = 12
Strings are actually one-dimensional array of characters terminated by a null character '\0'. Thus a null-terminated string contains the characters that comprise the string followed by a null.
The following declaration and initialization create a string consisting of the word "Hello". To hold the null character at the end of the array, the size of the character array containing the string is one more than the number of characters in the word "Hello."
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
If you follow the rule of array initialization then you can write the above statement as follows −
char greeting[] = "Hello";
In this section, we shall learn how to work with string C programming language. We have divided the examples in multiple sub-sections to have a better understanding of what we are doing −
Basic Programs
These programs made specially to understand the basics of strings in C. These program deals with string as an array of characters.
#include <stdio.h> int main() { char str[] = "Hello World"; printf("%s\n", str); return 0; }
Output
Output of this program should be −
Hello World
#include <stdio.h> int main() { char s1[] = "TajMahal"; int i = 0; while(s1[i] != '\0') { i++; } printf("Length of string '%s' is %d", s1, i); return 0; }
Output
Output of this program should be −
Length of string 'TajMahal' is 8
#include<stdio.h>
int main() { char s[] = "TajMahal"; // String Given char ch = 'a'; // Character to count int i = 0; int count = 0; // Counter while(s[i] != '\0') { if(s[i] == ch) count++; i++; } if(count > 0) { if(count == 1) printf("%c appears %d time in '%s'", ch, count, s); else printf("%c appears %d times in '%s'", ch, count, s); } else printf("%c did not appear in %s", ch, s); return 0; }
Output
Output of this program should be −
a appears 3 times in 'TajMahal'
#include <stdio.h> int main() { char s[] = "TajMahal"; // String Given int i = 0; int vowels = 0; // Vowels counter int consonants = 0; // Consonants counter while(s[i++] != '\0') { if(s[i] == 'a' || s[i] == 'e' || s[i] == 'i' || s[i] == 'o' || s[i] == 'u' ) vowels++; else consonants++; } printf("'%s' contains %d vowels and %d consonants.", s, vowels, consonants); return 0; }
Output
Output of this program should be −
'TajMahal' contains 3 vowels and 5 consonants.
#include <stdio.h> #include <string.h> int main (void) { char string[] = "simplyeasylearning"; char temp; int i, j; int n = strlen(string); printf("String before sorting - %s \n", string); for (i = 0; i < n-1; i++) { for (j = i+1; j < n; j++) { if (string[i] > string[j]) { temp = string[i]; string[i] = string[j]; string[j] = temp; } } } printf("String after sorting - %s \n", string); return 0; }
Output
Output of this program should be −
String before sorting - simplyeasylearning String after sorting - aaeegiillmnnprssyy
Multi-string Programs
These programs has more than one string variables. These should give you an insight of how to work with multiple string variables in C programming language −
#include <stdio.h> int main() { char s1[] = "TajMahal"; // String Given char s2[8]; // Variable to hold value int length = 0; while(s1[length] != '\0') { s2[length] = s1[length]; length++; } s2[length] = '\0'; // Terminate the string printf("Value in s1 = %s \n", s1); printf("Value in s2 = %s \n", s2); return 0; }
Output
Output of this program should be −
Value in s1 = TajMahal Value in s2 = TajMahal
2.Program to reverse string in C
#include <stdio.h> int main() { char s1[] = "TajMahal"; // String Given char s2[8]; // Variable to store reverse string int length = 0; int loop = 0; while(s1[length] != '\0') { length++; } printf("\nPrinting in reverse - "); for(loop = --length; loop>=0; loop--) printf("%c", s1[loop]); loop = 0; printf("\nStoring in reverse - "); while(length >= 0) { s2[length] = s1[loop]; length--; loop++; } s1[loop] = '\0'; // Terminates the string printf("%s\n", s2); return 0; }
Output
Output of this program should be −
Printing in reverse - lahaMjaT Storing in reverse - lahaMjaT
#include <stdio.h> #include <string.h> int main() { char s1[] = "Beauty is in the eye of the beholder"; char s2[] = "the"; int n = 0; int m = 0; int times = 0; int len = strlen(s2); // contains the length of search string while(s1[n] != '\0') { if(s1[n] == s2[m]) { // if first character of search string matches // keep on searching while(s1[n] == s2[m] && s1[n] !='\0') { n++; m++; } // if we sequence of characters matching with the length of searched string if(m == len && (s1[n] == ' ' || s1[n] == '\0')) { // BINGO!! we find our search string. times++; } } else { // if first character of search string DOES NOT match while(s1[n] != ' ') { // Skip to next word n++; if(s1[n] == '\0') break; } } n++; m=0; // reset the counter to start from first character of the search string. } if(times > 0) { printf("'%s' appears %d time(s)\n", s2, times); } else { printf("'%s' does not appear in the sentence.\n", s2); } return 0; }
Output
Output of this program should be −
'the' appears 2 time(s)
#include <stdio.h> int main() { char s1[] = "TajMahal"; char s2[] = "Dazzling"; char ch; int index = 0; //Character by Character approach printf("Before Swapping - \n"); printf("Value of s1 - %s \n", s1); printf("Value of s2 - %s \n", s2); while(s1[index] != '\0') { ch = s1[index]; s1[index] = s2[index]; s2[index] = ch; index++; } printf("After Swapping - \n"); printf("Value of s1 - %s \n", s1); printf("Value of s2 - %s \n", s2); return 0; }
Output
Output of this program should be −
Before Swapping - Value of s1 - TajMahal Value of s2 - Dazzling After Swapping - Value of s1 - Dazzling
5.Program to compare two strings in C
#include <stdio.h> int main() { char s1[] = "advise"; char s2[] = "advice"; int n = 0; unsigned short flag = 1; while (s1[n] != '\0') { if(s1[n] != s2[n]) { flag = 0; break; } n++; } if(flag == 1) { printf("%s and %s are identical\n", s1, s2); } else { printf("%s and %s are NOT identical\n", s1, s2); } return 0; }
Output
Output of this program should be −
advise and advice are NOT identical
#include <stdio.h> #include <string.h> int main() { char s1[10] = "Taj"; char s2[] = "Mahal"; int i, j, n1, n2; n1 = strlen(s1); n2 = strlen(s2); j = 0; for(i = n1; i< n1+n2; i++ ) { s1[i] = s2[j]; j++; } s1[i] = '\0'; printf("%s", s1); return 0; }
Output
Output of this program should be −
TajMahal
#include <stdio.h> #include <string.h> int main (void) { char s1[] = "recitals"; char s2[] = "articles"; char temp; int i, j; int n = strlen(s1); int n1 = strlen(s2); // If both strings are of different length, then they are not anagrams if( n != n1) { printf("%s and %s are not anagrams! \n", s1, s2); return 0; } // lets sort both strings first − for (i = 0; i < n-1; i++) { for (j = i+1; j < n; j++) { if (s1[i] > s1[j]) { temp = s1[i]; s1[i] = s1[j]; s1[j] = temp; } if (s2[i] > s2[j]) { temp = s2[i]; s2[i] = s2[j]; s2[j] = temp; } } } // Compare both strings character by character for(i = 0; i<n; i++) { if(s1[i] != s2[i]) { printf("Strings are not anagrams! \n", s1, s2); return 0; } } printf("Strings are anagrams! \n"); return 0; }
Output
Output of this program should be −
Strings are anagrams!
Long String Programs
A sentence or a line can be considered as a long string. The following programs deals with the same concept −
#include <stdio.h> #include <string.h> int string_length(char s[]) { int i = 0; while(s[i]!='\0') i++; return i; } void string_reverse(char st[]) { int i,j,len; char ch; j = len = string_length(st) - 1; i = 0; while(i < j) { ch = st[j]; st[j] = st[i]; st[i] = ch; i++; j--; } } int main (void) { char line[] = "Taj Mahal is one of the seven wonders of the world"; char reverse[100]="",temp[50]; int i,j,n; n = string_length(line); for(i = 0; i < n; i++) { for(j = 0; i < n && line[i]!=' '; ++i,++j) { temp[j] = line[i]; } temp[j] = '\0'; string_reverse(temp); strcat(reverse, temp); strcat(reverse, " "); } printf("Original - %s\n", line); printf("Reversed - %s\n",reverse); return 0; }
Output
Output of this program should be −
Original - Taj Mahal is one of the seven wonders of the world Reversed - jaT lahaM si eno fo eht neves srednow fo eht dlrow
#include <stdio.h> #include <string.h> int string_length(char s[]) { int i = 0; while(s[i]!='\0') i++; return i; } void string_reverse(char st[]) { int i,j,len; char ch; j = len = string_length(st) - 1; i = 0; while(i < j) { ch = st[j]; st[j] = st[i]; st[i] = ch; i++; j--; } } int main (void) { char line[] = "Taj Mahal is one of the seven wonders of the world"; char reverse[100] = "", temp[50]; int i, j, n; n = string_length(line); for(i = n-1; i >= 0; --i) { for(j = 0; i >= 0 && line[i] != ' '; --i,++j) temp[j] = line[i]; temp[j] = '\0'; string_reverse(temp); strcat(reverse,temp); strcat(reverse," "); } printf("Original - %s\n", line); printf("Reversed - %s\n",reverse); return 0; }
Output
Output of this program should be −
Original - Taj Mahal is one of the seven wonders of the world Reversed - world the of wonders seven the of one is Mahal Taj
A function is a group of statements that together perform a task. Every C program has at least one function, which is main(), and all the most trivial programs can define additional functions.
You can divide up your code into separate functions. How you divide up your code among different functions is up to you, but logically the division is such that each function performs a specific task.
A function declaration tells the compiler about a function's name, return type, and parameters. A function definition provides the actual body of the function.
The C standard library provides numerous built-in functions that your program can call. For example, strcat() to concatenate two strings, memcpy() to copy one memory location to another location, and many more functions.
A function can also be referred as a method or a sub-routine or a procedure, etc.
Defining a Function
The general form of a function definition in C programming language is as follows −
return_type function_name( parameter list ) { body of the function }
A function definition in C programming consists of a function header and a function body. Here are all the parts of a function −
- Return Type − A function may return a value. The return_type is the data type of the value the function returns. Some functions perform the desired operations without returning a value. In this case, the return_type is the keyword void.
- Function Name − This is the actual name of the function. The function name and the parameter list together constitute the function signature.
- Parameters − A parameter is like a placeholder. When a function is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a function. Parameters are optional; that is, a function may contain no parameters.
- Function Body − The function body contains a collection of statements that define what the function does.
Example
Given below is the source code for a function called max(). This function takes two parameters num1 and num2 and returns the maximum value between the two −
/* function returning the max between two numbers */ int max(int num1, int num2) { /* local variable declaration */ int result; if (num1 > num2) result = num1; else result = num2; return result; }
Function Declarations
A function declaration tells the compiler about a function name and how to call the function. The actual body of the function can be defined separately.
A function declaration has the following parts −
return_type function_name( parameter list );
For the above defined function max(), the function declaration is as follows −
int max(int num1, int num2);
Parameter names are not important in function declaration only their type is required, so the following is also a valid declaration −
int max(int, int);
Function declaration is required when you define a function in one source file and you call that function in another file. In such case, you should declare the function at the top of the file calling the function.
Calling a Function
While creating a C function, you give a definition of what the function has to do. To use a function, you will have to call that function to perform the defined task.
When a program calls a function, the program control is transferred to the called function. A called function performs a defined task and when its return statement is executed or when its function-ending closing brace is reached, it returns the program control back to the main program.
To call a function, you simply need to pass the required parameters along with the function name, and if the function returns a value, then you can store the returned value. For example −
#include <stdio.h> /* function declaration */ int max(int num1, int num2); int main () { /* local variable definition */ int a = 100; int b = 200; int ret; /* calling a function to get max value */ ret = max(a, b); printf( "Max value is : %d\n", ret ); return 0; } /* function returning the max between two numbers */ int max(int num1, int num2) { /* local variable declaration */ int result; if (num1 > num2) result = num1; else result = num2; return result; }
We have kept max() along with main() and compiled the source code. While running the final executable, it would produce the following result −
Max value is : 200
Function Arguments
If a function is to use arguments, it must declare variables that accept the values of the arguments. These variables are called the formal parameters of the function.
Formal parameters behave like other local variables inside the function and are created upon entry into the function and destroyed upon exit.
While calling a function, there are two ways in which arguments can be passed to a function −
Sr.No. | Call Type & Description |
---|---|
1 | Call by value
This method copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument.
|
2 | Call by reference
This method copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. This means that changes made to the parameter affect the argument.
|
By default, C uses call by value to pass arguments. In general, it means the code within a function cannot alter the arguments used to call the function.
Advanced
- Pointers
- Structures
- Function arguments by reference
- Dynamic allocation
- Arrays and Pointers
- Recursion
- Linked lists
- Binary trees
note:-Advanced topic will be updated soon
Comments
Post a Comment