Uploaded by Rohan Bhujade

C Notes

advertisement
Programming
By Minakshi Ma’am
(Assistant Professor)
C programming is a general-purpose, procedural computer programming language was
developed in 1972 by Dennis Ritchie to develop the UNIX operating system at bell
laboratories of AT&T (American Telephone & Telegraph), located in the U.S.A.
Dennis Ritchie is known as the founder of the C language.
It was developed to overcome the problems of previous languages such as B, BCPL, etc.
C is the most widely used computer language.
C programming is considered as the base for other programming languages, that is why
it is known as mother language.
It can be defined by the following ways:
->Mother language
->System programming language (It is generally used to create hardware devices, OS,
drivers, kernels, etc. For example, Linux kernel is written in C.)
->Procedure-oriented programming language
->Structured programming language
->Mid-level programming language
C as a procedural language
A procedure is known as a function, method, routine, subroutine, etc. A procedural
language specifies a series of steps for the program to solve the problem.
A procedural language breaks the program into functions, data structures, etc.
C is a procedural language. In C, variables and function prototypes must be declared
before being used.
C as a structured programming language
A structured programming language is a subset of the procedural language. Structure
means to break a program into parts or blocks so that it may be easy to understand.
In the C language, we break the program into parts using functions. It makes the
program easier to understand and modify.
C as a mid-level programming language
C is considered as a middle-level language because it supports the feature of both
low-level and high-level languages. C language program is converted into assembly code
(low-level), but it is machine independent (a feature of high-level).
A Low-level language is specific to one machine, i.e., machine dependent. It is machine
dependent, fast to run. But it is not easy to understand.
A High-Level language is not specific to one machine, i.e., machine independent. It is easy
to understand.
Applications of C Programming
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 are •
•
•
•
•
•
•
•
•
Operating Systems
Language Compilers
Assemblers
Text Editors
Network Drivers
Modern Programs
Databases
Language Interpreters
Utilities
A ‘C’ program basically consists of the
following parts −
Pre-processor Commands
Data Types
Variables
Functions
Operators
Statements & Expressions
Comments
Header Files
Loops
Arrays
Pointers
Structures
File I/O
First C Program
To write the first c program, open the C console and write the following code:
1.#include <stdio.h>
2.int main(){
3.printf("Hello C Language");
4.return 0;
5.}
#include <stdio.h> includes the standard input output library functions. The printf()
function is defined in stdio.h .
int main() The main() function is the entry point of every program in C language.
printf() The printf() function is used to print data on the console.
return 0 The return 0 statement, returns execution status to the OS. The 0 value is used for
successful execution and 1 for unsuccessful execution.
Hello World Program Example
Compilation process in C
What is a compilation?
The compilation is a process of converting the source code into object code. It is done with
the help of the compiler. The compiler checks the source code for the syntactical or
structural errors, and if the source code is error-free, then it generates the object code.
The C compilation process converts the source code taken as input into the object code or
machine code. The compilation process can be divided into four steps, i.e., Pre-processing,
Compiling, Assembling, and Linking.
The following are the phases through which our
program passes before being transformed into
an executable form:
Preprocessor
The source code is the code which is written in a
text editor and the source code file is given an
extension ".c". This source code is first passed to
the preprocessor, and then the preprocessor expands
this code. After expanding the code, the expanded
code is passed to the compiler.
Compiler
The code which is expanded by the preprocessor is passed to the compiler. The compiler
converts this code into assembly code. Or we can say that the C compiler converts the
pre-processed code into assembly code.
Assembler
The assembly code is converted into object code by using an assembler. The name of the
object file generated by the assembler is the same as the source file. The extension of the
object file is '.obj,' and in UNIX, the extension is 'o'. If the name of the source file
is 'hello.c', then the name of the object file would be 'hello.obj’.
Linker
Mainly, all the programs written in C use library functions. These library functions are
pre-compiled, and the object code of these library files is stored with '.lib' (or '.a') extension.
The main working of the linker is to combine the object code of library files with the object
code of our program.
C - Basic Syntax
C Tokens , Keywords and Identifiers
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");
The individual tokens are −
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.
Given below are two different statements −
printf("Hello, World! \n");
return 0;
Comments in C
Comments in C language are used to provide information about lines of code. It is
widely used for documenting code. Comments are like helping text in your C program
and they are ignored by the compiler.There are 2 types of comments in the C
language.
Single Line Comments
Multi-Line Comments
Single Line Comments
Single line comments are represented by double slash //.
Even you can place the comment after the statement.
For example:
printf("Hello C");//printing information
Multi Line Comments
Multi-Line comments are represented by slash asterisk /* ... */. It can occupy many
lines of code, but it can't be nested. Syntax:
Character set
A character set is a set of alphabets, letters and some special characters that are valid
in C language.
Alphabets
Uppercase: A B C ................................... X Y Z
Lowercase: a b c ...................................... x y z
C accepts both lowercase and uppercase alphabets as variables and functions.
Digits
0123456789
Special Characters
Whitespace in C
A line containing only whitespace, possibly with a comment, is known as a blank line,
and a C compiler totally ignores it.
Whitespace is the term used in C to describe blanks, tabs, newline characters and
comments. Whitespace separates one part of a statement from another and enables
the compiler to identify where one element in a statement, such as int, ends and the
next element begins. Therefore, in the following statement −
int age;
there must be at least one whitespace character (usually a space) between int and age
for the compiler to be able to distinguish them.
C Keywords
Keywords are predefined, reserved words used in programming that have special
meanings to the compiler. Keywords are part of the syntax and they cannot be used
as an constants or variables or any other identifier names. These words help us to
use the functionality of C language. They have special meaning to the compilers.
For example:
int money;
Here, int is a keyword that indicates money is a variable of type int (integer).
As C is a case sensitive language, all keywords must be written in lowercase.
There are total 32 keywords in C. Here is a list of all keywords allowed in ANSI C. The
C language was formalized in 1988 by the American National Standard Institue
(ANSI).
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.
Also remember, identifier names must be different from keywords. You cannot use
int as an identifier because int is a keyword.
C is a case-sensitive programming language. Thus, Manpower and manpower are
two different identifiers in C. Here are some examples of acceptable identifiers −
mohd
zara abc move_name a_123
myname50 _temp j a23b9 retVal
Rules for naming identifiers
A valid identifier can have letters (both uppercase and lowercase letters), digits
and underscores.
The first letter of an identifier should be either a letter or an underscore.
A valid identifier name cannot start with a digit.
You cannot use keywords like int, while etc. as identifiers.
There is no rule on how long an identifier can be. However, you may run into
problems in some compilers if the identifier is longer than 31 characters.
.
C Variables, Constants and Literals
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. For example:
int playerScore = 95;
Here, playerScore is a variable of int type. Here, the variable is assigned an integer value 95.
The value of a variable can be changed, hence the name variable.
char ch = 'a';
// some code
ch = 'l';
C is a strongly typed language. This means that the variable type cannot be changed
once it is declared. For example:
int number = 5; // integer variable
number = 5.5;
// error
double number;
// error
Here, the type of number variable is int. You cannot assign a floating-point (decimal)
value 5.5 to this variable. Also, you cannot redefine the data type of the variable to
double. By the way, to store the decimal values in C, you need to declare its type to
either double or float.
Literals
Literals are data used for representing fixed values. They can be used directly in the code.
For example: 1, 2.5, 'c' etc.
Here, 1, 2.5 and 'c' are literals. You cannot assign different values to these terms.
1. Integers
An integer is a numeric literal(associated with numbers) without any fractional or
exponential part. There are three types of integer literals in C programming:
•decimal (base 10)
•octal (base 8)
•hexadecimal (base 16)
For example:
Decimal: 0, -9, 22 etc
Octal: 021, 077, 033 etc
Hexadecimal: 0x7f, 0x2a, 0x521 etc
In C programming, octal starts with a 0, and hexadecimal starts with a 0x.
2. Floating-point Literals
A floating-point literal is a numeric literal that has either a fractional form or an exponent
form. For example:
-2.0
0.0000234
-0.22E-5
3. Characters
A character literal is created by enclosing a single character inside single quotation
marks. For example: 'a', 'm', 'F', '2', '}' etc.
4. Escape Sequences
Sometimes, it is necessary to use characters that 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 sequences are used.
For example: \n is used
for a newline. The
backslash \ causes escape
from the normal way the
characters are handled by
the compiler.
5. String Literals
A string literal is a sequence of characters enclosed in double-quote marks. For example:
"good"
""
" "
"x"
"Earth is round\n"
//string constant
//null string constant
//string constant of six white space
//string constant having a single character.
//prints string with a newline
Constants
If you want to define a variable whose value cannot be changed, you can use the const
keyword. This will create a constant. For example,
const double PI = 3.14;
Notice, we have added keyword const.
Here, PI is a symbolic constant; its value cannot be changed.
const double PI = 3.14;
PI = 2.9; //Error
Data
Types
in
C
A data type specifies the type of data that a variable can store such as integer, floating,
character, etc.
There are the following data types in C language.
Basic Data Types
The basic data types are
integer-based
and
floating-point
based.
C
language supports both
signed and unsigned literals.
The memory size of the
basic data types may change
according to 32 or 64-bit
operating system.
Its size is given according
to 32-bit architecture.
Data Types
Memory Size Range
char
signed char
unsigned char
int
signed int
unsigned int
short int
signed short int
unsigned short int
long int
1 byte
1 byte
1 byte
2 byte
2 byte
2 byte
2 byte
2 byte
2 byte
4 byte
signed long int
4 byte
unsigned long int
float
double
long double
String
4 byte
4 byte
8 byte
10 byte
An octal (base 8) integer
Hexadecimal
representation
Format Specifier
−128 to 127
%c
−128 to 127
%c
0 to 255
%c
−32,768 to 32,767
%d
−32,768 to 32,767
%i
0 to 65,535
%u
−32,768 to 32,767
%hd
%hi
−32,768 to 32,767
%hu
0 to 65,535
-2,147,483,648
to %ld
2,147,483,647
-2,147,483,648
to %li
2,147,483,647
0 to 4,294,967,295
%lu
%f
%lf
%Lf
%s
%o
%x or %X
Derived Data Types
Data types that are derived from fundamental data types are derived types. For example:
arrays, pointers, function types, structures, etc.
printf() and scanf() in C
The printf() and scanf() functions are used for input and output in C language. Both
functions are inbuilt library functions, defined in stdio.h (header file).
printf() function
The printf() function is used for output. It prints the given statement to the console.
The syntax of printf() function is given below:
printf("format string",argument_list);
The format string can be %d (integer), %c (character), %s (string), %f (float) etc.
scanf() function
The scanf() function is used for input. It reads the input data from the console.
scanf("format string",argument_list);
Program
numbers
to
print
sum
1.#include<stdio.h>
2.int main(){
3.int x=0,y=0,result=0;
4.
5.printf("enter first number:");
6.scanf("%d",&x);
7.printf("enter second number:");
8.scanf("%d",&y);
9.
10.result=x+y;
11.printf("sum of 2 numbers:%d ",result);
12.
13.return 0;
14.}
of
2
The scanf("%d",&x) statement reads integer
number from the console and stores the given
value in x variable.
Notice, that we have used &x inside scanf(). It is
because &x gets the address of x, and the value
entered by the user is stored in that address.
The printf("sum of 2 numbers:%d ",result)
statement prints the sum of two numbers on the
console.
Float and Double Input/Output
#include <stdio.h>
int main()
{
float num1;
double num2;
printf("Enter a number: ");
scanf("%f", &num1);
printf("Enter another number: ");
scanf("%lf", &num2);
printf("num1 = %f\n", num1);
printf("num2 = %lf", num2);
return 0;
}
C Character and ASCII I/O
#include <stdio.h>
int main()
{
char chr;
printf("Enter a character: ");
scanf("%c", &chr);
// When %c is used, a character is displayed
printf("You entered %c.\n",chr);
// When %d is used, ASCII value is displayed
printf("ASCII value is %d.", chr);
return 0;
}
When a character is entered by the user in
the above program, the character itself is not
stored. Instead, an integer value (ASCII value)
is stored.
And when we display that value using %c text
format, the entered character is displayed. If
we use %d to display the character, it's ASCII
value is printed.
ASCII: American Standard Code for Information
Interchange. ASCII stands
for
American
Standard Code for Information Interchange. It is
a method to define a set of characters for
encoding text documents on computers.
C Operators
An operator is simply a symbol that is used to perform operations. There can be many types
of operations like arithmetic, logical, bitwise, etc.
There are following types of operators to perform different types of operations in C
language.
• Arithmetic Operators
• Relational Operators
• Logical Operators
• Bitwise Operators
• Ternary or Conditional Operators
• Assignment Operator
• Misc Operator
C Arithmetic Operators
An
arithmetic
operator
performs
mathematical operations such as addition,
subtraction, multiplication, division etc on
numerical values (constants and variables).
In normal calculation, 9/4 = 2.25. However, the output is 2 in the program. It is because both the variables a and b are
integers. Hence, the output is also an integer. The compiler neglects the term after the decimal point and shows answer 2
instead of 2.25.
The modulo operator % computes the remainder. When a=9 is divided by b=4, the remainder is 1. The % operator can only be
used with integers.
C 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.
C 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.
C Bitwise Operators
During computation, mathematical operations like: addition, subtraction, multiplication,
division, etc are converted to bit-level which makes processing faster and saves power.
Bitwise operators are used in C programming to perform bit-level operations.
C Assignment Operators
An assignment operator is used for assigning a value to a variable. The most common
assignment operator is =
Comma Operator
Comma operators are used to link related expressions together. For example:
int a, c = 5, d;
The sizeof operator
The sizeof is a unary operator that returns the size of data (constants, variables, array,
structure, etc).
C 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.
Here, the operators ++ and -- are used as
prefixes. These two operators can also be used as
postfixes like a++ and a--.
C Flow Control
C if Statement
The syntax of the if statement in C is:
if (test expression)
{
// code
}
The if statement evaluates the test expression inside the parenthesis ().
• If the test expression is evaluated to true, statements inside the body of if are executed.
• If the test expression is evaluated to false, statements inside the body of if are not
executed.
Example
C if...else Statement
The if statement may have an optional else block. The syntax of the if…else statement is:
if (test expression) {
// run code if test expression is true
}
else {
// run code if test expression is false
}
If the test expression is evaluated to true,
• statements inside the body of if are executed.
• statements inside the body of else are skipped from execution.
If the test expression is evaluated to false,
• statements inside the body of else are executed
• statements inside the body of if are skipped from execution.
Example
C if...else Ladder
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 if...else ladder allows you to check
between multiple test expressions and
execute different statements.
#include <stdio.h>
Nested if...else
int main() {
It is possible to include an if...else statement int number1, number2;
printf("Enter two integers: ");
inside the body of another if...else statement.
scanf("%d %d", &number1, &number2);
This program given below relates two integers
using either <, > and = similar to the if...else
ladder's example. However, we will use a
nested if...else statement to solve this problem.
if (number1 >= number2) {
if (number1 == number2) {
printf("Result: %d = %d",number1,number2);
}
else {
printf("Result: %d > %d", number1, number2);
}
}
else {
printf("Result: %d < %d",number1, number2);
}
return 0;
If the body of an if...else statement has only
one statement, you do not need to use
brackets {}.
}
Conditional or Ternary Operator (?:)
in
TheCconditional operator is kind of similar to the if-else
statement as it does
follow the same algorithm as of if-else statement but the conditional operator
takes less space and helps to write the if-else statements in the shortest way
possible.
Syntax:
The conditional operator is of the form
variable = Expression1 ? Expression2 : Expression3
It can be visualized into if-else statement as:
if(Expression1)
{
variable = Expression2;
}
else
Since the Conditional Operator ‘?:’ takes three
{
operands to work, hence they are also
variable = Expression3;
called ternary operators.
}
Example: Program to Store the greatest of the two Number.
// C program to find largest among two
// numbers using ternary operator
#include <stdio.h>
int main()
{
int m = 5, n = 4;
Output
m is greater than n that is 5 > 4
(m > n) ? printf("m is greater than n that is %d > %d",m, n)
: printf("n is greater than m that is %d > %d",n, m);
return 0;
}
C Loops
In programming, a loop is used to repeat a block of code until the specified condition is met.
C programming has three types of loops:
▪ for loop
▪ while loop
▪ do...while loop
for Loop
The syntax of the for loop is:
for (initializationStatement; testExpression; updateStatement)
{
// statements inside the body of loop
}
How for loop works?
• The initialization statement is executed only once.
• Then, the test expression is evaluated. If the test expression is evaluated to false, the for
loop is terminated.
• However, if the test expression is evaluated to true, statements inside the body of the for
loop are executed, and the update expression is updated.
• Again the test expression is evaluated.
• This process goes on until the test expression is false. When the test expression is false,
the loop terminates.
• i is initialized to 1.
Example : for loop
// Print numbers from 1 to 10
#include <stdio.h>
• The test expression i < 11 is evaluated. Since 1 less than 11 is
true, the body of for loop is executed. This will print the 1
(value of i) on the screen.
int main() {
int i;
for (i = 1; i < 11; ++i)
{
printf("%d ", i);
}
return 0;
}
Output
1 2 3 4 5 6 7 8 9 10
• The update statement ++i is executed. Now, the value of i will
be 2. Again, the test expression is evaluated to true, and the
body of for loop is executed. This will print 2 (value of i) on
the screen.
• Again, the update statement ++i is executed and the test
expression i < 11 is evaluated. This process goes on until i
becomes 11.
• When i becomes 11, i < 11 will be false, and the for loop
terminates.
while loop
The syntax of the while loop is:
while (testExpression) {
// the body of the loop
}
How while loop works?
▪ The while loop evaluates the testExpression inside the parentheses ().
▪ If testExpression is true, statements inside the body of while loop are executed.
Then, testExpression is evaluated again.
▪ The process goes on until testExpression is evaluated to false.
▪ If testExpression is false, the loop terminates (ends).
Example : while loop
• Here, we have initialized i to 1.
// Print numbers from 1 to 5
• When i = 1, the test expression i <= 5 is true. Hence,
the body of the while loop is executed. This prints 1
#include <stdio.h>
int main() {
int i = 1;
while (i <= 5) {
printf("%d\n", i);
++i;
}
return 0;
}
on the screen and the value of i is increased to 2.
• Now, i = 2, the test expression i <= 5 is again true.
The body of the while loop is executed again. This
Output
prints 2 on the screen and the value of i is increased
to 3.
1
2
3
4
5
• This process goes on until i becomes 6. Then, the test
expression i <= 5 will be false and the loop
terminates.
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 at least once. Only then, the test expression is evaluated.
The syntax of the do...while loop is:
do {
// the body of the loop
}
while (testExpression);
How do...while loop works?
• The body of do...while loop is executed once. Only then, the testExpression is
evaluated.
• If testExpression is true, the body of the loop is executed again and testExpression is
evaluated once more.
• This process goes on until testExpression becomes false.
• If testExpression is false, the loop ends.
Example : do...while loop
// Program to add numbers until the user enters zero The do...while loop executes at least once i.e.
#include <stdio.h>
int main() {
double number, sum = 0;
the first iteration runs without checking the
condition. The condition is checked only after
the first iteration has been executed.
So, if the first input is a non-zero number, that
number is added to the sum variable and the
loop continues to the next iteration. This
process is repeated until the user enters 0.
// the body of the loop is executed at least once
do {
printf("Enter a number: ");
Output
scanf("%lf", &number);
sum += number;
Enter a number: 1.5 But if the first input is 0, there will be no
}
Enter a number: 2.4 second iteration of the loop and sum becomes
while(number != 0.0);
printf("Sum = %.2lf",sum);
return 0;
}
Enter a number: -3.4 0.0.
Enter a number: 4.2
Enter a number: 0 Outside the loop, we print the value of sum.
Sum = 4.70
C Switch Statement
The switch statement in C is an
alternate to if-else-if ladder
statement which allows us to
execute multiple operations for the
different possible values of a single
variable called switch variable.
Here, We can define various
statements in the multiple cases for
the different values of a single
variable.
Syntax of switch...case
switch(expression){
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......
default:
code to be executed if all cases are not mat
ched;
}
Rules for switch statement in C language
1) The switch expression must be of an integer or character type.
2) The case value must be an integer or character constant.
3) The case value can be used only inside the switch statement.
4) The break statement in switch case is not must. It is optional. If there is no break
statement found in the case, all the cases will be executed present after the matched case.
It is known as fall through the state of C switch statement.
We are assuming that there are following variables.
Switch Statement Flowchart
Example
1.#include<stdio.h>
2.int main(){
3.int number=0;
4.printf("enter a number:");
5.scanf("%d",&number);
6.switch(number){
7.case 10:
8.printf("number is equals to 10");
9.break;
10.case 50:
11.printf("number is equal to 50");
We can use as many switch statement as we want inside a
12.break;
switch statement. Such type of statements is called nested
13.case 100:
switch case statements.
14.printf("number is equal to 100");
15.break;
16.default:
17.printf("number is not equal to 10, 50 or 100");
18.}
19.return 0;
20.}
C break statement
The break is a keyword in C which is used to bring the program control out of the loop. The
break statement is used inside loops or switch statement. The break statement breaks the
loop one by one, i.e., in the case of nested loops, it breaks the inner loop first and then
proceeds to outer loops.
The break statement in C can be used in the following two scenarios:
1.With switch case
2.With loop
Example
C continue statement
The continue statement in C language is used to bring the program control to the
beginning of the loop. The continue statement skips some lines of code inside the loop and
continues with the next iteration. It is mainly used for a condition so that we can skip some
code for a particular condition.
Example
1.#include<stdio.h>
2.int main(){
3.int i=1;//initializing a local variable
4.//starting a loop from 1 to 10
5.for(i=1;i<=10;i++){
6.if(i==5){//if value of i is equal to 5, it will conti
nue the loop
7.continue;
8.}
9.printf("%d \n",i);
10.}//end of for loop
11.return 0;
12.}
C - Functions
• A function is a group of statements that together perform a task. Every C
program has at least one function, which is main(), and all the most trivial
programs can define additional functions.
• We can divide up our code into separate functions but logically the division is
such that each function performs a specific task.
• A function declaration tells the compiler about a function's name, return type,
and parameters. A function definition provides the actual body of the function.
• A function can also be referred as a method or a sub-routine or a procedure,
etc.
Types of function
There are two types of function in C programming:
•Standard library functions
•User-defined functions
Standard library functions
The standard library functions are built-in functions in C programming.
These functions are defined in header files. For 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 the stdio.h header file.
Hence, to use the printf()function, we need to include the stdio.h header file using
#include <stdio.h>.
The sqrt() function calculates the square root of a number. The function is defined in the
math.h header file.
C User-defined Functions
A function is a block of code that performs
a specific task.
C allows you to define functions according
to your need. These functions are known
as user-defined functions.
Example: User-defined function
Here is an example to add two integers. To
perform this task, we have created an
user-defined addNumbers().
Function prototype
A function prototype is simply the declaration of a function that specifies
function's name, parameters and return type. It doesn't contain function body.
A function prototype gives information to the compiler that the function may later
be used in the program.
In the above example, int addNumbers(int a, int b); is the function prototype which provides the
following information to the compiler:
name of the function is addNumbers()
return type of the function is int
two arguments of type int are passed to the function
The function prototype is not needed if the user-defined function is defined before the main()
function.
Calling a function
Control of the program is transferred to the user-defined function by
calling it.
In the above example, the function call is made using addNumbers(n1, n2); statement
inside the main() function.
Function definition
Function definition contains the block of code to perform a specific task. In our
example, adding two numbers and returning it.
When a function is called, the control of the
program is transferred to the function
definition. And, the compiler starts
executing the codes inside the body of a
function.
Passing arguments to a function
In programming, argument refers to the variable passed to the function. In the
above example, two variables n1 and n2 are passed during the function call.
The parameters a and b accepts the passed arguments in the function definition.
These arguments are called formal parameters of the function.
The type of arguments passed to a function and
the formal parameters must match, otherwise,
the compiler will throw an error.
If n1 is of char type, a also should be of char
type. If n2 is of float type, variable b also should
be of float type.
A function can also be called without passing
an argument.
Return Statement
The return statement terminates the execution
of a function and returns a value to the calling
function. The program control is transferred to
the calling function after the return statement.
In the above example, the value of the result
variable is returned to the main function. The
sum variable in the main() function is assigned
this value.
Syntax of return statement
return (expression);
For example,
return a;
return (a+b);
The type of value returned from the function
and the return type specified in the function
prototype and function definition must match.
Call by value and Call by reference in C
There are two methods to pass the data into the function in C language, i.e., call by
value and call by reference.
Call by value
This method copies the actual value of an argument into the
formal parameter of the function. In this case, changes made
to the parameter inside the function have no effect on the
argument.
Call by reference
This method copies the address of an argument
into the formal parameter. Inside the function,
the address is used to access the actual
argument used in the call. This means that
changes made to the parameter affect the
argument.
C Recursion
A function that calls itself is known as a recursive function. And, this technique is
known as recursion.
The recursion continues until some condition is met to prevent it.
To prevent infinite recursion, if...else statement (or similar approach) can be used
where one branch makes the recursive call, and other doesn't.
C - Arrays
Array is a kind of data structure that can store a fixed-size sequential collection of
elements of the same type. An array is a variable that can store multiple values.
How to declare an array?
dataType arrayName[arraySize];
For example,
float mark[5];
Here, we declared an array, mark, of floating-point type. And its size is 5. Meaning, it
can hold 5 floating-point values.
It's important to note that the size and type of an array cannot be changed once it is
declared.
Access Array Elements
You can access elements of an array by indices.
Suppose you declared an array mark as above. The first element is mark[0], the
second element is mark[1] and so on.
Note- mark[0]=0[mark]
Few keynotes:
• Arrays have 0 as the first index, not 1. In this example, mark[0] is the first element.
• If the size of an array is n, to access the last element, the n-1 index is used. In this
example, mark[4]
• Suppose the starting address of mark[0] is 2120d. Then, the address of the mark[1]
will be 2124d. Similarly, the address of mark[2] will be 2128d and so on.
• This is because the size of a float is 4 bytes.
How to initialize an array?
It is possible to initialize an array during declaration. For example,
int mark[5] = {19, 10, 8, 17, 9};
We can also initialize an array like this.
int mark[] = {19, 10, 8, 17, 9};
Here, we haven't specified the size. However, the compiler knows its size is 5 as we are
initializing it with 5 elements.
Here,
mark[0] is equal to 19
mark[1] is equal to 10
mark[2] is equal to 8
mark[3] is equal to 17
mark[4] is equal to 9
Change Value of Array elements
int mark[5] = {19, 10, 8, 17, 9}
// make the value of the third element to -1
mark[2] = -1;
// make the value of the fifth element to 0
mark[4] = 0;
Input and Output Array Elements
We can take input from the user and store
it in an array element.
// take input and store it in the 3rd
element
scanf("%d", &mark[2]);
// take input and store it in the ith element
We can print an individual element of an array.
// print the first element of the array
printf("%d", mark[0]);
// print the third element of the array
printf("%d", mark[2]);
// print ith element of the array
printf("%d", mark[i-1]);
Example 1: Array Input/Output
// Program to take 5 values from the user and store them in an
array
Output
// Print the elements stored in the array
#include <stdio.h>
Enter 5 integers: 1
int main() {
-3
int values[5];
34
printf("Enter 5 integers: ");
0
// taking input and storing it in an array
3
for(int i = 0; i < 5; ++i) {
Displaying integers: 1
scanf("%d", &values[i]);
-3
}
34
printf("Displaying integers: ");
0
3
// printing elements of an array
Here, we have used a for loop to take 5 inputs from
for(int i = 0; i < 5; ++i) {
the user and store them in an array. Then, using
printf("%d\n", values[i]);
another for loop, these elements are displayed on
}
the screen.
return 0;
In C programming, we can create an array of arrays. These arrays are known as
multidimensional arrays. For example,
float x[3][4];
Here, x is a two-dimensional (2d) array. The array can hold 12 elements. You can think the
array as a table with 3 rows and each row has 4 columns.
Similarly, we can declare a three-dimensional (3d) array. For example,
float y[2][4][3];
Here, the array y can hold 24 elements.
Initializing a multidimensional array
We can initialize two-dimensional and three-dimensional arrays:
Initialization of a 2d array
// Different ways to initialize two-dimensional array
int c[2][3] = {{1, 3, 0}, {-1, 5, 9}};
int c[][3] = {{1, 3, 0}, {-1, 5, 9}};
int c[2][3] = {1, 3, 0, -1, 5, 9};
We can initialize a three-dimensional array in a similar way like a two-dimensional array.
Here's an example,
int test[2][3][4] = {
{{3, 4, 2, 3}, {0, -3, 9, 11}, {23, 12, 23, 2}},
{{13, 4, 56, 3}, {5, 9, 3, 5}, {3, 1, 4, 9}}};
Pass arrays to a function in C
Pass Individual Array Elements
Passing array elements to a function is similar to passing variables to a function.
int ageArray[] = {2, 8, 4, 12};
// pass second and third elements to display()
display(ageArray[1], ageArray[2]);
Here, we have passed array parameters to the display() function in the same way we
pass variables to a function.
Pass Arrays to Functions
// Program to calculate the sum of array elements by passing to a function
#include <stdio.h>
float calculateSum(float num[]);
Output
int main() {
Result = 162.50
float result, num[] = {23.4, 55, 22.6, 3, 40.5, 18};
To pass an entire array to a function, only
// num array is passed to calculateSum()
the name of the array is passed as an
result = calculateSum(num);
argument.
printf("Result = %.2f", result);
result = calculateSum(num);
return 0;
However, notice the use of [] in the
}
function definition.
float calculateSum(float num[]) {
float calculateSum(float num[]) {
float sum = 0.0;
... ..
for (int i = 0; i < 6; ++i) {
}
sum += num[i];
This informs the compiler that you are
}
passing a one-dimensional array to the
return sum;
function.
}
C - Structures
Arrays allow to define type of variables that can hold several data items of the same
kind. Similarly 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 we want to keep track of your
books in a library. We might want to track the following attributes about each book
−
• Title
• Author
• Subject
• Book ID
Defining a Structure
To define a structure, you must use the struct keyword. The struct keyword defines a
new data type, with more than one member.
Here is the way you would declare the Book
structure −
Syntax of struct
struct Books {
struct structureName {
char title[50];
dataType member1;
char author[50];
dataType member2;
char subject[100];
...
int book_id;
} [one or more structure variables]; } book;
At the end of the structure's definition, before the final semicolon, you can specify one
or more structure variables but it is optional.
Create struct Variables
When a struct type is declared, no storage or memory is allocated. To allocate memory
of a given structure type and work with it, we need to create variables.
Here's how we create structure variables:
Another way of creating a struct variable is:
struct Person {
struct Person {
// code
// code
} person1, person2, p[20];
};
int main() {
struct Person person1, person2, p[20];
return 0;
}
In both cases,
person1 and person2 are struct Person variables
p[] is a struct Person array of size 20.
Access Members of a Structure
There are two types of operators used for accessing members of a structure.
. - Member operator
-> - Structure pointer operator
Suppose, we want to access the salary of person2. Here's how we can do it.
person2.salary
Example 1: C Structure
#include <stdio.h>
#include <string.h>
// create struct with person1 variable
struct Person {
char name[50];
int citNo;
float salary;
} person1;
// print struct variables
printf("Name: %s\n", person1.name);
printf("Citizenship No.: %d\n", person1.citNo);
printf("Salary: %.2f", person1.salary);
return 0;
}
int main() {
// assign value to name of person1
strcpy(person1.name, "George Orwell");
// assign values to other person1 variables
person1.citNo = 1984;
person1. salary = 2500;
Output
Name: George Orwell
Citizenship No.: 1984
Salary: 2500.00
Size of the Structure Can be Evaluated using “sizeof Operator”
size = sizeof(s);
Formula for Calculating Size of Structure :
------------------------------------------Size of Structure 'S' = sizeof(roll) + sizeof(name)
+ sizeof(mark)
= 2 + 10 + 2
= 14
->Size depends on your computer
Remember :
---------• sizeof is Operator not function
• sizeof Operator Takes any Variable as Parameter.
C -UNION
• A union is a special data type available in C that allows to store different data
types in the same memory location.
• We can define a union with many members, but only one member can contain
a value at any given time.
• Unions provide an efficient way of using the same memory location for
multiple-purpose.
• Structures allocate enough space to store all their members,
whereas unions can only hold one member value at a time.
How to define a union?
We use the union keyword to define unions.
Here's an example:
union car
{
char name[50];
int price;
};
The above code defines a derived type union
car.
Create union variables
When a union is defined, it creates a user-defined type. However, no memory is allocated.
To allocate memory for a given union type and work with it, we need to create variables.
Here's how we create union variables.
Another way of creating union variables is:
union car
{
char name[50];
int price;
};
union car
{
char name[50];
int price;
} car1, car2, *car3;
int main()
{
union car car1, car2, *car3;
return 0;
}
In both cases, union variables car1, car2, and a
union pointer car3 of union car type are created.
Access members of a union
We use the . operator to access members of a union. And to access pointer variables, we
use the -> operator.
In the above example,
To access price for car1, car1.price is used.
To access price using car3, either (*car3).price or car3->price can be used.
Difference between unions and structures
Let's take an example to demonstrate the difference between unions and structures:
#include <stdio.h>
union unionJob
{
int main()
//defining a union
{
char name[32];
printf("size of union = %d bytes", sizeof(uJob));
float salary;
printf("\nsize of structure = %d bytes", sizeof(sJob));
int workerNo;
return 0;
} uJob;
}
struct structJob
{
char name[32];
float salary;
int workerNo;
} sJob;
Why this difference in the size of union and structure variables?
Here, the size of sJob is 40 bytes because
• the size of name[32] is 32 bytes
• the size of salary is 4 bytes
• the size of workerNo is 4 bytes
However, the size of uJob is 32 bytes. It's because the size of a union variable will
always be the size of its largest element. In the above example, the size of its largest
element, (name[32]), is 32 bytes.
With a union, all members share the same memory.
Example: Accessing Union Members
#include <stdio.h>
union Job {
float salary;
int workerNo;
} j;
int main() {
j.salary = 12.3;
// when j.workerNo is assigned a value,
// j.salary will no longer hold 12.3
j.workerNo = 100;
printf("Salary = %.1f\n", j.salary);
printf("Number of workers = %d",
j.workerNo);
return 0;
}
Output
Salary = 0.0
Number of workers = 100
Storage Classes in C
Storage classes in C are used to determine the lifetime, visibility, memory location,
and initial value of a variable. There are four types of storage classes in C
•Automatic
•External
•Static
•Register
Automatic
•Automatic variables are allocated memory automatically at runtime.
•The visibility of the automatic variables is limited to the block in which they are defined.
•The scope of the automatic variables is limited to the block in which they are defined. The
automatic variables are initialized to garbage by default.
•The memory assigned to automatic variables gets freed upon exiting from the block.
•The keyword used for defining automatic variables is auto.
•Every local variable is automatic in C by default.
Example 1
#include <stdio.h>
int main()
{
int a; //auto
char b;
float c;
printf("%d %c %f",a,b,c); // printing initial default value of automatic variables a, b, and c.
return 0;
}
Static
•The variables defined as static specifier can hold their value between the multiple function
calls.
•Static local variables are visible only to the function or the block in which they are
defined.
•A same static variable can be declared many times but can be assigned at only one time.
•Default initial value of the static integral variable is 0.
•The visibility of the static global variable is limited to the file in which it has declared.
•The keyword used to define static variable is static.
Example 1
#include<stdio.h>
static char c;
static int i;
static float f;
static char s[100];
void main ()
{
printf("%d %d %f %s",c,i,f,s); // the initial default value of c, i, and f will be printed.
Register
•The variables defined as the register is allocated the memory into the CPU registers
depending upon the size of the memory remaining in the CPU.
•We can not dereference the register variables, i.e., we can not use &operator for the
register variable.
•The access time of the register variables is faster than the automatic variables.
•The initial default value of the register variable is garbage value.
•The register keyword is used for the variable which should be stored in the CPU
register. However, it is compiler’s choice whether or not; the variables can be stored
in the register.
External
•The external storage class is used to tell the compiler that the variable defined as extern is
declared with an external linkage elsewhere in the program.
•The variables declared as extern are not allocated any memory. It is only declaration and
intended to specify that the variable is declared elsewhere in the program.
•The default initial value of external integral type is 0 .
•We can only initialize the extern variable globally, i.e., we can not initialize the external
variable within any block or method.
•An external variable can be declared many times but can be initialized at only once.
•If a variable is declared as external then the compiler searches for that variable to be
initialized somewhere in the program which may be extern or static. If it is not, then the
compiler will show an error.
Example 1
1.#include <stdio.h>
2.int main()
3.{
4.extern int a;
5.printf("%d",a);
6.}
Example 2
1.#include <stdio.h>
2.int a;
3.int main()
4.{
5.extern int a; // variable a is defined globally, the memory will not be allocated to a
6.printf("%d",a);
Example 3
1.#include <stdio.h>
2.int a;
3.int main()
4.{
5.extern int a = 0; // this will show a compiler error since we can not use extern and init
ializer at same time
6.printf("%d",a);
7.}
Example 4
1.#include <stdio.h>
2.int main()
3.{
4.extern int a; // Compiler will search here for a variable a defined and initialized somewhere in
the pogram or not.
5.printf("%d",a);
6.}
7.int a = 20;
C Pointers
The pointer in C language is a variable which stores the address of another variable. This
variable can be of type int, char, array, function, or any other pointer. The size of the pointer
depends on the architecture. However, in 32-bit architecture the size of a pointer is 2 byte.
Consider the following example to define a pointer which stores the address of an integer.
1.int n = 10;
2.int* p = &n; // Variable p of type pointer is pointing to the address of the variable n of type in
teger.
Declaring a pointer
The pointer in c language can be declared
using * (asterisk symbol). It is also known as
indirection pointer used to dereference a pointer.
1.int *a;//pointer to int
2.char *c;//pointer to char
Pointer variable stores the address of number variable, i.e., fff4. The value of number
variable is 50. But the address of pointer variable p is aaa3.
By the help of * (indirection operator), we can print the value of pointer variable p.
Let's see the pointer example as explained for the above figure.
1.#include<stdio.h>
2.int main(){
3.int number=50;
4.int *p;
5.p=&number;
//stores the address of number variable
6.printf("Address of p variable is %x \n",p);
// p contains the address of the number therefore printing p gives the address of number
.
7.printf("Value of p variable is %d \n",*p);
// As we know that * is used to dereference a pointer therefore if we print *p, we will g
et the value stored at the address contained by p
8.return 0;
NULL Pointer
A pointer that is not assigned any value but NULL is known as the NULL pointer. If you
don't have any address to be specified in the pointer at the time of declaration, you can
assign NULL value. It will provide a better approach.
In the most libraries, the value of the pointer is 0 (zero).
C Preprocessor and Macros
The C preprocessor is a macro preprocessor (allows you to define macros) that
transforms our program before it is compiled. These transformations can be the
inclusion of header file, macro expansions etc.
All preprocessing directives begin with a # symbol. For example,
#define PI 3.14
Some of the common uses of C preprocessor are:
Including Header Files: #include
The #include preprocessor is used to include header files to C programs.
For example,
#include <stdio.h>
Here, stdio.h is a header file. The #include preprocessor directive replaces the
above line with the contents of stdio.h header file.
That's the reason why we need to use #include <stdio.h> before we can use
functions like scanf() and printf().
We can also create your own header file containing function declaration and
include it in your program using this preprocessor directive.
#include "my_header.h"
Macros using #define
A macro is a fragment of code that is
given a name. You can define a macro
in C using the #define preprocessor
directive.
Here's an example.
#define c 299792458 // speed of light
Here, when we use c in our program, it
is replaced with 299792458
Example 1: #define preprocessor
#include <stdio.h>
#define PI 3.1415
int main()
{
float radius, area;
printf("Enter the radius: ");
scanf("%f", &radius);
// Notice, the use of PI
area = PI*radius*radius;
printf("Area=%.2f",area);
return 0;
}
Size of a pointer
The size of a pointer in C/C++ is not fixed. It depends upon different issues like
Operating system, CPU architecture etc.
Usually it depends upon the word size of underlying processor for example for a
32 bit computer the pointer size can be 4 bytes for a 64 bit computer the pointer
size can be 8 bytes. So for a specific architecture pointer size will be fixed.
The size of a pointer depends on which compiler you are using.
If you are using 16 bit it will be 2 bytes.
If you are using 32 bit it will be 4 bytes .
If you are using 64 bit it will be 8 bytes.
It is common to all the data types (*int,*char,*float, etc…).
Q) Study the following statement
1.#include <stdio.h>
2. int main()
3. {
4.
int *ptr, a = 10;
5.
ptr = &a;
6.
*ptr += 1;
7.
printf("%d,%d/n", *ptr, a);
8. }
What will be the output?
1.10, 10
2.10, 11
3.11, 10
4.11, 11
Q) Which symbol is used to declare a
pointer?
1.*
2.#
3.&
4.&&
Explanation: To declare a pointer variable, we
use a '*' symbol before the pointer variable.
Q) Why is a macro used in place of a function?
1.It reduces execution time.
2.It reduces code size.
3.It increases execution time.
4.It increases code size.
Explanation: Macro is used in place of a function because it reduces code
size, and very efficient.
Q) Which one is the correct description for the variable balance declared
below?
int ** balance;
1. Balance is a point to an integer
2. Balance is a pointer to a pointer to an integer
3. Balance is a pointer to a pointer to a pointer to an integer
4. Balance is an array of integer
Download