0% found this document useful (0 votes)
187 views

Basics of C Simplified

C was initially used for system development work due to its ability to generate fast code like assembly language. It is commonly used to write operating systems, compilers, and other system tools. A basic C program structure includes preprocessor commands, functions, variables, statements, expressions, and comments. To compile and run a C program, it must be saved as a file with a .c extension, then compiled using a compiler like gcc and executed.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
187 views

Basics of C Simplified

C was initially used for system development work due to its ability to generate fast code like assembly language. It is commonly used to write operating systems, compilers, and other system tools. A basic C program structure includes preprocessor commands, functions, variables, statements, expressions, and comments. To compile and run a C program, it must be saved as a file with a .c extension, then compiled using a compiler like gcc and executed.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 106

C programming

Overview
C was initially used for system development work, particularly the
programs that make-up the operating system. C was adopted as a
system development language because it produces code that runs
nearly as fast as the code written in assembly language. Some
examples of the use of C might be
• Operating Systems
• Language Compilers
• Assemblers
• Text Editors
• Print Spoolers
• Network Drivers
• Modern Programs
• Databases
• Language Interpreters
• Utilities
A C program can vary from 3 lines to millions of lines and it should be
written into one or more text files with extension ".c"; for example,
hello.c. You can use "vi", "vim" or any other text editor to write your C
program into a file.
structure
Lets begin by looking at the simple structure of C
A C program basically consists of the following parts −
• Preprocessor Commands
• Functions
• Variables
• Statements & Expressions
• Comments

#include <stdio.h>

int main() {
/* my first program in C */
printf("Hello, World! \n");

return 0;
}
Lets consider the various past of the previous slide
1. The first line of the program #include <stdio.h> is a preprocessor command,
which tells a C compiler to include stdio.h file before going to actual
compilation.
2. The next line int main() is the main function where the program execution
begins.
3. The next line /*...*/ will be ignored by the compiler and it has been put to add
additional comments in the program. So such lines are called comments in the
program.
4. The next line printf(...) is another function available in C which causes the
message "Hello, World!" to be displayed on the screen.
5. The next line return 0; terminates the main() function and returns the value 0.
Compile and Execute C Program
Let us see how to save the source code in a file, and how to compile and run it.
Following are the simple steps
• Open a text editor and add the above-mentioned code.
• Save the file as hello.c
• Open a command prompt and go to the directory where you have saved the file.
• Type gcc hello.c and press enter to compile your code.
• If there are no errors in your code, the command prompt will take you to the next line and
would generate a.out executable file.
• Now, type a.out to execute your program.
• You will see the output "Hello World" printed on the screen.
Basic syntax
Since you have seen the basic structure of a C program, so it will be easy to
understand other basic building blocks of the C programming language.
Tokens in C
A C program consists of various tokens and a token is either a keyword, an
identifier, a constant, a string literal, or a symbol. For example, the following
C statement consists of five tokens
printf
(
"Hello, World! \n"
)
;
Semicolons
In a C program, the semicolon is a statement terminator. That is, each
individual statement must be ended with a semicolon. It indicates the
end of one logical entity.
Comments
Comments are like helping text in your C program and they are ignored
by the compiler. They start with /* and terminate with the characters
*/ as shown below −
/* my first program in C */
Identifiers
A C identifier is a name used to identify a variable, function, or any
other user-defined item. An identifier starts with a letter A to Z, a to z,
or an underscore '_' followed by zero or more letters, underscores, and
digits (0 to 9).
C does not allow punctuation characters such as @, $, and % within
identifiers. C is a case-sensitive programming language. Thus,
Manpower and manpower are two different identifiers in C.
keywords
auto else long switch

break enum register typedef

case extern return union

char float short unsigned

const for signed void

continue goto sizeof volatile

default if static while

do int struct _Packed

double
Variables

In programming, a variable is a container (storage area) to hold data.


