C Tutorial
C Tutorial
C Tutorial
examples
Learning C programming is easy if you follow the tutorials in the given order and
practice C programs along the way. This C tutorial is designed for beginners so
you won’t face any difficulty even if you have no prior knowledge in C language.
C Tutorial
Learn and practice these tutorials in the given order.
Loops in C
For loop – Examples, flow diagrams and use of for loop in C.
while loop – A guide on While loop usage with flow diagrams and examples.
dowhile loop – All about do-while loop along with differences between while and
dowhile.
Array Tutorials in C
Arrays – Array basics.
2D array – How to implement and use a 2D array in program.
Pointer to Array
Passing array to function – Learn passing of an array to a function as an
argument.
C – Strings
Strings and String functions – All about string and string functions. A complete
guide.
Functions in C
C functions – What’s the use of functions and how to implement them in a
program.
Function Call by value method – In the call by value method the actual
arguments are copied to the formal arguments, hence any operation performed
by function on arguments doesn’t affect actual parameters.
Function Call by Reference method – Unlike call by value, in this method,
address of actual arguments (or parameters) is passed to the formal parameters,
which means any operation performed on formal parameters affects the value of
actual parameters.
Structure
Structures in C – Complete guide for structures in C
Pointer in C Programming
C Pointers – What are pointers and how to use them.
Pointer to pointer – Tutorial on pointer to pointer (Double pointer).
Function Pointers – All about function pointers
Passing pointer to functions – Learn how to pass a pointer to a function.
File I/O
File I/O – Learn how to perform Input/Output operations on files in C. Also, get to
know the handling of text/binary files in a program.
C Examples
C examples
Next
Step 1: Locate the TC.exe file and open it. You will find it at location C:\TC\BIN\.
Step 2: File > New (as shown in above picture) and then write your C program
#include<stdio.h>
int main()
{
printf("hello World!");
return 0;
}
Step 3: Save the program using F2 (OR file > Save), remember the extension
should be “.c”. In the below screenshot I have given the name as helloworld.c.
Step 4: Compile the program using Alt + F9 OR Compile > Compile (as shown in
the below screenshot).
Step 5: Press Ctrl + F9 to Run (or select Run > Run in menu bar ) the C
program.
Step 6: Alt+F5 to view the output of the program at the output screen.
# include<stdio.h>
int main()
{
puts ("hello World");
return 0;
}
Compile it (it is basically converting a helloworld.c file to a helloworld file)
For Windows
>helloworld
For Mac and Linux OS
>./helloworld
gcc compiler took the human readable format (helloworld.c file) and converted
into a machine code for Windows, Linux and Mac OS X.
First C Program
/* Demo Program written on BeginnersBook.com*/
#include<stdio.h>
int main()
{
int num;
printf("Enter your age: ");
scanf("%d", &num);
if (num <18)
{
printf("you are not eligible for voting");
}
else
{
printf("You can do this!!");
}
return 0;
}
Output:
Include section: While writing program we use several keywords & statements
and functions such as printf(), scanf() etc. The file that has definitions of these
functions needs to be included in the program. In the above program we have
used stdio.h.There are several libraries and “stdio.h” is one of them, which is used
for reading the data from terminal and to display the data on terminal.
Display statements: printf function is used in couple of places in the above code.
Whatever you gives inside double quotes, it prints as it is at the console. You can
also use format specifiers such as %d, %c, %p to display the values of the
variables and pointers using printf.
Take input from the user: scanf function is used to take the input from the user.
When you run this program, it waits for a user input (age) and once user enters
the age, it does the processing of rest of the statements based on the age input
by user.
Main() function: It is the starting point of all the C programs. The execution of C
source code begins with this function.
Why it has a return type and what’s the need of it? The compiler should know
whether your program compiled successfully or it has failed. In order to know this
it checks the return value of function main (). If return value is 0 then it means that
the program is successful otherwise it assumes that there is a problem, this is
why we have a return 0 statement at the end of the main function.
if, else, switch, case, default – Used for decision control programming structure.
int, float, char, double, long – These are the data types and used during variable
declaration.
continue – It is generally used with for, while and dowhile loops, when compiler
encounters this statement it performs the next iteration of the loop, skipping rest
of the statements of current iteration.
volatile
C – If statement
Syntax of if statement:
The statements inside the body of “if” only execute if the given condition returns
true. If the condition returns false then the statements inside “if” are skipped.
if (condition)
{
//Block of C statements here
//These statements will only execute if the condition is true
}
Example of if statement
#include <stdio.h>
int main()
{
int x = 20;
int y = 22;
if (x<y)
{
printf("Variable x is less than y");
}
return 0;
}
#include <stdio.h>
int main()
{
int x, y;
printf("enter the value of x:");
scanf("%d", &x);
printf("enter the value of y:");
scanf("%d", &y);
if (x>y)
{
printf("x is greater than y\n");
}
if (x<y)
{
printf("x is less than y\n");
}
if (x==y)
{
printf("x is equal to y\n");
}
printf("End of Program");
return 0;
}
In the above example the output depends on the user input.
Output:
X is equal to y
C If else statement
Syntax of if else statement:
If condition returns true then the statements inside the body of “if” are executed
and the statements inside body of “else” are skipped.
If condition returns false then the statements inside the body of “if” are skipped
and the statements in “else” are executed.
if(condition) {
// Statements inside body of if
}
else {
//Statements inside body of else
}
Flow Chart of if else statement
#include <stdio.h>
int main()
{
int age;
printf("Enter your age:");
scanf("%d",&age);
if(age >=18)
{
/* This statement will only execute if the
* above condition (age>=18) returns true
*/
printf("You are eligible to do this");
}
else
{
/* This statement will only execute if the
* condition specified in the "if" returns false.
*/
printf("You are not eligible to do this");
}
return 0;
}
Output:
Note: If there is only one statement is present in the “if” or “else” body then you
do not need to use the braces (parenthesis). For example the above program
can be rewritten like this:
#include <stdio.h>
int main()
{
int age;
printf("Enter your age:");
scanf("%d",&age);
if(age >=18)
printf("You are eligible for voting");
else
printf("You are not eligible for voting");
return 0;
}
C Nested If..else statement
When an if else statement is present inside the body of another “if” or “else” then
this is called nested if else.
Syntax of Nested if else statement:
if(condition) {
//Nested if else inside the body of "if"
if(condition2) {
//Statements inside the body of nested "if"
}
else {
//Statements inside the body of nested "else"
}
}
else {
//Statements inside the body of "else"
}
Example of nested if..else
#include <stdio.h>
int main()
{
int var1, var2;
printf("Input the value of var1:");
scanf("%d", &var1);
printf("Input the value of var2:");
scanf("%d",&var2);
if (var1 != var2)
{
printf("var1 is not equal to var2\n");
//Nested if else
if (var1 > var2)
{
printf("var1 is greater than var2\n");
}
else
{
printf("var2 is greater than var1\n");
}
}
else
{
printf("var1 is equal to var2\n");
}
return 0;
}
Output:
if (condition1)
{
//These statements would execute if the condition1 is true
}
else if(condition2)
{
//These statements would execute if the condition2 is true
}
else if (condition3)
{
//These statements would execute if the condition3 is true
}
.
.
else
{
//These statements would execute if all the conditions return false.
}
Example of else..if statement
Lets take the same example that we have seen above while discussing nested
if..else. We will rewrite the same program using else..if statements.
#include <stdio.h>
int main()
{
int var1, var2;
printf("Input the value of var1:");
scanf("%d", &var1);
printf("Input the value of var2:");
scanf("%d",&var2);
if (var1 !=var2)
{
printf("var1 is not equal to var2\n");
}
else if (var1 > var2)
{
printf("var1 is greater than var2\n");
}
else if (var2 > var1)
{
printf("var2 is greater than var1\n");
}
else
{
printf("var1 is equal to var2\n");
}
return 0;
}
Output:
As you can see that only the statements inside the body of “if” are executed. This
is because in this statement as soon as a condition is satisfied, the statements
inside that block are executed and rest of the blocks are ignored.
Important Points:
1. else and else..if are optional statements, a program having only “if” statement
would run fine.
2. else and else..if cannot be used without the “if”.
3. There can be any number of else..if statement in a if else..if block.
4. If none of the conditions are met then the statements in else block gets
executed.
5. Just like relational operators, we can also use logical operators such as AND
(&&), OR(||) and NOT(!).
#include <stdio.h>
int main()
{
int num=2;
switch(num+2)
{
case 1:
printf("Case1: Value is: %d", num);
case 2:
printf("Case1: Value is: %d", num);
case 3:
printf("Case1: Value is: %d", num);
default:
printf("Default: Value is: %d", num);
}
return 0;
}
Output:
Before we discuss more about break statement, guess the output of this C
program.
#include <stdio.h>
int main()
{
int i=2;
switch (i)
{
case 1:
printf("Case1 ");
case 2:
printf("Case2 ");
case 3:
printf("Case3 ");
case 4:
printf("Case4 ");
default:
printf("Default ");
}
return 0;
}
Output:
#include <stdio.h>
int main()
{
int i=2;
switch (i)
{
case 1:
printf("Case1 ");
break;
case 2:
printf("Case2 ");
break;
case 3:
printf("Case3 ");
break;
case 4:
printf("Case4 ");
break;
default:
printf("Default ");
}
return 0;
}
Output:
Case 2
Why didn’t I use break statement after default?
The control would itself come out of the switch after default so I didn’t use it,
however if you want to use the break after default then you can use it, there is no
harm in doing that.
#include <stdio.h>
int main()
{
char ch='b';
switch (ch)
{
case 'd':
printf("CaseD ");
break;
case 'b':
printf("CaseB");
break;
case 'c':
printf("CaseC");
break;
case 'z':
printf("CaseZ ");
break;
default:
printf("Default ");
}
return 0;
}
Output:
CaseB
3) The expression provided in the switch should result in a constant value
otherwise it would not be valid.
For example:
Valid expressions for switch –
switch(1+2+23)
switch(1*2+3%4)
Invalid switch expressions –
switch(ab+cd)
switch(a+b+c)
4) Nesting of switch statements are allowed, which means you can have switch
statements inside another switch. However nested switch statements should be
avoided as it makes program more complex and less readable.
5) Duplicate case values are not allowed. For example, the following program is
incorrect:
This program is wrong because we have two case ‘A’ here which is wrong as we
cannot have duplicate case values.
#include <stdio.h>
int main()
{
char ch='B';
switch (ch)
{
case 'A':
printf("CaseA");
break;
case 'A':
printf("CaseA");
break;
case 'B':
printf("CaseB");
break;
case 'C':
printf("CaseC ");
break;
default:
printf("Default ");
}
return 0;
}
6) The default statement is optional, if you don’t have a default in the program, it
would run just fine without any issues. However it is a good practice to have a
default statement so that the default executes if no case is matched. This is
especially useful when we are taking input from user for the case choices, since
user can sometime enter wrong value, we can remind the user with a proper
error message that we can set in the default statement.
Loops in C
C For loop
This is one of the most frequently used loop in C programming.
Syntax of for loop:
1
2
3
Various forms of for loop in C
I am using variable num as the counter in all the following examples –
1) Here instead of num++, I’m using num=num+1 which is same as num++.
int num=10;
for (;num<20;num++)
Note: Even though we can skip initialization part but semicolon (;) before
condition is must, without which you will get compilation error.
3) Like initialization, you can also skip the increment part as we did below. In this
case semicolon (;) is must after condition logic. In this case the increment or
decrement part is done inside the loop.
int num=10;
for (;num<20;)
{
//Statements
num++;
}
5) As mentioned above, the counter variable can be decremented as well. In the
below example the variable gets decremented each time the loop runs until the
condition num>10 returns false.
#include <stdio.h>
int main()
{
for (int i=0; i<2; i++)
{
for (int j=0; j<4; j++)
{
printf("%d, %d\n",i ,j);
}
}
return 0;
}
Output:
0, 0
0, 1
0, 2
0, 3
1, 0
1, 1
1, 2
1, 3
In the above example we have a for loop inside another for loop, this is called
nesting of loops. One of the example where we use nested for loop is Two
dimensional array.
C – while loop
Syntax of while loop:
1 2 3 4
step1: The variable count is initialized with value 1 and then it has been tested
for the condition.
step2: If the condition returns true then the statements inside the body of while
loop are executed else control comes out of the loop.
step3: The value of count is incremented using ++ operator then it has been
tested again for the loop condition.
#include <stdio.h>
int main()
{
int var=1;
while (var <=2)
{
printf("%d ", var);
}
}
The program is an example
while(num1<=10||num2<=10)
– OR(||) operator, this loop will run until both conditions return false.
while(num1!=10 ||num2>=num1)
Example of while loop using logical operator
In this example we are testing multiple conditions using logical operator inside
while loop.
#include <stdio.h>
int main()
{
int i=1, j=1;
while (i <= 4 || j <= 3)
{
printf("%d %d\n",i, j);
i++;
j++;
}
return 0;
}
Output:
1 1
2 2
3 3
4 4
do
{
//Statements
}while(condition test);
Flow Chart of do while loop
#include <stdio.h>
int main()
{
int i=0;
while(i==1)
{
printf("while vs do-while");
}
printf("Out of loop");
}
Output:
Out of loop
Same example using do-while loop
#include <stdio.h>
int main()
{
int i=0;
do
{
printf("while vs do-while\n");
}while(i==1);
printf("Out of loop");
}
Output:
while vs do-while
Out of loop
Explanation: As I mentioned in the beginning of this guide that do-while runs at
least once even if the condition is false because the condition is evaluated, after
the execution of the body of loop.
C – Loop control statements
C – break statement
1. It is used to come out of the loop instantly. When a break statement is
encountered inside a loop, the control directly comes out of loop and the loop
gets terminated. It is used with if statement, whenever used inside loop.
2. This can also be used in switch case control structure. Whenever it is
encountered in switch-case block, the control comes out of the switch-case(see
the example below).
break;
Example – Use of break in a while loop
#include <stdio.h>
int main()
{
int num =0;
while(num<=100)
{
printf("value of variable num is: %d\n", num);
if (num==2)
{
break;
}
num++;
}
printf("Out of while-loop");
return 0;
}
Output:
var: 100
var: 99
Out of for-loop
Example – Use of break statement in switch-case
#include <stdio.h>
int main()
{
int num;
printf("Enter value of num:");
scanf("%d",&num);
switch (num)
{
case 1:
printf("You have entered value 1\n");
break;
case 2:
printf("You have entered value 2\n");
break;
case 3:
printf("You have entered value 3\n");
break;
default:
printf("Input value is other than 1,2 & 3 ");
}
return 0;
}
Output:
C – Continue statement
Syntax:
continue;
Flow diagram of continue statement
0 1 2 3 5 6 7 8
Value 4 is missing in the output, why? When the value of variable j is 4, the
program encountered a continue statement, which makes the control to jump at
the beginning of the for loop for next iteration, skipping the statements for current
iteration (that’s the reason printf didn’t execute when j is equal to 4).
#include <stdio.h>
int main()
{
int counter=10;
while (counter >=0)
{
if (counter==7)
{
counter--;
continue;
}
printf("%d ", counter);
counter--;
}
return 0;
}
Output:
10 9 8 6 5 4 3 2 1 0
The print statement is skipped when counter value was 7.
Another Example of continue in do-While loop
#include <stdio.h>
int main()
{
int j=0;
do
{
if (j==7)
{
j++;
continue;
}
printf("%d ", j);
j++;
}while(j<10);
return 0;
}
Output:
0 1 2 3 4 5 6 8 9
C – goto statement
When a goto statement is encountered in a C program, the control jumps directly
to the label mentioned in the goto stateemnt
Syntax of goto statement in C
goto label_name;
..
..
label_name: C-statements
addition:
printf("%d", sum);
return 0;
}
Output:
Explanation: In this example, we have a label addition and when the value of i
(inside loop) is equal to 5 then we are jumping to this label using goto. This is
reason the sum is displaying the sum of numbers till 5 even though the loop is
set to run from 0 to 10.
Array Tutorials in C
In general arr[n-1] can be used to access nth element of an array. where n is any
integer number.
For example:
int mydata[20];
mydata[0] /* first element of array mydata*/
mydata[19] /* last (20th) element of array mydata*/
Example of Array In C programming to find out the average
of 4 integers
#include <stdio.h>
int main()
{
int avg = 0;
int sum =0;
int x=0;
avg = sum/4;
printf("Average of entered number is: %d", avg);
return 0;
}
Output:
Enter number 1
10
Enter number 2
10
Enter number 3
20
Enter number 4
40
Average of entered number is: 20
Lets discuss the important parts of the above program:
11 22 34 44 55 66 79
#include<stdio.h>
int main(){
/* 2D array declaration*/
int disp[2][3];
/*Counter variables for the loop*/
int i, j;
for(i=0; i<2; i++) {
for(j=0;j<3;j++) {
printf("Enter value for disp[%d][%d]:", i, j);
scanf("%d", &disp[i][j]);
}
}
//Displaying array elements
printf("Two Dimensional array elements:\n");
for(i=0; i<2; i++) {
for(j=0;j<3;j++) {
printf("%d ", disp[i][j]);
if(j==2){
printf("\n");
}
}
}
return 0;
}
Output:
int disp[2][4] = { 10, 11, 12, 13, 14, 15, 16, 17};
Although both the above declarations are valid, I recommend you to use the first
method as it is more readable, because you can visualize the rows and columns
of 2d array in this method.
/* Valid declaration*/
int abc[2][2] = {1, 2, 3 ,4 }
/* Valid declaration*/
int abc[][2] = {1, 2, 3 ,4 }
/* Invalid declaration – you must specify second dimension*/
int abc[][] = {1, 2, 3 ,4 }
/* Invalid because of the same reason mentioned above*/
int abc[2][] = {1, 2, 3 ,4 }
How to store user input data into 2D array
We can calculate how many elements a two dimensional array can have by using
this formula:
The array arr[n1][n2] can have n1*n2 elements. The array that we have in the
example below is having the dimensions 5 and 4. These dimensions are known
as subscripts. So this array has first subscript value as 5 and second
subscript value as 4.
So the array abc[5][4] can have 5*4 = 20 elements.
To store the elements entered by user we are using two for loops, one of them is
a nested loop. The outer loop runs from 0 to the (first subscript -1) and the inner
for loops runs from 0 to the (second subscript -1). This way the the order in which
user enters the elements would be abc[0][0], abc[0][1], abc[0][2]…so on.
#include<stdio.h>
int main(){
/* 2D array declaration*/
int abc[5][4];
/*Counter variables for the loop*/
int i, j;
for(i=0; i<5; i++) {
for(j=0;j<4;j++) {
printf("Enter value for abc[%d][%d]:", i, j);
scanf("%d", &abc[i][j]);
}
}
return 0;
}
In above example, I have a 2D array abc of integer type. Conceptually you can
visualize the above array like this:
However the actual representation of this array in memory would be something
like this:
So abc[0] would have the address of first element of the first row (if we consider
the above diagram number 1).
similarly abc[1] would have the address of the first element of the second row. To
understand it better, lets write a C program –
#include <stdio.h>
int main()
{
int abc[5][4] ={
{0,1,2,3},
{4,5,6,7},
{8,9,10,11},
{12,13,14,15},
{16,17,18,19}
};
for (int i=0; i<=4; i++)
{
/* The correct way of displaying an address would be
* printf("%p ",abc[i]); but for the demonstration
* purpose I am displaying the address in int so that
* you can relate the output with the diagram above that
* shows how many bytes an int element uses and how they
* are stored in contiguous memory locations.
*
*/
printf("%d ",abc[i]);
}
return 0;
}
Output:
The addresses shown in the output belongs to the first element of each
row abc[0][0], abc[1][0], abc[2][0], abc[3][0] and abc[4][0].
Pointer and Array in C programming with
example
In this guide, we will learn how to work with Pointers and arrays in a C program. I
recommend you to refer Array and Pointer tutorials before going though this
guide so that it would be easy for you to understand the concept explained here.
11 22 34 44 55 66 79
In the above example I have used &val[i] to get the address of ith element of the
array. We can also use a pointer variable instead of using the ampersand (&) to
get the address.
/*Array declaration*/
int val[7] = { 11, 22, 33, 44, 55, 66, 77 } ;
p = var;
because the array name alone is equivalent to the base address of the array.
val==&val[0];
3) In the loop the increment operation(p++) is performed on the pointer variable
to get the next location (next element’s location), this arithmetic is same for all
types of arrays (for all data types double, char, int etc.) even though the bytes
consumed by each data type is different.
Pointer logic
You must have understood the logic in above code so now its time to play with
few pointer arithmetic and expressions.
#include <stdio.h>
int main( )
{
int *p;
int val[7] = { 11, 22, 33, 44, 55, 66, 77 } ;
p = val;
for ( int i = 0 ; i<7 ; i++ )
{
printf("val[%d]: value is %d and address is %p\n", i, *(p+i), (p+i));
}
return 0;
}
We don’t need the p++ statement in this program.
Passing array to function in C programming
with example
Just like variables, array can also be passed to a function as an argument . In
this guide, we will learn how to pass the array to a function using call by value
and call by reference methods.
1. C – Array
2. Function call by value in C
3. Function call by reference in C
#include <stdio.h>
void disp( char ch)
{
printf("%c ", ch);
}
int main()
{
char arr[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'};
for (int x=0; x<10; x++)
{
/* I’m passing each element one by one using subscript*/
disp (arr[x]);
}
return 0;
}
a b c d e f g h i j
Passing array to function using call by reference
When we pass the address of an array while calling a function then this is called
function call by reference. When we pass an address as an argument, the
function declaration should have a pointer as a parameter to receive the passed
address.
#include <stdio.h>
void disp( int *num)
{
printf("%d ", *num);
}
int main()
{
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
for (int i=0; i<10; i++)
{
/* Passing addresses of array elements*/
disp (&arr[i]);
}
return 0;
}
Output:
1 2 3 4 5 6 7 8 9 0
How to pass an entire array to a function as an argument?
In the above example, we have passed the address of each array element one
by one using a for loop in C. However you can also pass an entire array to a
function like this:
Note: The array name itself is the address of first element of that array. For
example if array name is arr then you can say that arr is equivalent to
the &arr[0].
#include <stdio.h>
void myfuncn( int *var1, int var2)
{
/* The pointer var1 is pointing to the first element of
* the array and the var2 is the size of the array. In the
* loop we are incrementing pointer so that it points to
* the next element of the array on each increment.
*
*/
for(int x=0; x<var2; x++)
{
printf("Value of var_arr[%d] is: %d \n", x, *var1);
/*increment pointer for next element fetch*/
var1++;
}
}
int main()
{
int var_arr[] = {11, 22, 33, 44, 55, 66, 77};
myfuncn(var_arr, 7);
return 0;
}
Output:
C – Strings
We will see how to compare two strings, concatenate strings, copy one string to
another & perform various string manipulation operations. We can perform such
operations using the pre-defined functions of “string.h” header file. In order to use
these string functions you must include string.h file in your C program.
String Declaration
Method 1:
/*Displaying String*/
printf("%s",nickname);
return 0;
}
Output:
Enter your Nick name:Negan
Negan
Note: %s format specifier is used for strings input/output
puts(nickname);
return 0;
}
C – String functions
C String function – strlen
Syntax:
Example of strlen:
#include <stdio.h>
#include <string.h>
int main()
{
char str1[20] = "BeginnersBook";
printf("Length of string str1: %d", strlen(str1));
return 0;
}
Output:
Example of strnlen:
#include <stdio.h>
#include <string.h>
int main()
{
char str1[20] = "BeginnersBook";
printf("Length of string str1 when maxlen is 30: %d", strnlen(str1, 30));
printf("Length of string str1 when maxlen is 10: %d", strnlen(str1, 10));
return 0;
}
Output:
Length of string str1 when maxlen is 30: 13
Length of string str1 when maxlen is 10: 10
Have you noticed the output of second printf statement, even though the string
length was 13 it returned only 10 because the maxlen was 10.
C String function – strcmp
int strcmp(const char *str1, const char *str2)
It compares the two strings and returns an integer value. If both the strings are
same (equal) then this function would return 0 otherwise it may return a negative
or positive value based on the comparison.
Example of strcmp:
#include <stdio.h>
#include <string.h>
int main()
{
char s1[20] = "BeginnersBook";
char s2[20] = "BeginnersBook.COM";
if (strcmp(s1, s2) ==0)
{
printf("string 1 and string 2 are equal");
}else
{
printf("string 1 and 2 are different");
}
return 0;
}
Output:
Example of strncmp:
#include <stdio.h>
#include <string.h>
int main()
{
char s1[20] = "BeginnersBook";
char s2[20] = "BeginnersBook.COM";
/* below it is comparing first 8 characters of s1 and s2*/
if (strncmp(s1, s2, 8) ==0)
{
printf("string 1 and string 2 are equal");
}else
{
printf("string 1 and 2 are different");
}
return 0;
}
Output:
Example of strcat:
#include <stdio.h>
#include <string.h>
int main()
{
char s1[10] = "Hello";
char s2[10] = "World";
strcat(s1,s2);
printf("Output string after concatenation: %s", s1);
return 0;
}
Output:
Example of strncat:
#include <stdio.h>
#include <string.h>
int main()
{
char s1[10] = "Hello";
char s2[10] = "World";
strncat(s1,s2, 3);
printf("Concatenation using strncat: %s", s1);
return 0;
}
Output:
Example of strcpy:
#include <stdio.h>
#include <string.h>
int main()
{
char s1[30] = "string 1";
char s2[30] = "string 2 : I’m gonna copied into s1";
/* this function has copied s2 into s1*/
strcpy(s1,s2);
printf("String s1 is: %s", s1);
return 0;
}
Output:
Example of strncpy:
#include <stdio.h>
#include <string.h>
int main()
{
char first[30] = "string 1";
char second[30] = "string 2: I’m using strncpy now";
/* this function has copied first 10 chars of s2 into s1*/
strncpy(s1,s2, 12);
printf("String s1 is: %s", s1);
return 0;
}
Output:
Example of strchr:
#include <stdio.h>
#include <string.h>
int main()
{
char mystr[30] = "I’m an example of function strchr";
printf ("%s", strchr(mystr, 'f'));
return 0;
}
Output:
f function strchr
C String function – Strrchr
char *strrchr(char *str, int ch)
It is similar to the function strchr, the only difference is that it searches the string
in reverse order, now you would have understood why we have extra r in strrchr,
yes you guessed it correct, it is for reverse only.
#include <stdio.h>
#include <string.h>
int main()
{
char mystr[30] = "I’m an example of function strchr";
printf ("%s", strrchr(mystr, 'f'));
return 0;
}
Output:
function strchr
Why output is different than strchr? It is because it started searching from the
end of the string and found the first ‘f’ in function instead of ‘of’.
Example of strstr:
#include <stdio.h>
#include <string.h>
int main()
{
char inputstr[70] = "String Function in C at BeginnersBook.COM";
printf ("Output string is: %s", strstr(inputstr, 'Begi'));
return 0;
}
Output:
give
Note that there is a difference of 4 bytes between each element because that’s
the size of an integer. Which means all the elements are stored in consecutive
contiguous memory locations in the memory.(See the diagram below)
Functions in C
a) Use the same set of statements every time you want to perform the task
b) Create a function to perform that task, and just call it every time you need to
perform that task.
Using option (b) is a good practice and a good programmer always uses
functions while writing codes in C.
Types of functions
1) Predefined standard library functions – such as puts(), gets(), printf(), scanf() etc
– These are the functions which already have a definition in header files (.h files
like stdio.h), so we just call them whenever there is a need to use them.
User Defined functions – The functions that we create in a program are known as
user defined functions.
In this guide, we will learn how to create user defined functions and how to use
them in C Programming
argument list: Argument list contains variables names along with their data
types. These arguments are kind of inputs for the function. For example – A
function which is used to add two integer variables, will be having two integer
argument.
Block of code: Set of C statements, which will be executed whenever a call will
be made to the function.
Do you find above terms confusing? – Do not worry I’m not gonna end this
guide until you learn all of them :)
Lets take an example – Suppose you want to create a function to add two integer
variables.
int main()
{
int var1, var2;
printf("Enter number 1: ");
scanf("%d",&var1);
printf("Enter number 2: ");
scanf("%d",&var2);
return 0;
}
Output:
int main()
{
/*calling function*/
introduction();
return 0;
}
Output:
Hi
My name is Chaitanya
How are you?
Few Points to Note regarding functions in C:
1) main() in C program is also a function.
2) Each C program must have at least one function, which is main().
3) There is no limit on number of functions; A C program can have any number of
functions.
4) A function can call itself and it is known as “Recursion“. I have written a
separate guide for it.
Note: for example, if function return type is char, then function should return a
value of char type and while calling this function the main() function should have
a variable of char data type to store the returned value.
int main()
{
…
char c1 = abc('a', 'x');
…
}
For example:
#include <stdio.h>
int sum(int a, int b)
{
int c=a+b;
return c;
}
int main(
{
int var1 =10;
int var2 = 20;
int var3 = sum(var1, var2);
printf("%d", var3);
return 0;
}
In the above example variable a and b are the formal parameters (or formal
arguments). Variable var1 and var2 are the actual arguments (or actual
parameters). The actual parameters can also be the values. Like sum(13, 22),
here 13 and 22 are actual parameters.
In this guide, we will discuss function call by value. If you want to read call by
reference method then refer this guide: function call by reference.
#include <stdio.h>
int increment(int var)
{
var = var+1;
return var;
}
int main()
{
int num1=20;
int num2 = increment(num1);
printf("num1 value is: %d", num1);
printf("\nnum2 value is: %d", num2);
return 0;
}
Output:
Num 1 value is 22
Num 2 value is 27
Explanation
We passed the variable num1 while calling the method, but since we are calling
the function using call by value method, only the value of num1 is copied to the
formal parameter var. Thus change made to the var doesn’t reflect in the num1.
}
int main( )
{
int num1 = 35, num2 = 45 ;
printf("Before swapping: %d, %d", num1, num2);
#include <stdio.h>
void increment(int *var)
{
/* Although we are performing the increment on variable
* var, however the var is a pointer that holds the address
* of variable num, which means the increment is actually done
* on the address where value of num is stored.
*/
*var = *var+1;
}
int main()
{
int num=20;
/* This way of calling the function is known as call by
* reference. Instead of passing the variable num, we are
* passing the address of variable num
*/
increment(&num);
printf("Value of num is: %d", num);
return 0;
output:
#include
void swapnum ( int *var1, int *var2 )
{
int tempnum ;
tempnum = *var1 ;
*var1 = *var2 ;
*var2 = tempnum ;
}
int main( )
{
int num1 = 35, num2 = 45 ;
printf("Before swapping:");
printf("\nnum1 value is %d", num1);
printf("\nnum2 value is %d", num2);
printf("\nAfter swapping:");
printf("\nnum1 value is %d", num1);
printf("\nnum2 value is %d", num2);
return 0;
}
Output:
Before swapping:
num1 value is 39
num2 value is 47
After swapping:
num1 value is 47
num2 value is 39
Structure
Lets say we need to store the data of students like student name, age, address,
id etc. One way of doing this would be creating a different variable for each
attribute, however when you need to store the data of multiple students then in
that case, you would need to create these several variables again for each
student. This is such a big headache to store data in this way.
We can solve this problem easily by using structure. We can create a structure
that has members for name, id, address and age and then we can create the
variables of this structure for each student. This may sound confusing, do not
worry we will understand this with the help of example.
struct struct_name {
DataType member1_name;
DataType member2_name;
DataType member3_name;
…
};
Here struct_name can be anything of your choice. Members data type can be
same or different. Once we have declared the structure we can use the struct
name as a data type like int, float etc.
First we will see the syntax of creating struct variable, accessing struct members
etc and then we will see a complete example.
struct struct_name {
DataType member1_name;
DataType member2_name;
DataType member3_name;
…
} var_name;
How to access data members of a structure using a struct
variable?
var_name.member1_name;
var_name.member2_name;
…
How to assign values to structure members?
There are three ways to do this.
1) Using Dot(.) operator
var_name.memeber_name = value;
2) All members assigned in one statement
Example of Structure in C
#include <stdio.h>
/* Created a structure here. The name of the structure is
* StudentData.
*/
struct StudentData{
char *stu_name;
int stu_id;
int stu_age;
};
int main()
{
/* student is the variable of structure StudentData*/
struct StudentData student;
struct stu_address
{
int street;
char *state;
char *city;
char *country;
}
Structure 2: stu_data
struct stu_data
{
int stu_id;
int stu_age;
char *stu_name;
struct stu_address stuAddress;
}
As you can see here that I have nested a structure inside another structure.
printf("%s", mydata.stuAddress.city);
Use of typedef in Structure
typedef makes the code short and improves readability. In the above discussion
we have seen that while using structs every time we have to use the lengthy
syntax, which makes the code confusing, lengthy, complex and less readable.
The simple solution to this issue is use of typedef. It is like an alias of struct.
struct home_address {
int local_street;
char *town;
char *my_city;
char *my_country;
};
...
struct home_address var;
var.town = "Agra";
Code using tyepdef
Pointer in C Programming
So let’s say the address assigned to variable num is 0x7fff5694dc58, which means
whatever value we would be assigning to num should be stored at the
location: 0x7fff5694dc58. See the diagram below.
#include <stdio.h>
int main()
{
int num = 10;
printf("Value of variable num is: %d", num);
/* To print the address of a variable we use %p
* format specifier and ampersand (&) sign just
* before the variable name like &num.
*/
printf("\nAddress of variable num is: %p", &num);
return 0;
}
Output:
Parameter name-num
Value of num-13
Address of num-0*7fff5794dt57
Example of Pointers in C
This program shows how a pointer is declared and used. There are several other
things that we can do with pointers, we have discussed them later in this guide.
For now, we just need to know how to link a pointer to the address of a variable.
Important point to note is: The data type of pointer and the variable must
match, an int pointer can hold the address of int variable, similarly a pointer
declared with float data type can hold the address of a float variable. In the
example below, the pointer and the variable both are of int type.
#include <stdio.h>
int main()
{
//Variable declaration
int num = 10;
//Pointer declaration
int *p;
Pointer is just like another variable, the main difference is that it stores
address of another variable rather than a value.
double a = 10;
double *p;
p = &a;
*p would give us the value of the variable a. The following statement would
display 10 as output.
printf("%d", *p);
Similarly if we assign a value to *pointer like this:
*p = 200;
It would change the value of variable a. The statement above will change the
value of a from 10 to 200.
C-pointers
Int var=13;
Int*p;
P=&var;
0*8fff5ed98c9c Val 13
0*8fff5ed98c9c
0*8fff5ed98c83
char ch='a';
char *ptr;
Read the value of ch
ch = 'b';
or
*ptr = 'b';
The above code would replace the value ‘a’ with ‘b’.
#include <stdio.h>
int main()
{
int var =10;
int *p;
p= &var;
return 0;
}
Output:
java