C-Programming Fundamentals
C-Programming Fundamentals
C-Programming Fundamentals
Introduction to C Program:
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.
1. Mother language
2. System programming language
3. Procedure-oriented programming language
4. Structured programming language
5. Mid-level programming language
1) C as a mother language
It provides the core concepts like the array, strings, functions, file handling, etc.
that are being used in many languages like C++, Java, C#, etc.
It can't be used for internet programming like Java, .Net, PHP, etc.
3) C as a procedural language
A procedural language breaks the program into functions, data structures, etc.
In the C language, we break the program into parts using functions. It makes the
program easier to understand and modify.
You can download turbo c++ from many sites. download Turbo c++
Now, you need to create a new directory turboc inside the c: drive. Now extract
the tc3.zip file in c:\truboc directory.
Press enter, it will look inside the c:\turboc directory for the required files.
Select Start installation by the down arrow key then press enter.
In windows 7 or window 8, it will show a dialog block to ignore and close the
application because fullscreen mode is not supported. Click on Ignore button.
C programming
Thus, the structure helps us analyze the format to write a program for the least
errors. It gives better clarity and the concept of a program.
Let's start.
Sections of a C program
The sections of a C program are listed below:
1. Documentation section
2. Preprocessor section
3. Definition section
4. Global declaration
5. Main function
6. User defined functions
Documentation section
1. //name of a program
Or
1. /*
2. Overview of the code
3. .
4. */
Preprocessor section
The preprocessor section contains all the header files used in a program. It
informs the system to link the header files to the system libraries. It is given by:
1. #include<stdio.h>
2. #include<conio.h>
The #include statement includes the specific file as a part of a function at the
time of the compilation. Thus, the contents of the included file are compiled
along with the function being compiled. The #include<stdio.h> consists of the
contents of the standard input output files, which contains the definition of
stdin, stdout, and stderr. Whenever the definitions stdin, stdout, and stderr are
used in a function, the statement #include<stdio.h> need to be used.
There are various header files available for different purposes. For example, #
include <math.h>. It is used for mathematic functions in a program.
Define section
The define section comprises of different constants declared using the define
keyword. It is given by:
1. #define a = 2
Global declaration
The global section comprises of all the global declarations in the program. It is
given by:
char = 1 byte
float = 4 bytes
int = 4 bytes
We can also declare user defined functions in the global variable section.
Main function
main()
We can also use int or main with the main (). The void main() specifies that the
program will not return any value. The int main() specifies that the program can
return integer type data.int main()
Or
void main()
Local declarations
The variable that is declared inside a given function or block refers to as local
declarations.
1. main()
2. {
3. int i = 2;
4. i++;
5. }
Statements
The statements refers to if, else, while, do, for, etc. used in a program within
the main function.
Expressions
An expression is a type of formula where operands are linked with each other
by the use of operators. It is given by:
1. a - b;
2. a +b;
User defined functions
The user defined functions specified the functions specified as per the
requirements of the user. For example, color(), sum(), division(), etc.
The program (basic or advance) follows the same sections as listed above.
Return function is generally the last section of a code. But, it is not necessary
to include. It is used when we want to return a value. The return function returns
a value when the return type other than the void is specified with the function.
Return type ends the execution of the function. It further returns control to the
specified calling function. It is given by:
return;
Or
return expression ;
For example,
return 0;
Examples
It is given by:
/* Sum of the two It is the comment section. Any statement described in it is not
numbers */ considered as a code. It is a part of the description section in a code.
The comment line is optional. It can be in a separate line or part of an
executable line.
printf() The printf() prints text on the screen. It is a function for displaying
constant or variables data. Here, 'Enter two numbers to be added' is the
parameter passed to it.
scanf() It reads data from the standard input stream and writes the result into the
specified arguments.
sum = a + b The addition of the specified two numbers will be passed to the sum
parameter in the output.
return 0 A program can also run without a return 0 function. It simply states that
a program is free from error and can be successfully exited.
Here, we will discuss the method to compile and run the C program with the
help of the command prompt.
1. Create a program
2. Compile a program
3. Run or execute a program
4. Output of the program
Create a program
It refers to the code created in any text editor. We can also compile and run the
C code in any software, such as Visual studio.
Compile a program
If refers to the process of checking the errors in the code. The computer displays
all the errors (if any) found in our specified C code. We can make further
changes to correct those errors.
The next step is the run or execution part. A program is assembled and linked
without any error. The computer performs different operations, such as
decoding, ALU operations to run a program.
It is the last part of the program where the output of the specified code is
produced as the result.
But, where to write a program and how to open a command prompt to run that
program. Do not worry; it is very easy to do all these steps. Let's start with the
step to compile and run a C program.
We need first to ensure that the gcc compiler is already present on our PC or
not. If it is not installed, we need first to install the gcc compiler. We can also
try other methods to run a C program. But here, we have used the gcc compiler.
Complete all the steps during the installation till the process gets completed.
Create a C program using the simple text editor. Here, we have used notepad. It
is shown below:
1. #include<stdio.h>
2. main()
3. {
4. printf("Hello, Welcome to the C programming \n");
5. return;
6. }
Now, save the file in any directory with the extension (.c). For example, we
have saved the file with the name 'welcome.c' on the desktop.
Open the cmd or command prompt on our computer. We can simply type cmd
on the search or the run option. The Command prompt will appear.
After the command prompt opens, type 'gcc -v' and press Enter. It will appear
as the image shown below:
It shows that gcc is successfully installed on our PC.
We now need to specify the source directory on the cmd. Type 'cd space source
directory' and press Enter. Since, we have saved our text editor file on the
desktop, so we will specify the source directory as desktop. It is given by:
cd desktop
Step: 6 - compile the source code
Run the command 'gcc space full name of the file saved with the extension (.c)'
and press Enter, as shown below:
gcc welcome.c
If there is any error in our file, it will appear. Otherwise, move on to the step 7.
Step: 7 - Compile the source code
The executable file is not yet named because we have not told the compiler to
perform any such task. So, we will first name the executable file by running the
command 'gcc space -o space (name of executable file) space (name of the
original file with the extension)' and press Enter. It is given by:
Here, we have given the executable name as hello. We can define the name as
per our convenience.
It is the last step to run a program. We will run the program in the command
prompt only. Here, we will type the name of the executable file without any
extension. The executable name will be the same as specified in step 7. It is
given by:
hello
Press Enter. The output will appear on the command prompt, as shown below:
Similarly, we can run multiple C programs using the same steps, as discussed
above.
C Program
In this tutorial, all C programs are given with C compiler so that you can
quickly change the C program code.
File: main.c
1. #include <stdio.h>
2. int main() {
3. printf("Hello C Programming\n");
4. return 0;
5. }
Tokens in C:
Tokens in C is the most important element to be used in creating a program in
C. We can define the token as the smallest individual element in C. For
`example, we cannot create a sentence without using words; similarly, we
cannot create a program in C without using tokens in C. Therefore, we can say
that tokens in C is the building block or the basic component for creating
a program in C language.
Classification of tokens in C
o Keywords in C
o Identifiers in C
Keywords in C:
Keywords in C can be defined as the pre-defined or the reserved words having
its own importance, and each keyword has its own functionality. Since
keywords are the pre-defined words used by the compiler, so they cannot be
used as the variable names. If the keywords are used as the variable names, it
means that we are assigning a different meaning to the keyword, which is not
allowed. C language supports 32 keywords given below:
Auto double int Struct
Do If Static While
Identifiers in C:
Identifiers in C are used for naming variables, functions, arrays, structures, etc.
Identifiers in C are the user-defined words. It can be composed of uppercase
letters, lowercase letters, underscore, or digits, but the starting letter should be
either an underscore or an alphabet. Identifiers cannot be used as keywords.
Rules for constructing identifiers in C are given below:
float: Floa ng-point data type, used for numbers with decimal points.
float price = 19.99;
double: Double-precision floa ng-point data type, provides more precision than float.
double pi = 3.14159265359;
float: 32-bit floa ng-point.
double: 64-bit double-precision floa ng-point.
long double: Extended precision.
double price = 99.99;
Variables:
Variables are used to store and manipulate data in a program. They must be declared before
use, specifying their data type.
int main() {
int x; // Declara on
Constants:
Constants are values that do not change during the execu on of a program. They can be
defined using the const keyword.
const float PI = 3.1415;
Literals:
Literals are constant values that are used directly in the program. For example:
Integer literals: 10, 20
Floa ng-point literals: 3.14, 2.0
Character literals: 'A', 'b'
Storage Classes:
Storage classes in C determine the scope and life me of variables. The main storage classes
are:
auto: The default storage class for local variables. The variable is automa cally created and
destroyed.
register: Similar to auto, but suggests the compiler to store the variable in a register for faster
access.
sta c: The variable retains its value between func on calls. It has a file scope if declared
outside a func on.
extern: Informs the compiler that the variable is defined elsewhere. Used for global variables.
Operators:
Operators in C are symbols that perform opera ons on variables and values. They can be
categorized as:
Arithme c Operators: +, -, *, /, %
int result = 10 + 5; // result is 15
int main() {
int a = 5, b = 10;
prin ("Before Swap: a = %d, b = %d\n", a, b);
a = a + b;
b = a - b;
a = a - b;
int main() {
int num;
prin ("Enter an integer: ");
scanf("%d", &num);
if (num % 2 == 0)
prin ("%d is even.\n", num);
else
prin ("%d is odd.\n", num);
return 0;
}
int main() {
float radius, area;
prin ("Enter the radius of the circle: ");
scanf("%f", &radius);
4. Declare a constant named PI and a variable named radius. Calculate the circumference
using the formula: circumference = 2 * PI * radius.
#include <stdio.h>
int main() {
const float PI = 3.14;
float radius, circumference;
circumference = 2 * PI * radius;
5. Write a program to perform bitwise AND, OR, and XOR opera ons on two integers.
#include <stdio.h>
int main() {
int a = 12, b = 25;
int main() {
int year;
prin ("Enter a year: ");
scanf("%d", &year);
return 0;
}
int main() {
int num, sum = 0;
prin ("Enter a posi ve integer: ");
scanf("%d", &num);
int factorial(int n) {
if (n == 0 || n == 1)
return 1;
else
return n * factorial(n - 1);
}
int main() {
int num;
prin ("Enter a number: ");
scanf("%d", &num);
9. Write a program that ini alizes an array of integers and finds the sum and average of
its elements.
#include <stdio.h>
int main() {
int numbers[] = {2, 4, 6, 8, 10};
int sum = 0, size = sizeof(numbers) / sizeof(numbers[0]);
return 0;
}
10. Write a program to simulate a basic login system using logical operators.
#include <stdio.h>
int main() {
char username[] = "user123";
char password[] = "pass456";
char inputUsername[20];
char inputPassword[20];
return 0;
}
11. Write a program to find the maximum of two numbers using the condi onal (ternary)
operator.
#include <stdio.h>
int main() {
int a, b;
prin ("Enter two numbers: ");
scanf("%d %d", &a, &b);
12. Write a program to find the length of a string without using the `strlen` func on.
#include <stdio.h>
int main() {
char text[] = "Hello, World!";
prin ("Length of the string: %d\n", stringLength(text));
return 0;
}
13. Write a program to le -shi and right-shi an integer by a specified number of
posi ons.
#include <stdio.h>
int main() {
int num, shi ;
return 0;
}
14. Define a structure called `Person` with a ributes `name` and `age`. Create an array of
persons and print their details.
#include <stdio.h>
struct Person {
char name[50];
int age;
};
int main() {
struct Person people[3] = {{"Alice", 25}, {"Bob", 30}, {"Charlie", 22}};
return 0;
}
15. Create a union called `Value` that can store either an integer or a float. Write a
program to demonstrate its usage.
#include <stdio.h>
union Value {
int intValue;
float floatValue;
};
int main() {
union Value data;
data.intValue = 10;
data.floatValue = 3.14;
prin ("Float Value: %f\n", data.floatValue);
return 0;
}
Decision Making (if, if - else, else if, Switch statements)
C is consider as a structure programming language. One of the reason for this is having
various program control structures.
C process the decision making capabilities and supports the statements known as control
statements.
There are 3 types of control statements supported by C…
1. Condition control statements
2. Un condition control statements
3. Loop control statements.
Entry
False
Expr
True
Statements
Next Statements
If the expression is true, then the statement block will be executed and the statement block
will be executed and the control transfer to the next statement. Otherwise, if the expression
is false then the control directly goes to the next statement.
Example 1:
#include<stdio.h>
int main()
{
int num1=15;
int num2=29;
if(num1<num2) //test-condition
{
printf("num1 is smaller than num2");
}
return 0;
}
Output
Note:- In any control statement the statement block contains only a single statement, braces are
not necessary.
Example 2:
Write a program to find the max value of given three numbers using simple if statements.
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c,max;
clrscr();
printf("Enter any three numbers:");
scanf("%d%d%d",&a,&b,&c);
max=a;
if(max<b)
max=b;
if(max<c)
max=c;
printf("Max value:%d",max);
getch();
Example 3:
Write a program to enter any date in date format and display given date.
#include<stdio.h>
#include<conio.h>
void main()
{
int d,m,y;
clrscr();
printf("Enter any date (dd-mm-yyyy):");
scanf("%d-%d-%d",&d,&m,&y);
printf("Given date:%.2d-%.2d-%d",d,m,y);
getch();
}
The condition is false, then program control goes inside the else block and executes the
corresponding Statement.
Syntax: -
if(expression)
{
statement-1;
}
else
{
Statement-2;
}
Example 4:
#include<stdio.h>
int main()
{
int num=57;
if(num<20)
{
printf("The value is less than 20");
}
else
{
printf("The value is greater than 20");
}
return 0;
}
Output
Example 5:
getch();
Example 6:
#include <stdio.h>
int main() {
int y;
int x = 2;
y = (x >= 6) ? 6 : x;/* This is equivalent to: if (x >= 5) y = 5; else y = x; */
printf("y =%d ",y);
return 0;
}
Output :
y =2
Example 7:
Write a program to find the maximum value of given 3 no's using nested if.
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c,max;
clrscr();
scanf("%d%d%d",&a,&b,&c);
if(a>b)
{
if(a>c)
max=a;
else
max=c;
}
else
{
if(b>c)
max=b;
else
max=c;
}
printf("Max Value for given 3 numbers:%d",max);
getch();
Example 8:
#include<stdio.h>
int main()
{
int num=1;
if(num<10)
{
if(num==1)
{
printf("The value is:%d\n",num);
}
else
{
printf("The value is greater than 1");
}
}
else
{
printf("The value is greater than 10");
}
return 0;
}
Output
Example 9:
Write a program to accept any character and check whether the given character is vowel or
consonant or not an alphabet.
#include<stdio.h>
#include<conio.h>
void main()
{
char ch;
clrscr();
printf("Enter any character:");
scanf("%c",&ch);
if((ch>=65 && ch<=90) || (ch>=97 && ch<=122))
{
if(ch=='A' || ch=='a' || ch=='E'|| ch=='e' || ch=='I' || ch=='i' || ch=='O' || ch=='o' || ch=='U' ||
ch=='u')
printf("Given character is vowel");
else
printf("Given character is consonant");
}
else
printf("Given character is not an alphabet");
getch();
iv. If else if ladder:- It is also used for a serried of decisions are involved.
Syntax:-if(expression-1)
{
stataement-1;
}
else if (expression-2)
{
statements-2;
}
--------------
--------------
--------------
else if (expression-n)
{
statements-n;
}
else
{
statements;
}
In this statement expression are evaluated top to bottom. If the condition true, the statements
associated that blocks is executed and the control transfer to the next statement. When all
expressions are false, then the final else block statements will be executed.
Example 10:
Write a program to accept any character and check whether the given character is alphabet or
digit or a special character.
#include<stdio.h>
#include<conio.h>
void main()
{
char ch;
clrscr();
printf("Enter any character:");
scanf("%c",&ch);
if((ch>=65 && ch<=90) || (ch>=97 && ch<=122))
printf("Given character is alphabet");
else if(ch>=48 && ch<=57)
printf("Given character is digit");
else
printf("Given character is a special character");
getch();
}
Example 11:
#include <stdio.h>
int main()
{
int num1, num2;
printf("Enter two numbers: ");
scanf("%d %d", &num1, &num2);
//checks if the two integers are equal.
if(num1 == num2)
{
printf("Result is %d = %d",num1,num2);
}
//checks if number1 is greater than number2.
else if (num1 > num2)
{
printf("Result is %d > %d", num1, num2);
}
//checks if both conditions are false
else
{
printf("Result: %d < %d",num1, num2);
}
return 0;
}
Output 1
Output 2
Output 3
Example 12:
#include<stdio.h>
int main()
{
int temperature = 35;
if(marks>40)
{
printf("Extremely hot");
}
else if(marks>30)
{
printf("Mildly hot");
}
else if(marks>20)
{
printf("Comfortable");
}
else
{
printf("Cold");
}
return 0;
}
Output
Mildly hot
Example 13:
include<stdio.h>
int main()
{
int marks=83;
if(marks>75){
printf("First class");
}
else if(marks>65){
printf("Second class");
}
else if(marks>55){
printf("Third class");
}
else{
printf("Fourth class");
}
return 0;
}
Output:
First class
V. Switch Statement:- It is a multi way conditional statement used in c language. It is mainly
used in situations where there is need to pick one alternate among many alternates.
Syntax:-
Switch (expression or variable)
{
Case value 1;
Statement1;
Break;
----------------------
----------------------
Case value n;
Statements n;
Break;
Default;
Default statement;
}
The switch statement tests the value of the given variable or expression against a list of case
values and
when a match is found, a block of statements associated that case is executed. Otherwise the
default block
statements will be executed.
Break:- It is unconditional control statement and is used to terminate a switch statement.
Syntax :- break;
Note:- i) In switch statement the variable or expression is an integral value.(int & char).
ii) It cannot pass string and floating values.
iii) In switch statement the default block is optional.
Example 14:
Write a program to test all arithmetic operations using switch statement
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,opt;
clrscr();
printf("Enter any two numbers:");
scanf("%d%d",&a,&b);
printf("1.Addition\n2.Subtraction\n3.Multiplication\n4.Division\n5.Enter Option");
scanf("%d",&opt);
switch(opt)
{
case1 :
printf("\nAddition %d and %d is %d",a,b,a+b);
break;
case2 :
printf("\nSubtraction %d and %d is %d",a,b,a-b);
break;
case3 :
printf("\nMultiplication %d and %d is %d",a,b,a*b);
break;
case4 :
printf("\nDivision %d and %d is %d",a,b,a-b);
break;
case5 :
printf("\nModulus %d and %d is %d",a,b,a%b);
break;
default :
printf("\nInvalid Region:");
}
getch();
}
Example 15:
#include <stdio.h>
int main() {
int num = 8;
switch (num) {
case 7:
printf("Value is 7");
break;
case 8:
printf("Value is 8");
break;
case 9:
printf("Value is 9");
break;
default:
printf("Out of range");
break;
}
return 0;
}
Output
Value is 8
#include <stdio.h>
int main() {
int num = 8;
switch (num) {
case 7:
printf("Value is 7");
case 8:
printf("Value is 8");
case 9:
printf("Value is 9");
default:
printf("Out of range");
}
return 0;
}
Output
Value is 8
Value is 9
Out of range
Functions
In c, we can divide a large program into the basic building blocks known as function. The
function contains the set of programming statements enclosed by {}. A function can be called
multiple times to provide reusability and modularity to the C program. Every ‘C’ program has at
least one function which is the main function, but a program can have any number of functions.
The main () function in C is a starting point of a program.
Advantages of Functions in C
Functions in C is a highly useful feature of C with many advantages as mentioned below:
1. The function can reduce the repetition of the same statements in the program.
2. The function makes code readable by providing modularity to our program.
3. There is no fixed number of calling functions it can be called as many times as you
want.
4. The function reduces the size of the program.
5. Once the function is declared you can just use it without thinking about the internal
working of the function.
Disadvantages of Functions in C
The following are the major disadvantages of functions in C:
1. Cannot return multiple values.
2. Memory and time overhead due to stack frame allocation and transfer of program
control.
Function Types
The return_data_type: is the data type of the value function returned back to the calling
statement.
The function_name: is followed by parentheses
Arguments names with their data type declarations optionally are placed inside the parentheses.
We consider the following program that shows how to declare a cube function to calculate the
cube value of an integer variable
#include <stdio.h>
/*Function declaration*/
int add(int a,b);
/*End of Function declaration*/
Note: A function does not necessarily return a value. In this case, the keyword void is used.
For example, the output_message function declaration indicates that the function does not return
a value:
void output_message();
Function Definition
Function definition means just writing the body of a function. A body of a function consists of
statements which are going to perform a specific task. A function body consists of a single or a
block of statements. It is also a mandatory part of a function.
int add(int a,int b) //function body
{
int c;
c=a+b;
return c;
}
Function call
A function call means calling a function whenever it is required in a program. Whenever we call
a function, it performs an operation for which it was designed. A function call is an optional part
of a program.
result = add(4,5);
Function Arguments
A function’s arguments are used to receive the necessary values by the function call. They are
matched by position; the first argument is passed to the first parameter, the second to the second
parameter and so on.
By default, the arguments are passed by value in which a copy of data is given to the called
function. The actually passed variable will not change.
We consider the following program which demonstrates parameters passed by value:
int add (int x, int y);
int main() {
int a, b, result;
a = 5;
b = 10;
result = add(a, b);
printf("%d + %d\ = %d\n", a, b, result);
return 0;}
int add (int x, int y) {
x += y;
return(x);}
The program output is:
5 + 10 = 15
Note: The values of a and b were passed to add function were not changed because only its value
was passed into the parameter x.
While calling a function, there are two ways in which arguments can be passed to a function −
Sr.No. Call Type & Description
Call by value
This method copies the actual value of an argument into the formal parameter of the
1
function. In this case, changes made to the parameter inside the function have no
effect on the argument.
Call by reference
This method copies the address of an argument into the formal parameter. Inside the
2
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.
The call by value method of passing arguments to a function 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.
By default, C programming 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. Consider the function
swap() definition as follows.
#include <stdio.h>
/* function declaration */
void swap(int x, int y);
int main () {
/* local variable definition */
int a = 100;
int b = 200;
printf("Before swap, value of a : %d\n", a );
printf("Before swap, value of b : %d\n", b );
/* calling a function to swap the values */
swap(a, b);
printf("After swap, value of a : %d\n", a );
printf("After swap, value of b : %d\n", b );
return 0;
}
void swap(int x, int y) {
int temp;
temp = x; /* save the value of x */
x = y; /* put y into x */
y = temp; /* put temp into y */
return;
}
The call by reference method of passing arguments to a function 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. It means the changes made to the parameter affect the passed
argument.
To pass a value by reference, argument pointers are passed to the functions just like any other
value. So accordingly you need to declare the function parameters as pointer types as in the
following function swap(), which exchanges the values of the two integer variables pointed to,
by their arguments.
Call the function swap() by passing values by reference as in the following example −
#include <stdio.h>
int main () {
/* local variable definition */
int a = 100;
int b = 200;
printf("Before swap, value of a : %d\n", a );
printf("Before swap, value of b : %d\n", b );
/* calling a function to swap the values */
swap(&a, &b);
printf("After swap, value of a : %d\n", a );
printf("After swap, value of b : %d\n", b );
return 0;
}
void swap(int *x, int *y) {
int temp;
temp = *x; /* save the value of x */
*x = *y; /* put y into x */
*y = temp; /* put temp into y */
return;
}
Return Value
A C function may or may not return a value from the function. If you don't have to return any
value from the function, use void for the return type.
Let's see a simple example of C function that doesn't return any value from the function.
Example without return value:
void test(){
printf("hi");
}
If you want to return any value from the function, you need to use any data type such as int, long,
char, etc. The return type depends on the value to be returned from the function.
Let's see a simple example of C function that returns int value from the function.
Example with return value:
int get(){
return 10;
}
In the above example, we have to return 10 as a value, so the return type is int. If you want to
return floating-point value (e.g., 10.2, 3.1, 54.5, etc), you need to use float as the return type of
the method.
float get(){
return 10.2;
}
Function categories
There are 4 types of functions:
Recursion:
Recursion is the technique of making a function call itself. This technique provides a way to
break complicated problems down into simple problems which are easier to solve.
Example
In the following example, recursion is used to add a range of numbers together by breaking it
down into the simple task of adding two numbers:
10 + sum(9)
10 + ( 9 + sum(8) )
10 + ( 9 + ( 8 + sum(7) ) )
...
10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + sum(0)
10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + 0
Since the function does not call itself when k is 0, the program stops there and returns the result.
Scope of variables:
By scope of a variable we mean which part of the code a variable is accessible (visible) to .A
variable can have many scopes in c let’s discuss some of them .
According to Scope, variables is divided into two categories:-
1. Local Variables
2. Global Variables
Local Variable
Local variables are those variables that are defined in a small block of the program such as
function, control statement block etc. Such variables are used only by the same block.
A variable inside the function/block is a local variable. The default value of the Local variables
is ‘garbage value’.
Example :
#include<stdio.h>
int main()
{
int a,b,c; // local variables
a =10;
b = 30;
c = a + b;
printf("%d",c);
}
Here a, b, c all are local variables and can not be used by any other function except main. On
execution of the program the compiler prints 40
Global variable
As oppose to local variable a global variable is out side every function and is accessible to all the
functions and the value of a global variable can be changed by any function. Global variables are
those variable whose scope is in whole program. These variables are defined at the beginning of
the program. The default value of ‘Global Variables’ is ‘0’.
#include<stdio.h>
int d=20; // global variable
int main()
{
int a,b,c; // local variables
a = 10;
b = 30;
d = d + 10;
c = a + b + d;
printf("%d",c);
return c;
}
Exercise
Program-1
C Program to Display Prime Numbers Between Intervals Using Function
#include <stdio.h>
int checkPrimeNumber(int n);
int main() {
int n1, n2, i, flag;
printf("Enter two positive integers: ");
scanf("%d %d", &n1, &n2);
if (n1 > n2) {
n1 = n1 + n2;
n2 = n1 - n2;
n1 = n1 - n2;
}
printf("Prime numbers between %d and %d are: ", n1, n2);
for (i = n1 + 1; i < n2; ++i) {
flag = checkPrimeNumber(i);
if (flag == 1) {
printf("%d ", i);
}
}
return 0;
}
int checkPrimeNumber(int n) {
int j, flag = 1;
for (j = 2; j <= n / 2; ++j) {
if (n % j == 0) {
flag = 0;
break;
}
}
return flag;
}
Program-2
C Program to Check Prime or Armstrong Number Using User-defined Function
#include <math.h>
#include <stdio.h>
int checkPrimeNumber(int n);
int checkArmstrongNumber(int n);
int main() {
int n, flag;
printf("Enter a positive integer: ");
scanf("%d", &n);
flag = checkPrimeNumber(n);
if (flag == 1)
printf("%d is a prime number.\n", n);
else
printf("%d is not a prime number.\n", n);
flag = checkArmstrongNumber(n);
if (flag == 1)
printf("%d is an Armstrong number.", n);
else
printf("%d is not an Armstrong number.", n);
return 0;
}
int checkPrimeNumber(int n) {
int i, flag = 1, squareRoot;
squareRoot = sqrt(n);
for (i = 2; i <= squareRoot; ++i) {
if (n % i == 0) {
flag = 0;
break;
}
}
return flag;
}
int checkArmstrongNumber(int num) {
int originalNum, remainder, n = 0, flag;
double result = 0.0;
for (originalNum = num; originalNum != 0; ++n) {
originalNum /= 10;
}
for (originalNum = num; originalNum != 0; originalNum /= 10) {
remainder = originalNum % 10;
result += pow(remainder, n);
}
if (round(result) == num)
flag = 1;
else
flag = 0;
return flag;
}
Program-3
C Program to Check Whether a Number can be Expressed as Sum of Two Prime Numbers
#include <stdio.h>
int checkPrime(int n);
int main() {
int n, i, flag = 0;
printf("Enter a positive integer: ");
scanf("%d", &n);
for (i = 2; i <= n / 2; ++i) {
if (checkPrime(i) == 1) {
if (checkPrime(n - i) == 1) {
printf("%d = %d + %d\n", n, i, n - i);
flag = 1;
}
}
}
if (flag == 0)
printf("%d cannot be expressed as the sum of two prime numbers.", n);
return 0;
}
int checkPrime(int n) {
int i, isPrime = 1;
if (n == 0 || n == 1) {
isPrime = 0;
}
else {
for(i = 2; i <= n/2; ++i) {
if(n % i == 0) {
isPrime = 0;
break;
}
}
}
return isPrime;
}
Program-4
C Program to Find the Sum of Natural Numbers using Recursion
#include <stdio.h>
int addNumbers(int n);
int main() {
int num;
printf("Enter a positive integer: ");
scanf("%d", &num);
printf("Sum = %d", addNumbers(num));
return 0;
}
int addNumbers(int n) {
if (n != 0)
return n + addNumbers(n - 1);
else
return n;
}
Program-5
C Program to Find Factorial of a Number Using Recursion
#include<stdio.h>
long int multiplyNumbers(int n);
int main() {
int n;
printf("Enter a positive integer: ");
scanf("%d",&n);
printf("Factorial of %d = %ld", n, multiplyNumbers(n));
return 0;
}
long int multiplyNumbers(int n) {
if (n>=1)
return n*multiplyNumbers(n-1);
else
return 1;
}
Program-6
C Program to Find G.C.D Using Recursion
#include <stdio.h>
int hcf(int n1, int n2);
int main() {
int n1, n2;
printf("Enter two positive integers: ");
scanf("%d %d", &n1, &n2);
printf("G.C.D of %d and %d is %d.", n1, n2, hcf(n1, n2));
return 0;
}
int hcf(int n1, int n2) {
if (n2 != 0)
return hcf(n2, n1 % n2);
else
return n1;
}
Program-7
C Program to Reverse a Sentence Using Recursion
#include <stdio.h>
void reverseSentence();
int main() {
printf("Enter a sentence: ");
reverseSentence();
return 0;
}
void reverseSentence() {
char c;
scanf("%c", &c);
if (c != '\n') {
reverseSentence();
printf("%c", c);
}
}
Program-8
C program to calculate the power using recursion
#include <stdio.h>
int power(int n1, int n2);
int main() {
int base, a, result;
printf("Enter base number: ");
scanf("%d", &base);
printf("Enter power number(positive integer): ");
scanf("%d", &a);
result = power(base, a);
printf("%d^%d = %d", base, a, result);
return 0;
}
int power(int base, int a) {
if (a != 0)
return (base * power(base, a - 1));
else
return 1;
}
Program-9
C Program to Convert Binary Number to Decimal and vice-versa
#include <stdio.h>
#include <math.h>
int convert(long long);
int main() {
long long n;
printf("Enter a binary number: ");
scanf("%lld", &n);
printf("%lld in binary = %d in decimal", n, convert(n));
return 0;
}
int convert(long long n) {
int dec = 0, i = 0, rem;
while (n != 0) {
rem = n % 10;
n /= 10;
dec += rem * pow(2, i);
++i;
}
return dec;
}
Program-10
C Program to Convert Octal Number to Decimal and vice-versa
#include <stdio.h>
#include <math.h>
int convertDecimalToOctal(int decimalNumber);
int main() {
int decimalNumber;
printf("Enter a decimal number: ");
scanf("%d", &decimalNumber);
printf("%d in decimal = %d octal", decimalNumber, convertDecimalToOctal(decimalNumber));
return 0;
}
int convertDecimalToOctal(int decimalNumber) {
int octalNumber = 0, i = 1;
while (decimalNumber != 0) {
octalNumber += (decimalNumber % 8) * i;
decimalNumber /= 8;
i *= 10;
}
return octalNumber;
}
Program-11
C Program to Convert Binary Number to Octal and vice-versa
#include <math.h>
#include <stdio.h>
int convert(long long bin);
int main() {
long long bin;
printf("Enter a binary number: ");
scanf("%lld", &bin);
printf("%lld in binary = %d in octal", bin, convert(bin));
return 0;
}
int convert(long long bin) {
int oct = 0, dec = 0, i = 0;
while (bin != 0) {
dec += (bin % 10) * pow(2, i);
++i;
bin /= 10;
}
i = 1;
while (dec != 0) {
oct += (dec % 8) * i;
dec /= 8;
i *= 10;
}
return oct;
}
Program-12
Write a program in C to find the square of any number using the function.
#include <stdio.h>
double square(double num)
{
return (num * num);
}
int main()
{
int num;
double n;
printf("\n\n Function : find square of any number :\n");
printf("Input any number for square : ");
scanf("%d", &num);
n = square(num);
printf("The square of %d is : %.2f\n", num, n);
return 0;
}
Program-13
Write a program in C to check if a given number is even or odd using the function.
#include <stdio.h>
int checkOddEven(int n1)
{
return (n1 & 1);
}
int main()
{
int n1;
printf("\n\n Function : check the number is even or odd:\n");
printf("Input any number : ");
scanf("%d", &n1);
if(checkOddEven(n1))
{
printf("The entered number is odd.\n\n");
}
else
{
printf("The entered number is even.\n\n");
}
return 0;
}
Program-14
Write a program in C to get the largest element of an array using the function.
#include<stdio.h>
#define MAX 100
int findMaxElem(int []);
int n;
int main()
{
int arr1[MAX],mxelem,i;
printf("\n\n Function : get largest element of an array :\n");
printf(" Input the number of elements to be stored in the array :");
scanf("%d",&n);
printf(" Input %d elements in the array :\n",n);
for(i=0;i<n;i++)
{
printf(" element - %d : ",i);
scanf("%d",&arr1[i]);
}
mxelem=findMaxElem(arr1);
printf(" The largest element in the array is : %d\n\n",mxelem);
return 0;
}
int findMaxElem(int arr1[])
{
int i=1,mxelem;
mxelem=arr1[0];
while(i < n)
{
if(mxelem<arr1[i])
mxelem=arr1[i];
i++;
}
return mxelem;
}
Program-15
Write a program in C to find the sum of the series 1!/1+2!/2+3!/3+4!/4+5!/5 using the function.
#include <stdio.h>
int fact(int);
void main()
{
int sum;
sum=fact(1)/1+fact(2)/2+fact(3)/3+fact(4)/4+fact(5)/5;
printf("\n\n Function : find the sum of 1!/1+2!/2+3!/3+4!/4+5!/5 :\n");
printf("The sum of the series is : %d\n\n",sum);
}
int fact(int n)
{
int num=0,f=1;
while(num<=n-1)
{
f =f+f*num;
num++;
}
return f;
}
‘C’ LANGUAGE
POINTERS
Pointer:
Syntax:
<Datatype> *<ptr_variable> [= &variable];
Ex:
int a=10;
int *p = &a;
printf(“address is %u”,p);
printf(“value is %d”,*p;
Uses:
-1-
‘C’ LANGUAGE
What is indirection?
Syntax:
<datatype> *<pointer_var> [= &variable];
Ex:
int a=10;
int *p = &a;
#include<stdio.h>
int main()
{
int a=10;
int *p;
p = &a;
printf("address is %u\n",p);
printf("value is %d\n",*p);
(*p)++;
return 0;
}
Syntax:
data_type_of_pointer **name_of_variable = &
normal_pointer_variable;
Example 2:
#include<stdio.h>
int main()
{
int a=10;
int *p,**q;
p=&a;
q=&p;
printf("%d %d %d\n",*(&a),a,*p,**q);
printf("%u %u %u\n",&a,p,*q);
printf("%u %u %u",&p,q,&q);
printf("\n%d",sizeof(p));
return 0;
}
NULL Pointer:
The Null Pointer is the pointer that does not point to any
location but NULL.
Syntax of Null Pointer Declaration in C
type pointer_name = NULL;
type pointer_name = 0;
Example 3:
#include <stdio.h>
int main()
{
if (ptr == NULL)
{
printf("Pointer does not point to anything");
}
else
{
printf("Value pointed by pointer: %d", *ptr);
}
return 0;
}
void pointer:
Example 4:
#include<stdio.h>
int main(void)
{
int a=10;
float b=3.14;
void *p;
p=&a;
printf("%d\n",*(int *)p);
p=&b;
-4-
‘C’ LANGUAGE
printf("%f",*(float *)p);
return 0;
}
Syntax:
<datatype> *<ptr_var> [= array_name];
Ex:
int a[5]={1,2,3,4,5};
#include<stdio.h>
int main()
{
int a[5]={1,2,3,4,5};
int *p,i;
p=a; // p=&a[0]
for(i=0;i<5;i++)
printf("%d ",*(p+i));
return 0;
}
#include<stdio.h>
int main()
{
int a[10], i, n;
-5-
‘C’ LANGUAGE
read(a,n);
sort(a,n);
return 0;
}
printf("\n");
}
Syntax:
<datatype> *<ptr_var> [= array_name];
Ex:
int a[3][3]={{1,2,3},{4,5,6},{7,8,9}};
#include<stdio.h>
int main()
{
int a[3][3]={{1,2,3},{4,5,6},{7,8,9}};
int i, j;
Syntax:
char *ptr_var [= &str_variable];
-7-
‘C’ LANGUAGE
Ex:
Char st[]=”hello”;
char *ptr = st;
#include<stdio.h>
int main()
{
char st[80];
int len;
clrscr();
count( st );
return 0;
}
now = 1;
nos = noc = 0;
noc++;
}
-8-
‘C’ LANGUAGE
#include<stdio.h>
#include<string.h>
int main()
{
char st[10][20];
int n, i;
line(40);
printf("Before Sorting Strings are ::\n");
line(40);
print( st, n );
sort( st, n );
line(40);
printf("After sorting String are :: \n");
line(40);
print( st[0], n );
retun 0;
-9-
‘C’ LANGUAGE
Syntax:
- 10 -
‘C’ LANGUAGE
#include<stdio.h>
typedef struct
{
int sid;
char sna[20];
char course[10];
}Student;
int main()
{
Student s;
read(&s);
print(&s);
return 0;
}
- 11 -
‘C’ LANGUAGE
#include<stdio.h>
temp = *p1;
*p1 = *p2;
*p2 = temp;
}
int main()
{
int a=10, b=20;
swap(&a,&b);
return 0;
}
malloc():
Syntax:
#include<stdio.h>
#include<stdlib.h>
int n;
int main()
{
int *a;
printf("Enter array size...");
scanf("%d",&n);
a=(int *)malloc(sizeof(int)*n);
read(a);
print(a);
return 0;
}
for(i=0;i<n;i++)
printf("%d ",*(a+i));
}
calloc():
1. “calloc” or “contiguous allocation” method in C is used
to dynamically allocate the specified number of blocks of
memory of the specified type. it is very much similar to
malloc() but has two different points and these are:
Syntax :
- 13 -
‘C’ LANGUAGE
#include<stdlib.h>
#include<stdio.h>
int main(void)
{
int *a,s,n;
printf("enter the size of array: ");
scanf("%d",&n);
a=(int *)calloc(n,sizeof(int));
if(a==NULL)
{
printf("\a\a\a\aerror!!!");
exit(0);
}
printf("enter the elements in arr:");
for(int i=0;i<n;i++) scanf("%d",(a+i));
printf("enter element need to find: ");
scanf("%d",&s);
if(bs(a,s,0,n-1)) printf("element found");
else printf("element not found");
return 0;
}
#include<stdio.h>
#include<stdlib.h>
int i,j;
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
printf("%d ",*(*(a+i)+j));
printf("\n");
}
}
int main(void)
{
int **a,i,j,r,c;
printf("enter the size of matrix: ");
scanf("%d%d",&r,&c);
a=(int **)malloc(r*sizeof(int));
for(i=0;i<r;i++)
{
*(a+i)=(int *)malloc(c*sizeof(int));
}
read(a,r,c);
display(a,r,c);
return 0;
}
free():
Syntax :
free(ptr);
Example 16:
#include <stdio.h>
#include <stdlib.h>
int main()
{
free(ptr1);
printf("Calloc Memory successfully freed.\n");
}
return 0;
}
realloc():
Syntax :
Example 17:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int* ptr;
int n, i;
n = 5;
printf("Enter number of elements: %d\n", n);
if (ptr == NULL) {
- 16 -
‘C’ LANGUAGE
n = 10;
printf("\n\nEnter the new size of the array:
%d\n", n);
free(ptr);
}
return 0;
}
- 17 -