To indicate the storage area, each variable should be given a unique
name (identifier). Variable names are just the symbolic representation
of a memory location. Example..
int playerScore = 95;
Rules for naming a variable in C
1. A variable name can have letters (both uppercase and lowercase
letters), digits and underscore only.
2. The first character of a variable should be either a letter or an
underscore. However, it is discouraged to start variable name with
an underscore. It is because variable name that starts with an
underscore can conflict with system name and may cause error.
3. There is no rule on how long a variable can be. However, only the
first 31 characters of a variable are checked by the compiler. So, the
first 31 letters of two variables in a program should be different.
Constants/Literals

A constant is a value or an identifier whose value cannot be altered in a


program. Example const double PI = 3.14
Here, PI is a constant.
Integer constants
An integer constant is a numeric constant (associated with number)
without any fractional or exponential part. There are three types of
integer constants in C programming:
• decimal constant(base 10)
• octal constant(base 8)
• hexadecimal constant(base 16)
Floating-point constants
A floating point constant is a numeric constant that has either a
fractional form or an exponent form
Character constants
A character constant is a constant which uses single quotation around
characters. For example: 'a', 'l', 'm', 'F‘
Escape Sequences
Sometimes, it is necessary to use characters which cannot be typed or
has special meaning in C programming. For example: newline(enter),
tab, question mark etc. In order to use these characters, escape
sequence is used.
For example: \n is used for newline. The backslash ( \ ) causes "escape"
from the normal way the characters are interpreted by the compiler.
Escape Sequences
Escape Sequences Character

\b Backspace

\f Form feed

\n Newline

\r Return

\t Horizontal tab

\v Vertical tab

\\ Backslash

\' Single quotation mark

\" Double quotation mark

\? Question mark

\0 Null character
String constants
String constants are the constants which are enclosed in a pair of
double-quote marks. For example:
"good" //string constant
"" //null string constant
" " //string constant of six white space
"x" //string constant having single character.
"Earth is round\n" //prints string with newline
Enumeration constants
Keyword enum is used to define enumeration types
enum color {yellow, green, black, white};
Here, color is a variable and yellow, green, black and white are the
enumeration constants having value 0, 1, 2 and 3 respectively.
Data types
Data types simply refers to the type and size of data associated with
variables and functions.
Data types in C
• Fundamental Data Types
• Integer types
• Floating type
• Character type
• Derived Data Types
• Arrays
• Pointers
• Structures
• Enumeration
Difference between float and double
The size of float (single precision float data type) is 4 bytes. And the size
of double (double precision float data type) is 8 bytes. Floating point
variables has a precision of 6 digits whereas the precision of double is
14 digits.
Character types
Keyword char is used for declaring character type variables. For
example: char test = 'h';
Sign qualifiers
Integers and floating point variables can hold both negative and
positive values. However, if a variable needs to hold positive value only,
unsigned data types are used.
// unsigned variables cannot hold negative value
unsigned int positiveInteger;
Signed variables hold both positive and negative. However it is not
necessary to declare a variable signed since its by default.
Constant qualifiers
An identifier can be declared as a constant. To do so const keyword is
used. Example const int cost = 20;
The value of cost cannot be changed in the program.
Operators
An operator is a symbol which operates on a value or a variable.
C programming has wide range of operators to perform various
operations. For better understanding of operators, these operators can
be classified as:
Arithmetic Operators

Increment and Decrement Operators

Assignment Operators

Relational Operators

Logical Operators

Conditional Operators

Bitwise Operators

Special Operators
Arithmetic Operators
An arithmetic operator performs mathematical operations such as
addition, subtraction and multiplication on numerical values (constants
and variables).
Operator Meaning of Operator

+ addition or unary plus

- subtraction or unary minus

* multiplication

/ division

remainder after division( modulo


%
division)
example
// C Program to demonstrate the working of arithmetic operators
#include <stdio.h>
int main()
{
int a = 9,b = 4, c;
c = a+b;
printf("a+b = %d \n",c);
c = a-b;
printf("a-b = %d \n",c);
c = a*b;
printf("a*b = %d \n",c);
c=a/b;
printf("a/b = %d \n",c);
c=a%b;
printf("Remainder when a divided by b = %d \n",c);
return 0;
}
Increment and decrement operators
C programming has two operators increment ++ and decrement -- to change the value of
an operand (constant or variable) by 1.
Increment ++ increases the value by 1 whereas decrement -- decreases the value by 1.
These two operators are unary operators, meaning they only operate on a single operand.

// C Program to demonstrate the working of increment and decrement operators


#include <stdio.h>
int main()
{
int a = 10, b = 100;
float c = 10.5, d = 100.5;
printf("++a = %d \n", ++a);
printf("--b = %d \n", --b);
printf("++c = %f \n", ++c);
printf("--d = %f \n", --d);
return 0;
}
Assignment Operators
An assignment operator is used for assigning a value to a variable. The
most common assignment operator is =

Operator Example Same as

= a=b a=b

+= a += b a = a+b

-= a -= b a = a-b

*= a *= b a = a*b

/= a /= b a = a/b

%= a %= b a = a%b
example
// C Program to demonstrate the working of assignment operators
#include <stdio.h>
int main()
{
int a = 5, c;
c = a;
printf("c = %d \n", c);
c += a; // c = c+a
printf("c = %d \n", c);
c -= a; // c = c-a
printf("c = %d \n", c);
c *= a; // c = c*a
printf("c = %d \n", c);
c /= a; // c = c/a
printf("c = %d \n", c);
c %= a; // c = c%a
printf("c = %d \n", c);
return 0;
}
Relational Operators
A relational operator checks the relationship between two operands. If
the relation is true, it returns 1; if the relation is false, it returns value 0.
Relational operators are used in decision making and loops.

Operator Meaning of Operator Example

== Equal to 5 == 3 returns 0

> Greater than 5 > 3 returns 1

< Less than 5 < 3 returns 0

!= Not equal to 5 != 3 returns 1

>= Greater than or equal to 5 >= 3 returns 1

<= Less than or equal to 5 <= 3 return 0


// C Program to demonstrate the working of arithmetic operators
#include <stdio.h>
int main()
{
int a = 5, b = 5, c = 10;
printf("%d == %d = %d \n", a, b, a == b); // true
printf("%d == %d = %d \n", a, c, a == c); // false
printf("%d > %d = %d \n", a, b, a > b); //false
printf("%d > %d = %d \n", a, c, a > c); //false
printf("%d < %d = %d \n", a, b, a < b); //false
printf("%d < %d = %d \n", a, c, a < c); //true
printf("%d != %d = %d \n", a, b, a != b); //false
printf("%d != %d = %d \n", a, c, a != c); //true
printf("%d >= %d = %d \n", a, b, a >= b); //true
printf("%d >= %d = %d \n", a, c, a >= c); //false
printf("%d <= %d = %d \n", a, b, a <= b); //true
printf("%d <= %d = %d \n", a, c, a <= c); //true
return 0;
}
Logical Operators
An expression containing logical operator returns either 0 or 1
depending upon whether expression results true or false. Logical
operators are commonly used in decision making in C programming.

Operator Meaning of Operator Example

Logial AND. True only if all operands If c = 5 and d = 2 then, expression ((c
&&
are true == 5) && (d > 5)) equals to 0.

Logical OR. True only if either one If c = 5 and d = 2 then, expression ((c
||
operand is true == 5) || (d > 5)) equals to 1.

Logical NOT. True only if the operand If c = 5 then, expression ! (c == 5)


!
is 0 equals to 0.
// C Program to demonstrate the working of logical operators
#include <stdio.h>
int main()
{
int a = 5, b = 5, c = 10, result;
result = (a == b) && (c > b);
printf("(a == b) && (c > b) equals to %d \n", result);
result = (a == b) && (c < b);
printf("(a == b) && (c < b) equals to %d \n", result);
result = (a == b) || (c < b);
printf("(a == b) || (c < b) equals to %d \n", result);
result = (a != b) || (c < b);
printf("(a != b) || (c < b) equals to %d \n", result);
result = !(a != b);
printf("!(a == b) equals to %d \n", result);
result = !(a == b);
printf("!(a == b) equals to %d \n", result);
return 0;
}
Bitwise Operators
During computation, mathematical operations like: addition,
subtraction, addition and division are converted to bit-level which
makes processing faster and saves power

Operators Meaning of operators

& Bitwise AND

| Bitwise OR

^ Bitwise exclusive OR

~ Bitwise complement

<< Shift left

>> Shift right


Ternary Operator (?:)
A conditional operator is a ternary operator, that is, it works on 3
operands.
conditionalExpression ? expression1 : expression2
The conditional operator works as follows:
• The first expression conditionalExpression is evaluated first. This expression
evaluates to 1 if it's true and evaluates to 0 if it's false.
• If conditionalExpression is true, expression1 is evaluated.
• If conditionalExpression is false, expression2 is evaluated.
example
#include <stdio.h>
int main(){
char February;
int days;
printf("If this year is leap year, enter 1. If not enter any integer: ");
scanf("%c",&February);
// If test condition (February == 'l') is true, days equal to 29.
// If test condition (February =='l') is false, days equal to 28.
days = (February == '1') ? 29 : 28;
printf("Number of days in February = %d",days);
return 0;
}
Decision Making Construct
Decision making is used to specify the order in which statements are
executed. Decision making structures require that the programmer
specifies one or more conditions to be evaluated or tested by the
program, along with a statement or statements to be executed if the
condition is determined to be true, and optionally, other statements to
be executed if the condition is determined to be false. There are three
types of decision making:
• Simple if
• If….else
• Nested if….else
Simple if statement
if (testExpression)
{
// statements
}
The if statement evaluates the test expression inside the parenthesis.
If the test expression is evaluated to true (nonzero), statements inside
the body of if is executed.
If the test expression is evaluated to false (0), statements inside the
body of if is skipped from execution.
example
// Program to display a number if user enters negative number
// If user enters positive number, that number won't be displayed

#include <stdio.h>
int main()
{
int number;
printf("Enter an integer: ");
scanf("%d", &number);

// Test expression is true if number is less than 0


if (number < 0)
{
printf("You entered %d.\n", number);
}
printf("The if statement is easy.");
return 0;
}
If…else
The if...else statement executes some code if the test expression is true
(nonzero) and some other code if the test expression is false (0)
if (testExpression) {
// codes inside the body of if
}
else {
// codes inside the body of else
}
If test expression is true, codes inside the body of if statement is
executed and, codes inside the body of else statement is skipped.

If test expression is false, codes inside the body of else statement is


executed and, codes inside the body of if statement is skipped.
example
// Program to check whether an integer entered by the user is odd or even

#include <stdio.h>
int main()
{
int number;
printf("Enter an integer: ");
scanf("%d",&number);
// True if remainder is 0
if( number%2 == 0 )
printf("%d is an even integer.",number);
else
printf("%d is an odd integer.",number);
return 0;
}
Nested If…Else
The if...else statement executes two different codes depending upon
whether the test expression is true or false. Sometimes, a choice has to
be made from more than 2 possibilities.
The nested if...else statement allows you to check for multiple test
expressions and execute different codes for more than two conditions.
if (testExpression1)
{
// statements to be executed if testExpression1 is true
}
else if(testExpression2)
{
// statements to be executed if testExpression1 is false and testExpression2 is true
}
else if (testExpression 3)
{
// statements to be executed if testExpression1 and testExpression2 is false and testExpression3 is true
}
.
.
else
{
// statements to be executed if all test expressions are false
}
example
// Program to relate two integers using =, > or <

#include <stdio.h>
int main()
{
int number1, number2;
printf("Enter two integers: ");
scanf("%d %d", &number1, &number2);

//checks if two integers are equal.


if(number1 == number2)
{
printf("Result: %d = %d",number1,number2);
}

//checks if number1 is greater than number2.


Cont….
else if (number1 > number2)
{
printf("Result: %d > %d", number1, number2);
}

// if both test expression is false


else
{
printf("Result: %d < %d",number1, number2);
}

return 0;
}
Looping construct
Loops are used in programming to repeat a specific block until some
end condition is met. There are three loops in C programming:
• for loop
• while loop
• do...while loop
for Loop
The syntax of for loop is:
for (initializationStatement; testExpression; updateStatement)
{
// codes
}
How for loop works
The initialization statement is executed only once.

Then, the test expression is evaluated. If the test expression is false (0), for
loop is terminated. But if the test expression is true (nonzero), codes inside
the body of for loop is executed and the update expression is updated.

This process repeats until the test expression is false.

The for loop is commonly used when the number of iterations is known.

To learn more on test expression (when test expression is evaluated to


nonzero (true) and 0 (false)), check out relational and logical operators.
Example
// 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 n is less than count
for(count = 1; count <= num; ++count)
{
sum += count;
}
printf("Sum = %d", sum);
return 0;
}
while loop
The syntax of a while loop is:
while (testExpression)
{
//codes
}
where, testExpression checks the condition is true or false before each
loop.
How while loop works
The while loop evaluates the test expression.
If the test expression is true (nonzero), codes inside the body of while
loop are executed. The test expression is evaluated again. The process
goes on until the test expression is false.
When the test expression is false, the while loop is terminated.
example
// Program to find factorial of a number
// For a positive integer n, factorial = 1*2*3...n

#include <stdio.h>
int main()
{
int number;
long long factorial;
printf("Enter an integer: ");
scanf("%d",&number);
factorial = 1;
// loop terminates when number is less than or equal to 0
while (number > 0)
{
factorial *= number; // factorial = factorial*number;
--number;
}
printf("Factorial= %lld", factorial);
return 0;
}
do...while loop
The do..while loop is similar to the while loop with one important
difference. The body of do...while loop is executed once, before
checking the test expression. Hence, the do...while loop is executed at
least once.
do
{
// codes
}
while (testExpression);
How do...while loop works
The code block (loop body) inside the braces is executed once.

Then, the test expression is evaluated. If the test expression is true, the
loop body is executed again. This process goes on until the test
expression is evaluated to 0 (false).

When the test expression is false (nonzero), the do...while loop is


terminated.
example
// Program to add numbers until user enters zero

#include <stdio.h>
int main()
{
double number, sum = 0;
// loop body 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;
}
Break and continue
It is sometimes desirable to skip some statements inside the loop or
terminate the loop immediately without checking the test expression.
In such cases, break and continue statements are used.

break Statement
The break statement terminates the loop (for, while and do...while
loop) immediately when it is encountered. The break statement is used
with decision making statement such as if...else.
Syntax is: break;
How the break works
How break statement works?
example
// Program to calculate the sum of maximum of 10 numbers
// Calculates sum until user enters positive number

# 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 user enters negative number, loop is terminated
if(number < 0.0)
{
break;
}
sum += number; // sum = sum + number;
}
printf("Sum = %.2lf",sum);
return 0;
}
continue Statement
The continue statement skips some statements inside the loop. The
continue statement is used with decision making statement such as
if...else.
How the continue works
// Program to calculate sum of maximum of 10 numbers
// Negative numbers are skipped from 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 user enters negative number, loop is terminated
if(number < 0.0)
{
continue;
}
sum += number; // sum = sum + number;
}
printf("Sum = %.2lf",sum);
return 0;
}
Switch case
The if..else..if ladder allows you to execute a block code among many
alternatives. If you are checking on the value of a single variable in
if...else...if, it is better to use switch statement.

The switch statement is often faster than nested if...else (not always).
Also, the syntax of switch statement is cleaner and easy to understand.
syntax
switch (n)
​{
case constant1:
// code to be executed if n is equal to constant1;
break;

case constant2:
// code to be executed if n is equal to constant2;
break;
.
.
.
default:
// code to be executed if n doesn't match any constant
}
When a case constant is found that matches the switch expression,
control of the program passes to the block of code associated with that
case.
In the above pseudocode, suppose the value of n is equal to constant2.
The compiler will execute the block of code associate with the case
statement until the end of switch block, or until the break statement is
encountered.
The break statement is used to prevent the code running into the next
case.
example
// Program to create a simple calculator
// Performs addition, subtraction, multiplication or division depending the input from user

# include <stdio.h>
int main() {
char operator;
double firstNumber,secondNumber;

printf("Enter an operator (+, -, *, /): ");


scanf("%c", &operator);
printf("Enter two operands: ");
scanf("%lf %lf",&firstNumber, &secondNumber);

switch(operator)
{
case '+':
printf("%.1lf + %.1lf = %.1lf",firstNumber, secondNumber, firstNumber+secondNumber);
break;
Cont…….
case '-':
printf("%.1lf - %.1lf = %.1lf",firstNumber, secondNumber, firstNumber-secondNumber);
break;
case '*':
printf("%.1lf * %.1lf = %.1lf",firstNumber, secondNumber, firstNumber*secondNumber);
break;
case '/':
printf("%.1lf / %.1lf = %.1lf",firstNumber, secondNumber, firstNumber/firstNumber);
break;

// operator is doesn't match any case constant (+, -, *, /)


default:
printf("Error! operator is not correct");
}
return 0;
}
The Go-To Statement
The goto statement is used to alter the normal sequence of a C
program.
goto label;
... .. ...
... .. ...
label:
statement;
The label is an identifier. When goto statement is encountered, control
of the program jumps to label: and starts executing the code.
example
// Program to calculate the sum and average of maximum of 5 numbers
// If user enters negative number, the sum and average of previously entered positive
number is displayed

# include <stdio.h>
int main()
{

const int maxInput = 5;


int i;
double number, average, sum=0.0;

for(i=1; i<=maxInput; ++i)


{
printf("%d. Enter a number: ", i);
scanf("%lf",&number);
Cont….
// If user enters negative number, flow of program moves to label jump
if(number < 0.0)
goto jump;

sum += number; // sum = sum+number;


}

jump:

average=sum/(i-1);
printf("Sum = %.2f\n", sum);
printf("Average = %.2f", average);

return 0;
}
Functions
A function is a block of code that performs a specific task. Every C program has at
least one function, which is main(), and all the most trivial programs can define
additional functions.
return_type function_name( parameter list ) {
//body of the 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.
Types of functions
There are two types of functions in C programming:
• Standard library functions
• User defined functions
The standard library functions are built-in functions in C programming
to handle tasks such as mathematical computations, I/O processing,
string handling etc.
These functions are defined in the header file. When you include the
header file, these functions are available for use. Example
The printf() is a standard library function to send formatted output to
the screen (display output on the screen). This function is defined in
"stdio.h" header file.
There are other numerous library functions defined under "stdio.h",
such as scanf(), fprintf(), getchar() etc. Once you include "stdio.h" in
your program, all these functions are available for use.

User-defined functions
As mentioned earlier, C allow programmers to define functions. Such
functions created by the user are called user-defined functions.
Depending upon the complexity and requirement of the program, you
can create as many user-defined functions as you want.
How user define function works
#include <stdio.h>
void functionName()
{
... .. ...
... .. ...
}
int main()
{
... .. ...
... .. ...

functionName();

... .. ...
... .. ...
}
Example
/* 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;
}
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
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;
}
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

Call by value: This method copies the actual value of an argument into the formal
1 parameter of the 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
2 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
A to programs to check whether an integer entered by the user is a prime number or
not.
#include <stdio.h>
int checkPrimeNumber(int n);
int main()
{
int n, flag;
printf("Enter a positive integer: ");
scanf("%d",&n);

// n is passed to the checkPrimeNumber() function


// the value returned from the function is assigned to flag variable
flag = checkPrimeNumber(n);

if(flag==1)
printf("%d is not a prime number",n);
else
printf("%d is a prime number",n);
return 0;
}
// integer is returned from the function
int checkPrimeNumber(int n)
{
/* Integer value is returned from function checkPrimeNumber() */
int i;

for(i=2; i <= n/2; ++i)


{
if(n%i == 0)
return 1;
}

return 0;
}
Arrays
An array is a collection of data that holds fixed number of values of
same type. An array is used to store a collection of data, but it is often
more useful to think of an array as a collection of variables of the same
type. The size and type of arrays cannot be changed after its
declaration.
Arrays are of two types:
• One-dimensional arrays
• Multidimensional arrays
Declaring and initializing an Array
To declare an array in C, a programmer specifies the type of the
elements and the number of elements required by an array
type arrayName [ arraySize ];
This is called a single-dimensional array. The arraySize must be an
integer constant greater than zero and type can be any valid C data
type.
You can initialize an array in C either one by one or using a single
statement. Example
double balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0};
example
// Program to find the average of n (n < 10) numbers using arrays
#include <stdio.h>
int main(){

int marks[10], i, n, sum = 0, average;


printf("Enter n: ");
scanf("%d", &n);

for(i=0; i<n; ++i)


{
printf("Enter number%d: ",i+1);
scanf("%d", &marks[i]);
sum += marks[i];
}
average = sum/n;
printf("Average = %d", average);

return 0;
}
Two-dimensional Arrays
type name[size1][size2]...[sizeN];
The simplest form of multidimensional array is the two-dimensional
array. A two-dimensional array is, in essence, a list of one-dimensional
arrays. To declare a two-dimensional integer array of size [x][y], you
would write something as follows −

type arrayName [ x ][ y ];
example
#include <stdio.h>
int main () {

/* an array with 5 rows and 2 columns*/


int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}};
int i, j;

/* output each array element's value */


for ( i = 0; i < 5; i++ ) {

for ( j = 0; j < 2; j++ ) {


printf("a[%d][%d] = %d\n", i,j, a[i][j] );
}
}
return 0;
}
Example 2
#include <stdio.h>
int main()
{
float a[2][2], b[2][2], c[2][2];
int i, j;

// Taking input using nested for loop


printf("Enter elements of 1st matrix\n");
for(i=0; i<2; ++i)
for(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(i=0; i<2; ++i)
for(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(i=0; i<2; ++i)
for(j=0; j<2; ++j)
{
c[i][j] = a[i][j] + b[i][j];
}
// Displaying the sum
printf("\nSum Of Matrix:");

for(i=0; i<2; ++i)


for(j=0; j<2; ++j)
{
printf("%.1f\t", c[i][j]);

if(j==1)
printf("\n");
}
return 0;
}
Three dimensional array
#include <stdio.h>
int main()
{
// this array can store 12 elements

int i, j, k, test[2][3][2];
printf("Enter 12 values: \n");

for(i = 0; i < 2; ++i) {


for (j = 0; j < 3; ++j) {
for(k = 0; k < 2; ++k ) {
scanf("%d", &test[i][j][k]);
}
}
}
// Displaying values with proper index.
printf("\nDisplaying values:\n");

for(i = 0; i < 2; ++i) {


for (j = 0; j < 3; ++j) {
for(k = 0; k < 2; ++k ) {
printf("test[%d][%d][%d] = %d\n", i, j, k, test[i][j][k]);
}
}
}

return 0;
}
Passing arrays to a functions
C program to pass a single element of an array to function
#include <stdio.h>
void display(int age)
{
printf("%d", age);
}

int main(){

int ageArray[] = { 2, 3, 4 };
display(ageArray[2]); //Passing array element ageArray[2] only.

return 0;

}
Passing an entire one-dimensional array to a
function
While passing arrays as arguments to the function, only the name of
the array is passed (,i.e, starting address of memory area is passed as
argument).
Example:
A program to pass an array containing age of person to a function. This
function should find average age and display the average age in main
function.
#include <stdio.h>
float average(float age[]);
int main()​{
float avg, age[] = { 23.4, 55, 22.6, 3, 40.5, 18 };
avg = average(age); /* Only name of array is passed as argument. */
printf("Average age=%.2f", avg);
return 0;
}
float average(float age[])
{
int i; float avg, sum = 0.0;
for (i = 0; i < 6; ++i)
{
sum += age[i];
}
avg = (sum / 6);
return avg;
}
Pointers
A pointer is a variable whose value is the address of another variable,
i.e., direct address of the memory location.
Arrays are closely related to pointers in C programming but the
important difference between them is that, a pointer variable takes
different addresses as value whereas, in case of array it is fixed.
Like any variable or constant, you must declare a pointer before using it
to store any variable address.
type *var-name;

int *ip; /* pointer to an integer */


double *dp; /* pointer to a double */
float *fp; /* pointer to a float */
char *ch /* pointer to a character */
How to Use Pointers
(a) We define a pointer variable,
(b) assign the address of a variable to a pointer and
(c) finally access the value at the address available in the pointer
variable. This is done by using unary operator * that returns the
value of the variable located at the address specified by its operand.
#include <stdio.h>
int main () {

int var = 20; /* actual variable declaration */


int *ip; /* pointer variable declaration */

ip = &var; /* store address of var in pointer variable*/

printf("Address of var variable: %x\n", &var );

/* address stored in pointer variable */


printf("Address stored in ip variable: %x\n", ip );

/* access the value using the pointer */


printf("Value of *ip variable: %d\n", *ip );

return 0;
}
Pointers and Arrays
#include <stdio.h>
int main()
{
int i, classes[6],sum = 0;
printf("Enter 6 numbers:\n");
for(i = 0; i < 6; ++i)
{
// (classes + i) is equivalent to &classes[i]
scanf("%d",(classes + i));

// *(classes + i) is equivalent to classes[i]


sum += *(classes + i);
}
printf("Sum = %d", sum);
return 0;
}
Pointers and functions
When a pointer is passed as an argument to a function, address of the
memory location is passed instead of the value.
This is because, pointer stores the location of the memory, and not the
value.
Example
/* C Program to swap two numbers using pointers and function. */
#include <stdio.h>
void swap(int *n1, int *n2);

int main()
{
int num1 = 5, num2 = 10;

// address of num1 and num2 is passed to the swap function


swap( &num1, &num2);
printf("Number1 = %d\n", num1);
printf("Number2 = %d", num2);
return 0;
}
void swap(int * n1, int * n2)
{
// pointer n1 and n2 points to the address of num1 and num2
respectively
int temp;
temp = *n1;
*n1 = *n2;
*n2 = temp;
}
Structures
structure is another user defined data type available in C that allows to
combine data items of different kinds.
Structures are used to represent a record. Suppose you want to keep
track of your books in a library
To define a structure, you must use the struct statement. The struct
statement defines a new data type, with more than one member
struct [structure tag] {
member definition;
member definition;
...
member definition;
} [one or more structure variables];
Accessing Structure
To access any member of a structure, we use the member access
operator (.). The member access operator is coded as a period between
the structure variable name and the structure member that we wish to
access. You would use the keyword struct to define variables of
structure type.
Example
#include <stdio.h>
#include <string.h>

struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
};

int main( ) {

struct Books Book1; /* Declare Book1 of type Book */


struct Books Book2; /* Declare Book2 of type Book */
/* book 1 specification */
strcpy( Book1.title, "C Programming");
strcpy( Book1.author, "Nuha Ali");
strcpy( Book1.subject, "C Programming Tutorial");
Book1.book_id = 6495407;

/* book 2 specification */
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Zara Ali");
strcpy( Book2.subject, "Telecom Billing Tutorial");
Book2.book_id = 6495700;
/* print Book1 info */
printf( "Book 1 title : %s\n", Book1.title);
printf( "Book 1 author : %s\n", Book1.author);
printf( "Book 1 subject : %s\n", Book1.subject);
printf( "Book 1 book_id : %d\n", Book1.book_id);

/* print Book2 info */


printf( "Book 2 title : %s\n", Book2.title);
printf( "Book 2 author : %s\n", Book2.author);
printf( "Book 2 subject : %s\n", Book2.subject);
printf( "Book 2 book_id : %d\n", Book2.book_id);

return 0;
}
Structures to Pointers
Structures can be created and accessed using pointers

struct name {
member1;
member2;
.
.
};
int main()
{
struct name *ptr;
}
Accessing structure's member through pointer

A structure's member can be accessed through pointer in two ways:


• Referencing pointer to another address to access memory
• Using dynamic memory allocation

1. Example of Referencing pointer to another address to access


memory
#include <stdio.h>
typedef struct person
{
int age;
float weight;
};
int main()
{
struct person *personPtr, person1;
personPtr = &person1; // Referencing pointer to memory address of person1

printf("Enter integer: ");


scanf("%d",&(*personPtr).age);

printf("Enter number: ");


scanf("%f",&(*personPtr).weight);

printf("Displaying: ");
printf("%d%f",(*personPtr).age,(*personPtr).weight);
return 0;
}

You might also like