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

Programming in C1

The C programming language was developed at Bell Laboratories in the early 1970s by Dennis Ritchie. It was originally created for writing operating systems like UNIX. The name C comes from an earlier language called BCPL that was created by Ken Thompson. C is a general purpose, structured programming language that is portable, flexible, widely accepted, and efficient. It is well suited for system programming tasks like operating systems, language compilers, and drivers.

Uploaded by

Arun Baral
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
249 views

Programming in C1

The C programming language was developed at Bell Laboratories in the early 1970s by Dennis Ritchie. It was originally created for writing operating systems like UNIX. The name C comes from an earlier language called BCPL that was created by Ken Thompson. C is a general purpose, structured programming language that is portable, flexible, widely accepted, and efficient. It is well suited for system programming tasks like operating systems, language compilers, and drivers.

Uploaded by

Arun Baral
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 151

• THE HISTORY OF C

• The C language was developed at Bell Laboratories (now AT&


T’: American Telegraph & Telephone) in the early 1970’s by a
system programmer named Dennis Ritchie. It was written
originally for programming under an operating system called
UNIX, which itself was later rewritten almost entirely in C.
• Its name encrypted as C, derives from the fact that it is based
on an earlier version written by Ken Thompson, another Bell
Laboratories systems engineer. He adapted it from a language
that was known by the initials BCPL (Basic Combined
Programming Language). Thompson derived his programming
language name as B, the first of the initials BCPL.
Merits of C Programming Language
• In computer programming, different high-level programming languages are used. There are some
programming languages specially designed to write programs for special kind of solutions such as
simulations, games, space research, etc. Here are some merits of using C programming
language.

• C is general purpose programming language. You can generate different kind of software such as
billing system, games, utilities, word processor, etc.
• C is the structured programming language. It uses structured statements such as while, for, etc.
• C is a standardized programming language. For example ANSI (American National Standards
Institute) C is a standard programming language.
• The C language can run in any computer system. It is system independent.
• It has the small range of data types of detailed data manipulation statements with power data
definition methods.
• It is a language of few words such that the programmer can remember them easily.
• It is a highly efficient programming language since C compilers are generally able to translate
source code into efficient machine instructions.
Features of C Programming Language
• The C language was successful in developing UNIX operating systems.
It has special reasons to become very popular in the programming
world.
• Portability: This refers to the ability of a program to run in different
environments. Some programming language compilers such as
FORTRAN and Pascal could be used in those computers containing the
same compilers. Since, C languages have different compilers almost in
all systems, a C is termed as the most portable language.
• Flexibility: The C language combines the convenience and portable
nature of high-level language with the flexible nature.
• Wide acceptability: The C language is known to the entire world. The
language is suitable for projects at the system level and at the
application level.
• Get Started With C
To start using C, you need two things:
• A text editor, like Notepad, to write C code
• A compiler, like GCC, to translate the C code into a language that the computer will
understand
• There are many text editors and compilers to choose from. In this tutorial, we will
use an IDE (see below).

C Install IDE:
• An IDE (Integrated Development Environment) is used to edit AND compile the
code.
• Popular IDE's include Code::Blocks, Eclipse, and Visual Studio. These are all free,
and they can be used to both edit and debug C code.

• Note: Web-based IDE's can work as well, but functionality is limited.


Structure of C Program
• All human beings have a definite structure, i.e., head, neck,
and four limbs connected to a torso. Almost everything has a
definite structure. Likewise, in the case of programming
languages, all of them have a definite structure. These
structures have to be followed while writing the code.

• The structure of a C program can be mainly divided into six


parts, each having its purpose. It makes the program easy to
read, easy to modify, easy to document, and makes it
consistent in format.
• Example: Write a program to calculate our age.
In the following example, we'll calculate age concerning a year.
• Algorithm
You've to subtract the current year from your birth year and get
your age.
Let's implement this and check:
/** //Documentation
* file: age.c
* author: yourname
* description: program to find our age.
*/

#include <stdio.h> //Link


#define BORN 2000 //Definition
int age(int current); //Global Declaration
int main(void) //Main() Function
{
int current = 2021;
printf("Age: %d", age(current)); // %d is a format specifiar specifies the type of variable as decimal
return 0;
}
int age(int current) { //Subprograms
return current - BORN;
}
• Why use C?
• 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 Assemblers


• Language Compilers Text Editors
• Print Spoolers Network Drivers
• Modern Programs Databases
• Language Interpreters Utilities
• Before we study the basic building blocks of the C programming
language, let us look at a bare minimum C program structure so that we
can take it as a reference in the upcoming chapters.
• Hello World Example

• A C program basically consists of the following parts −


• Preprocessor Commands
• Functions
• Variables
• Statements & Expressions
• Comments
• Let us look at a simple code that would print the words "Hello World" −
• #include <stdio.h> Let us take a look at the various parts of the above
program −

The first line of the program #include <stdio.h> is a


• int main() { preprocessor command, which tells a C compiler to
include stdio.h file before going to actual compilation.
• /* my first program in C */
The next line int main() is the main function where the
• printf("Hello, World! \n"); program execution begins.

• The next line /*...*/ will be ignored by the compiler and it


has been put to add additional comments in the program.
• return 0; So such lines are called comments in the program.
• } The next line printf(...) is another function available in C
which causes the message "Hello, World!" to be
displayed on the screen.

The next line return 0; terminates the main() function and


returns the value 0.
• 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 −
• 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
• 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 */ = //comment


• 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. Here are
some examples of acceptable identifiers −

• mohd zara abc move_name a_123


• myname50 _temp j a23b9 retVal
• Keywords
• The following list shows the reserved words in C. These reserved words may not be
used as constants or variables or any other identifier names.


• 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. On the other hand, in the following
statement −
• fruit = apples + oranges; // get the total fruit
• no whitespace characters are necessary between fruit and =, or between = and
apples, although you are free to include some if you wish to increase readability.
• Data Types in C
In C programming, data types are declarations for
variables. This determines the type and size of data
associated with variables.
For example,

int myVar;
Here, myVar is a variable of int (integer) type. The size of
int is 4 bytes.

1 Basic Types
They are arithmetic types and are further classified into: (a) integer types and (b)
floating-point types.
2 Enumerated types:
They are again arithmetic types and they are used to define variables that can only
assign certain discrete integer values throughout the program.
3 The type void: The type specifier void indicates that no value is available.
4 Derived types
They include (a) Pointer types, (b) Array types, (c) Structure types, (d) Union types and
(e) Function types.
• In the C programming language, data types refer to an extensive system used for
declaring variables or functions of different types. The type of a variable determines
how much space it occupies in the storage and how the bit pattern stored is
interpreted.
• In C, there are several data types that you can use, including:

• int: This is used to store integer values. For example, int x = 10;
• float: This is used to store decimal values with single precision. For example, float y =
3.14;
• double: This is used to store decimal values with double precision. For example,
double z = 2.71828;
• char: This is used to store a single character. For example, char c = 'A';
• void: This is used to represent the absence of a type. For example, void function() { ...
}
• There are many other data types that you can use in C, but these are some of the
most common ones.
C Variables
• Variables are containers for storing data values.
• In C, there are different types of variables (defined with different
keywords), for example:

• int - stores integers (whole numbers), without decimals, such as


123 or -123
• float - stores floating point numbers, with decimals, such as
19.99 or -19.99
• char - stores single characters, such as 'a' or 'B'. Char values
are surrounded by single quotes
• Declaring (Creating) Variables
• To create a variable, specify the type and assign it a value:
Syntax
• type variableName = value;
• (Where type is one of C types (such as int), and variableName is the name of the variable (such as x or
myName). The equal sign is used to assign a value to the variable.
• So, to create a variable that should store a number, look at the following example:)

• Create a variable called myNum of type int and assign the value 15 to it:

Note: If you assign a new value to an existing variable, it will overwrite the previous
• int myNum = 15; value:
int myNum = 15; // myNum is 15
myNum = 10; // Now myNum is 10
• Constants
• If you don't want others (or yourself) to override existing
variable values, use the const keyword (this will declare the
variable as "constant", which means unchangeable and read-
only):
• Example
• const int myNum = 15; // myNum will always be 15
• myNum = 10; // error: assignment of read-only variable 'myNum'
• You should always declare the variable as constant when you have
values that are unlikely to change:
• const int minutesPerHour = 60;
• const float PI = 3.14;
• Operators
• Operators are used to perform operations on variables and
values.
• In the example below, we use the + operator to add together
two values:
• intmyNum = 100 + 50;
• C divides the operators into the following groups:
• Arithmetic operators Assignment operators
• Comparison operators Logical operators
• Bitwise operators
• Assignment Operators
• Assignment operators are used to assign values to variables.
• In the example below, we use the assignment operator (=) to
assign the value 10 to a variable called x:
• example program:
• #include <stdio.h>
int main() {
int x = 10;
x += 5;
printf("%d", x);
return 0;
}
o/p: 15
Example programs:
• WAP to print your name:
#include <stdio.h>
int main()
{
printf("My Name is YourName!");
return 0;
}
Data types and format
specifier example #include <stdio.h>

int main() {
// Create variables
int myNum = 5; // Integer (whole number)
float myFloatNum = 5.99; // Floating point number
char myLetter = 'D'; // Character

// Print variables
printf("%d\n", myNum);
printf("%f\n", myFloatNum);
printf("%c\n", myLetter);
return 0;
}
• write a c program to input your name and display it to the user.

#include <stdio.h>
void main()
{
char name[30];
printf("Input Your name: ");
scanf("%s", name);
printf("%s",name);
}
• Booleans
Very often, in programming, you will need a data type that can only have one of
two values, like:
YES / NO
ON / OFF
TRUE / FALSE
For this, C has a bool data type, which is known as booleans.
Booleans represent values that are either true or false.
In C, the bool type is not a built-in data type, like int or char.
It was introduced in C99, and you must import the following header file to use it:
we must have to use : #include <stdbool.h> for booleans
Example
// Create boolean variables
bool isProgrammingFun = true;
bool isFishTasty = false;
// Return boolean values
printf("%d", isProgrammingFun); // Returns 1 (true)
printf("%d", isFishTasty); // Returns 0 (false)
Exercise:

• Insert the missing part of the code below to output "Hello


World!".

• int () {
("Hello World!");
• return 0;
• }
• Comments in C are written with special characters. Insert the
missing parts:

This is a single-line comment


This is a multi-line comment

• Create a variable named myNum and assign the value 50 to it.

• Use the correct format specifier to output the value of myNum:


int myNum = 15;
printf(" ", myNum);
• Display the sum of 5 + 10, using two variables: x and y.
= ;
int y = 10;
printf("%d", x + y);

Fill in the missing parts to create three variables of the same type,
using a comma-separated list:

x=5 y=6 z = 50;


printf("%d", x + y + z);
• Add the correct data type for the following variables:
myNum = 5;
myFloatNum = 5.99;
myLetter = 'D';
• C - Decision Making
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.
Show below is the general form of a typical decision making structure found in most
of the programming languages −
• Conditions and If Statements
You have already learned that C supports the usual logical conditions from mathematics:
Less than: a < b
Less than or equal to: a <= b
Greater than: a > b
Greater than or equal to: a >= b
Equal to a == b
Not Equal to: a != b
You can use these conditions to perform different actions for different decisions.

C has the following conditional statements:


Use if to specify a block of code to be executed, if a specified condition is true
Use else to specify a block of code to be executed, if the same condition is false
Use else if to specify a new condition to test, if the first condition is false
Use switch to specify many alternative blocks of code to be executed.
• The if Statement
• Use the if statement to specify a block of code to be executed if
a condition is true.

• Syntax
if (condition) {
// block of code to be executed if the condition is true
}
classwork:
test two values to find out if 20 is greater than 18. If the
condition is true, print some text:
#include <stdio.h> We can also test variables:

int main() { Example::


if (20 > 18) {
printf("20 is greater than 18"); int x = 20;
} int y = 18;
return 0; if (x > y) {
} printf("x is greater than y");
}

In the example above we use two variables, x and y, to test whether x is greater than
y (using the > operator). As x is 20, and y is 18, and we know that 20 is greater than
18, we print to the screen that "x is greater than y".
example program
#include <stdio.h>
int main () {
/* local variable definition */
int a = 10;
/* check the boolean condition using if statement */
if( a < 20 ) {
/* if condition is true then print the following */
printf("a is less than 20\n" );
}
printf("value of a is : %d\n", a);
return 0;
}
classwork:

WAP to print if given value is less then, equal to, greater then by using if statement.
(by using multiple if statement.)
Check if a character is a vowel or consonant?

Program to check if a number is positive or negative.


• The if..else Statement
Use the else statement to specify a block of code to be executed
if the condition is false.
Syntax:
if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}
• The if statement can be extended
with an else clause, which allows
you to specify a block of code to
be executed if the expression is
false.
if (condition) {
// block of code to be executed if the
condition is true
} else {
// block of code to be executed if the
condition is false
}
Example
int time = 20;
if (time < 18) {
printf("Good day.");
} else {
printf("Good evening.");
}
// Outputs "Good evening."
In the example above, time (20) is greater than 18, so the condition is false. Because of this, we move on to the
else condition and print to the screen "Good evening". If the time was less than 18, the program would print
"Good day".
• #include <stdio.h>
in this example, the value of x
is 10, which is greater than 0,
• int main(void) { so the code inside the first set
• int x = 10; of curly braces is executed,
• if (x > 0) { and the output is "x is positive".
If the value of x were -5, for
• printf("x is positive\n"); example, then the code inside
• } else { the second set of curly braces
• printf("x is not positive\n"); would be executed, and the
output would be "x is not
• } positive".
• return 0;
• }
#include <stdio.h>
int main ()
/* local variable definition */
int a = 100;
/* check the boolean condition */
if( a < 20 ) {
/* if condition is true then print the following */
printf("a is less than 20\n" );
} else {
/* if condition is false then print the following */
printf("a is not less than 20\n" );
When the above code is compiled and executed, it produces
} the following result −
printf("value of a is : %d\n", a);
a is not less than 20;
return 0; value of a is : 100
}
1) Fill in the blanks to divide 10 by 5, and print the result.
int x = 10;
int y = 5;
printf(" ", x y);
2) Use the correct operator to increase the value of the variable x by 1.
int x = 10;
x ;
3) Use the addition assignment operator to add the value 5 to the variable x.
int x = 10;
x 5;
• Print "Hello World" if x is greater than y.
int x = 50;
int y = 10;
(x y) {
printf("Hello World");
}
Print "Hello World" if x is equal to y.
int x = 50;
int y = 50;
(x y) {
printf("Hello World");
}
Print "Yes" if x is equal to y, otherwise print "No".
int x = 50;
int y = 50;
(x y) {
printf("Yes");
} {
printf("No");
}
Print "1" if x is equal to y, print "2" if x is greater than y, otherwise print "3".
int x = 50;
int y = 50;
(x y) {
printf("1");
} else if (x y) {s
printf("2");
} {
printf("3");
}
The else if Statement
• Use the else if statement to specify a new condition if the first
condition is false.
Syntax
if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is true
} else {
// block of code to be executed if the condition1 is false and condition2 is false
}
Example :1 Example explained:

int time = 22; In the example above, time (22) is greater than 10, so the first condition is
if (time < 10) { false. The next condition, in the else if statement, is also false, so we
move on to the else condition since condition1 and condition2 is both false
printf("Good morning."); - and print to the screen "Good evening".
} else if (time < 20) {
However, if the time was 14, our program would print "Good day."
printf("Good day.");
Another Example
} else { This example shows how you can use if..else to find out if a
printf("Good evening."); number is positive or negative:

} Example
// Outputs "Good evening." int myNum = - 10; // Is this a positive or negative number?

if (myNum > 0) {
printf("The value is a positive number.");
} else if (myNum < 0) {
printf("The value is a negative number.");
} else {
printf("The value is 0.");
}
Switch Case Statememt
• Switch Statement
• Instead of writing many if..else statements, you can use the
switch statement.
• The switch statement selects one of many code blocks to be
executed:
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
Following program illustrates the use of switch:

#include <stdio.h>
int main() {
int num = 8;
switch (num) {
case 7:
printf("Value is 7");
break;
case 8:
printf("Value is 8");
break;
case 9:
printf("Value is 9");
break;
default:
printf("Out of range");
break;
}
return 0;
} The Output = Value is 8
For example, we consider the following program which defaults:

#include <stdio.h>
int main() {
int language = 10;
switch (language) {
case 1:
printf("C#\n");
break;
case 2:
printf("C\n");
break;
case 3:
printf("C++\n");
break;
default:
printf("Other programming language\n");}}
Output: Other programming
language
Looping
• The computer has the ability to peform a set of instructions
repetedly. This involves repeating some portion of program
either for a specified number of iteams or till a given condition
is satisfied. this repetitive operation is done by a loop control
statement.
• Looping(or iteration or repetition) is an operation that repeats the execution of statement until a
certain condition is satisfied.
• There are three loops.:
for statement
while ststememt
do.while statement
• for loop
THe for loop is the most commenly used statement in c this loop
consist of three expression

Syntax ::
for (statement 1; statement 2; statement 3) {
// code block to be executed
}
Statement 1: is executed (one time) before the execution of the code block.
Statement 2: defines the condition for executing the code block.
Statement 3: is executed (every time) after the code block has been
executed.
Example:
#include<stdio.h>
int i;
for (i = 0; i < 5; i++) {
printf("%d\n", i);
}
Example explained:
Statement 1: sets a variable before the loop starts (int i = 0).
Statement 2: defines the condition for the loop to run (i must be less than 5). If the
condition is true, the loop will start over again, if it is false, the loop will end.
Statement 3: increases a value (i++) each time the code block in the loop has been
executed.
Example 1: for loop
#include <stdio.h>
// Print numbers from 1 to 10
void main()
#include <stdio.h> {
int i;
int main() { printf("The first 10 natural numbers are:\
int i; n");
for (i = 1; i < 11; ++i) for (i=1;i<=10;i++)
{
{
printf("%d ",i);
printf("%d ", i); }
} printf("\n");
return 0; }
}
#include <stdio.h>
int main()
{
int j, sum = 0;
printf("The first 10 natural number is :\n");
for (j = 1; j <= 10; j++)
{
sum = sum + j;
printf("%d ",j);
}
printf("\nThe Sum is : %d\n", sum);
}

The first 10 natural number is :


1 2 3 4 5 6 7 8 9 10
The Sum is : 55
Another Example
This example will only print even values between 0 and 10:

#include <stdio.h>
int main() {
int i;
for (i = 0; i <= 10; i = i + 2) {
printf("%d\n", i);
}
return 0;
}
Nested Loops

It is also possible to place a loop inside another loop. This is called


a nested loop.

The "inner loop" will be executed one time for each iteration of the
"outer loop":
while loop:
The second type of loop statement is while loop. while loop first
checks whether the initial condition is true of false and finding it to
be true, it will either the loop and execute the statement.
syntax:

while (condition) {
statement_1;
........
statement_n;
increment/decrement;
}
Example When the above code is compiled and
executed, it produces the following
#include<stdio.h> result −

int main(){ value of a: 0


value of a: 1
/* local variable definition */ value of a: 2
value of a: 3
int i = 0; value of a: 4
/* while loop execution */
while (i < 5) {
printf("%d\n", i);
i++;
}
return 0;
}
The Do/While Loop
The do/while loop is a variant of the while loop. This loop will
execute the code block once, before checking if the condition is
true, then it will repeat the loop as long as the condition is true.

Syntax
do {
// code block to be executed
}
while (condition);
• The example below uses a do/while loop. The loop will always
be executed at least once, even if the condition is false, because
the code block is executed before the condition is tested:
Example
#include<stdio.h>
int i = 0;
do {
printf("%d\n", i);
i++;
}
while (i < 5);
Assignment
• write a program to read the principal rate of interest and number
of years and find the simple intreast and amount.
• A C program to print Fibonacci series i.e:0 1 1 2 3 5 8... upto nth
term.
• write a program to check weather given number is prime or not.
#include <stdio.h>

int main() {
float principal, rate, time, simple_interest, amount;

printf("Enter the principal amount: ");


scanf("%f", &principal);
printf("Enter the rate of interest: ");
scanf("%f", &rate);
printf("Enter the time period (in years): ");
scanf("%f", &time);

simple_interest = (principal * rate * time) / 100;


amount = principal + simple_interest;

printf("Simple Interest: %.2f\n", simple_interest);


printf("Amount: %.2f\n", amount);

return 0;
}
fibonacci series
#include <stdio.h>
int main() {
int n, i, t1 = 0, t2 = 1, next_term;
printf("Enter the number of terms: ");
scanf("%d", &n);
printf("Fibonacci series: ");
for (i = 1; i <= n; i++) {
printf("%d,", t1);
next_term = t1 + t2;
t1 = t2;
t2 = next_term;
}
return 0;
}
• #include<stdio.h>
• int main()
• {
• int i,fact=1,number;
• printf("Enter a number: ");
• scanf("%d",&number);
• for(i=1;i<=number;i++){
• fact=fact*i;
• }
• printf("Factorial of %d is: %d",number,fact);
• return 0;
• }
•Array and string.
(VVI)
An array is defined as the collection of similar type of data items
stored at contiguous memory locations. Arrays are the derived
data type in C programming language which can store the
primitive type of data such as int, char, double, float, etc. It also
has the capability to store the collection of derived data types,
such as pointers, structure, etc. The array is the simplest data
structure where each data element can be randomly accessed by
using its index number.
Declaring Arrays
To declare an array in C, a programmer specifies the type of the
elements and the number of elements required by an array as
follows −
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. For example, to declare a 10-element array called
balance of type double, use this statement −
Example:
int balance[10];
Here balance is a variable array which is sufficient to hold up to 10 int numbers.
Declaration of C Array
We can declare an array in the c language in the following way.

data_type array_name[array_size];

Now, let us see the example to declare the array.


int marks [5];

Here, int is the data_type, marks are the array_name, and 5 is the
array_size.
Initialization of C Array

The simplest way to initialize an array is by using the index of


each element. We can initialize each element of the array by
using the index. Consider the following example.

marks[0]=80;//initialization of array
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;
Access the Elements of an Array:
To access an array element, refer to its index number.

Array indexes start with 0: [0] is the first element. [1] is the
second element, etc.

This statement accesses the value of the first element [0] in


myNumbers:

int myNumbers[] = {25, 50, 75, 100};


#include <stdio.h>
int main() {
int myNumbers[] = {25, 50, 75, 100};
printf("%d", myNumbers[0]);
return 0;
}
Change an Array Element
To change the value of a specific element, refer to the index
number:
myNumbers[0] = 33;
#include <stdio.h>
int main() {
int myNumbers[] = {25, 50, 75, 100};
myNumbers[0] = 33;
printf("%d", myNumbers[0]);
return 0;
}
Set Array Size
Another common way to create arrays, is to specify the size of the
array, and add elements later:

#include <stdio.h>
int main() {
// Declare an array of four integers:
int myNumbers[4]; int myNumebrs[4]: {25, 50, 75, 100}
// Add elements to it
myNumbers[0] = 25;
myNumbers[1] = 50;
myNumbers[2] = 75;
myNumbers[3] = 100;
printf("%d\n", myNumbers[0]); Using this method, you should know the size of the array, in order
return 0; for the program to store enough memory.
}
You are not able to change the size of the array after creation.
#include <stdio.h>
int main() {
int myNumbers[] = {25, 50, 75, 100};
int i;
for (i = 0; i < 4; i++) {
printf("%d\n", myNumbers[i]);
}
return 0;
}
Write a program in C to store elements in an array and print it.
// Program to take 5 values from the user
and store them in an array
// Print the elements stored in the array

#include <stdio.h>
int main() {
int values[5];
printf("Enter 5 integers: ");
// taking input and storing it in an array
for(int i = 0; i < 5; ++i) {
scanf("%d", &values[i]);
}
printf("Displaying integers: ");
// printing elements of an array
for(int i = 0; i < 5; ++i) {
printf("%d\n", values[i]);
}
return 0;
}
• Classwork:
Write a C program to ask ten numbers from the user and
display them using arrey.

.WAP to read salaries of 50 employees and count the number


of employees getting a salary from 5000 to 10000.
Multidimensional Arrays
In the previous chapter, you learned about arrays, which is also
known as single dimension arrays. These are great, and
something you will use a lot while programming in C. However, if
you want to store data as a tabular form, like a table with rows and
columns, you need to get familiar with multidimensional arrays.

A multidimensional array is basically an array of arrays.

Arrays can have any number of dimensions. In this chapter, we will


introduce the most common; two-dimensional arrays (2D).
• Two-Dimensional Arrays
• A 2D array is also known as a matrix (a table of rows and
columns).

• To create a 2D array of integers, take a look at the following


example:
• int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} };

The first dimension represents the number of rows [2], while the
second dimension represents the number of columns [3]. The
values are placed in row-order, and can be visualized like this:
• Access the Elements of a 2D Array
• To access an element of a two-dimensional array, you must
specify the index number of both the row and column.

• This statement accesses the value of the element in the first row
(0) and third column (2) of the matrix array.
#include <stdio.h>
int main() {
int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} };
printf("%d", matrix[0][2]);
return 0;
}

the output = ????


Change Elements in a 2D Array
To change the value of an element, refer to the index number of
the element in each of the dimensions:

The following example will change the value of the element in the
first row (0) and first column (0):
#include <stdio.h>
int main() {
int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} };
matrix[0][0] = 9;

printf("%d", matrix[0][0]); // Now outputs 9 instead of 1

return 0;
}
Loop Through a 2D Array
To loop through a multi-dimensional array, you need one loop
for each of the array's dimensions.
The following example outputs all elements in the matrix array:
#include <stdio.h>
int main() {
int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} };

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

return 0;
}

Output : ???????????
#include <stdio.h>

int main()
{
int salary[50],i,n,count=0;

printf("\n Input salary of 300 persons:- ");


for(i=0;i<50;i++)
scanf("%d",&salary[i]);
for(i=0;i<50;i++)
{
if(salary[i]>1000 && salary[i]<15000)
count++;
}
printf("There are %d persons whose salary is in between 1000 and
15000",count);

return 0;
}
String:(character Array)
We can represent character easily by char data type whereas the
string is a group of characters that can only be represented by
character array. To represent a character, we use char data type.
declaration:
char X;
we can only store only one character at a time which is always
enclosed by single quote.
initialization:

char x = ‘a’
The following declaration and initialization create a string consisting of the
word "Hello". To hold the null character at the end of the array, the size of the
character array containing the string is one more than the number of
characters in the word "Hello."
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
If you follow the rule of array initialization then you can write the above
statement as follows −

char greeting[] = "Hello";


Following is the memory presentation of the above defined string in C/C++ −
Actually, you do not place the null character at the end of a
string constant. The C compiler automatically places the '\0' at
the end of the string when it initializes the array. Let us try to
print the above mentioned string −
#include <stdio.h>
int main () {
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
printf("Greeting message: %s\n", greeting );
return 0;
}
note: %s refers to a string
C Copy String: strcpy() C String Concatenation: strcat()
The strcpy(destination, source) function copies The strcat(first_string, second_string)
the source string in destination. function concatenates two strings and result
is returned to first_string.
#include<stdio.h>
#include <string.h> #include<stdio.h>
int main(){ #include <string.h>
char ch[20]={'H', 'e', 'l', 'l', 'o','\0'}; int main(){
char ch2[20]; char ch[10]={'h', 'e', 'l', 'l', 'o', '\0'};
strcpy(ch2,ch); char ch2[10]={'c', '\0'};
printf("Value of second string is: %s",ch2); strcat(ch,ch2);
return 0; printf("Value of first string is: %s",ch);
} return 0;
Output: }
• Value of second string is: Hello Output:
• Helloc
C Compare String: strcmp()
The strcmp(first_string, second_string) function compares two string and returns 0 if
both strings are equal.
/*Here, we are using gets() function which reads string from the console.*/

#include<stdio.h>
#include <string.h>
int main(){
char str1[20],str2[20];
printf("Enter 1st string: ");
gets(str1);//reads string from console
printf("Enter 2nd string: ");
gets(str2);
if(strcmp(str1,str2)==0)
printf("Strings are equal");
else
printf("Strings are not equal");
return 0;
}
C Reverse String: strrev()
The strrev(string) function returns reverse of the given string. Let's see a simple example of strrev()
function.

#include<stdio.h>
#include <string.h>
int main(){
char str[20];
printf("Enter string: ");
gets(str);//reads string from console
printf("String is: %s",str);
printf("\nReverse String is: %s",strrev(str));
return 0;
}
Output:

Enter string: hello


String is: hello
Reverse String is: olleh
programs:
WAP c program to input a string and count the number of vowels
contaning in the string.
WAP to input a word and determine weather it’s palindrome or
not?
WAP to imput the names of ‘N’ numbers of students and sort
them in alphabetical order.
#include <stdio.h>
void main()
{
char a[100];
int len,i,vow=0;

printf("\nENTER A STRING: ");


gets(a);
len=strlen(a);
for(i=0;i<len;i++)
{
if(a[i]=='a' || a[i]=='A' || a[i]=='e' || a[i]=='E' || a[i]=='i' || a[i]=='I' || a[i]=='o' || a[i]=='O' || a[i]=='u' || a[i]=='U')
vow=vow+1;
}
printf("\nTHERE ARE %d VOWELS IN THE STRING",vow);

}
void main(){
char str1[] = "First";
char str2[20];
strcpy(str2,str1);

printf("%s%s",str1,str2);
printf("%d",(str1!=str2)); // (!= relational operator if = 0 if !
= 1)
printf("%d",strcmp(str1,str2));
C String Length: strlen() function
The strlen() function returns the length of the given string. It doesn't count null character '\0'.

#include<stdio.h>
#include <string.h>
int main(){
char ch[20]={'h', 'e', 'l', 'l', 'o', '\0'};
printf("Length of string is: %d",strlen(ch));
return 0;
}
Output: 5
#include <stdio.h>
#include <string.h>
int main () {
Output: ????
char str1[12] = "Hello";
char str2[12] = "World";
char str3[12];
int len ;
/* copy str1 into str3 */
strcpy(str3, str1);
printf("strcpy( str3, str1) : %s\n", str3 );
/* concatenates str1 and str2 */
strcat( str1, str2);
printf("strcat( str1, str2): %s\n", str1 );
/* total lenghth of str1 after concatenation */
len = strlen(str1);
printf("strlen(str1) : %d\n", len );
return 0;
}
Functions
• Functions are the self-contained program that contains
several block of statement which performs the defined task.
In C language, we can create one or more functions
according to the requirements.

• sually, In C programs flows from top left to right bottom of


main() functions. We can create any number of functions
below that main() functions. These function are called from
main() function. Requirement while creating a functions.
a) Declare a function
b) Call statement
c) Definition of function.
After the function is called from the main(), the flow of control
will return to the main() function.
Advantage:
1. Big programs can be divided into smaller module using
functions.
2. Program development will be faster.
3. Program debugging will be easier and faster.
4. Use of functions reduce program complexity.
5. Program length can be reduced through code reusability.
6. Use of functions enhance program readability.
7. Several developer can work on a single project.
8. Functions are used to create own header file i.e mero.h
9. Functions can be independently tested.
#include <stdio.h>
int area (void); declaration
int main()
{
int a;
a = area(); function call
printf("area is %d",a);
return 0;
}
int area()
{
int l,b,ar;
printf("Enter length and breadth");
scanf("%d%d",&l,&b); Defination
ar = l*b;
return ar;
}
WAP to calculate simple interest using function
#include <stdio.h>
float interest(void); //function declaration
int main() WAP to calculate area of rectangle using function.
{ float si; #include <stdio.h>
si=interest(); //function call Int area (void);
printf("Simple interst is %.2f\n",si); int main()
return 0; {
} int a;
float interest() //function definition a = area();
{ printf(“area is %d”,a);
float p,t,r,i; return 0;
printf("Enter Principal, Time and Rate"); }
scanf("%f%f%f",&p,&t,&r); int area()
i=(p*t*r)/100; {
return i; //function return value int l,b,ar;
} printf(“Enter length and breadth”);
scanf(“%d%d”,&l,&b);
ar = l*b
return ar;
}
• Pointer (v-imp)

• Pointers in C are similar to as other variables that we use to hold


the data in our program but, instead of containing actual data,
they contain a pointer to the address (memory location) where
the data or information can be found.
• These is an important and advance concept of C language
since, variables names are not sufficient to provide the
requirement of user while developing a complex program.
However, use of pointers help to access memory address of that
entities globally to any number of functions that we use in our
program.
Why should we use Pointers? We can display this address by following program C
program
Understanding pointer thoroughly
Let us consider, an integer variable #include
age which value is 16, which is int main()
{
declared as: int age=16;
int age =16; printf("Address of age is %u”, &age);
This declaration tells the C compiler: printf(“Value of age is %d”, age);
return 0;
• To reserve space in memory to hold }
the integer value. Output of the above program is
• Associate the name ‘age’ with this
Address of age is 65676
memory location.
• Store the value 16 at this location. Value of age is 16

[Note: &age return memory address, %u denotes unsigned integer generally used for large
positive numbers i.e address of age in this case. Memory address may vary with
computers. Same program may give different memory location but should give same value]
Importance of Pointer.
While using several numbers of functions in C program, every
functions should be called and value should be passed locally.
However, using pointer variable, which can access the address
or memory location and points whatever the address (memory
location) contains.
Pointer declaration

Data_type *variable_name

Eg, int *age;


Advantages
1. It helps us to access a variable that is not defined within a function.
2. It helps to reduce program length and complexity i.e. faster program
execution time.
3. It is more convenient to handle datas.
4. It helps to return one or more than one value from the functions.

Disadvantages / cons / Demerits of Pointes in C


Comparatively, pointers variables are slower than any other variables.
Memory leak can be a major issue if dynamically allocated memory are not
freed on time.
If Pointers variable are not declared that it may lead to segmentation fault.
Declaration of Pointer Variable

• Syntax:
• datatype *pointer_varible;
For eg:
int *a;
char *b;
float *c;
• Simple program example of pointers in C
#include<stdio.h>
int main()
Output of the above program is
{
Address of age is 65676
int age=16, *a;
Value of age is 16
a = &age;
printf("Address of age is %p\n”, (void*)a);
printf(“Value of age is %d\n”, *a);
return 0;
}
[Note: %p format specifier is used for printing the address to which pointer
points in C]
• Explanation of above program
• In C, the asterisk (*) is used to declare a variable as a pointer, and also to dereference a
pointer variable, which means accessing the value stored in the memory location pointed to by
the pointer.

• In the code, ‘a’ is declared as a pointer to an integer by using the * in the declaration int *a;.
This means that a can hold the address of an integer variable.

• Later in the code, ‘a’ is assigned the address of the age variable by using the & operator to get
the address of ‘age’: ‘a = &age;’. This means that a now points to the memory location where
age is stored.

• Finally, to print the value of age, the code uses the dereference operator * to access the value
stored in the memory location pointed to by ‘a’: ‘printf("Value of age is %d", *a);’.

• So, the ‘*a’ in the code is used to access the value of the variable pointed to by ‘a’. Without the
* operator, ‘a’ would simply represent the memory address of the variable, not its value.
Recursive functions: (V.Imp)

Those function which calls itself is known as recursive function


and the concept of using recursive functions to repeat the
execution of statements as per the requirement is known as
recursion. The criteria for recursive functions are:

• The function should call itself.


• There should be terminating condition so that function calling
will not be for infinite number of time.
WAP to calculate factorial of a given number using recursion/recursive function. (V.IMP)
#include<stdio.h>
int fact (int);
int main()
{
int n,f;
printf("Enter any number");
scanf("%d",&n); note:
f = fact(n); example : given number is 4:
printf("factorial is %d",f); 4 x fact(4-1 = 3) it will call fact function again
return 0; next: 3 x fact(3-1 = 2) {4*3*2*1= 24}
} next: 2 x fact(2-1 = 1)
int fact (int n)
{
if (n<=1)
return 1;
else
return (n*fact(n-1));
}
Write a program to enter ten integer numbers into an array, sort
and display them in ascending order.
array vs structure vs union in C::
Arrays are used to represent a group of data items that belong to
the same type, such as 'int' for integers or ‘float’ for floating value
i.e. decimal numbers. We cannot use an array if we want to
represent a collection of data items of several data types using a
same name. Which means, if we create an array as int then it
cannot hold floating values and strings. This limitation is eradicated
by structure and union in C.
• Introduction of Structure in C
• A structure is a collection of one or more variables, that may be
same or different data types, grouped together under a
single(same) name for easy handling. It is a convenient tool for
handling a group of logically related data items. Structures help
to organize complex data in a more meaningful and logical way.
Thus, can be used in large program design, because they allow
a group of related variables/items to be treated as a single unit.
They are also known as constructed datatypes.
• [Note: In some language, structures are known as records and
the elements of structures are known as
fields/members/components.]
• Declaration of Structure in C
• Keyword used by Structure is ‘struct’
• Syntax struct student
struct structure_name {
char name [35];
int age;
{ char address [50];
float Percentage;
data_type member_1; } s1, s2;

data_type member_2;
.
data_type member_n;
}structure_variables;
struct Student
{
char name[25];
int age;
char branch[10];
// F for female and M for male
char gender;
};

Here struct Student declares a structure to hold the details of a student which
consists of 4 data fields, namely name, age, branch and gender. These fields are
called structure elements or members.

Each member can have different datatype, like in this case, name is an array of
char type and age is of int type etc. Student is the name of the structure and is
called as the structure tag.
Let's see the example to define a structure for an entity employee in c.
Struct Keyword
struct employee tag, struct-tag
{ int id;
char name[10]; Member
float salary;
};
• How to create a structure?
• ‘struct’ keyword is used to create a structure. Following is an
example.
struct address
{
char name[50];
char street[100];
char city[50];
char state[20];
int pin;
};
C Structure example
Let's see a simple example of structure in C language.

#include<stdio.h>
#include <string.h>
struct employee
{ int id;
char name[50];
}e1; //declaring e1 variable for structure
int main( )
{
//store first employee information
e1.id=01;
strcpy(e1.name, "Sudip kattel"); //copying string into char array
//printing first employee information
printf( "employee 1 id : %d\n", e1.id);
printf( "employee 1 name : %s\n", e1.name);
return 0;
}
#include<stdio.h>
#include <string.h>
struct employee
{ int id;
char name[50];
float salary;
}e1,e2; //declaring e1 and e2 variables for structure
int main( )
{
//store first employee information
e1.id=01;
strcpy(e1.name, "Sudip Kattel");//copying string into char array
e1.salary=56000;

//store second employee information


e2.id=02;
strcpy(e2.name, "James Bond");
e2.salary=126000;

//printing first employee information


printf( "employee 1 id : %d\n", e1.id);
printf( "employee 1 name : %s\n", e1.name);
printf( "employee 1 salary : %f\n", e1.salary);

//printing second employee information


printf( "employee 2 id : %d\n", e2.id);
printf( "employee 2 name : %s\n", e2.name);
printf( "employee 2 salary : %f\n", e2.salary);
return 0;
}
Introduction of union in C
• Union is a user-defined data type. It is a concept borrowed from
structures and therefore follow this same syntax structures.
• the major differences between them is in terms of storage. In structures,
each member has its own storage location, whereas all the members of a
union use the same location. Which means, although a union may
contain many members of different types, it can handle only one member
at a time.
• Every union member takes memory that contains a variety of data item or
objects. So that, the union members share space thus helps in conserving
memory.
• The memory size used by a union variable is the size used by the
member with the largest size. Since, one memory space is shared by all
data members, only one data member can be accessed at a time.
• Declaration of Union in C Let us create a union to illustrate the above-mentioned
• Keyword used by Union is ‘union’ declaration,

• Syntax union student


{
char name [35];
union union_name int age;
char address [50];
{ float Percentage;
} s1, s2;
data_type member_1;
data_type member_2;
.
data_type member_n;
}union_variable;
Structures in C is a user-defined data type available in C Union in C is a special data type available in C that allows
that allows to combining of data items of different kinds. storing different data types in the same memory location. You
Structures are used to represent a record. 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
Defining a structure: To define a structure, you must use purposes.
the struct statement. The struct statement defines a new
data type, with more than or equal to one member. The Defining a Union: To define a union, you must use the union
format of the struct statement is as follows: statement in the same way as you did while defining a
struct [structure name] structure. The union statement defines a new data type with
{ more than one member for your program. The format of the
member definition; union statement is as follows:
union [union name]
member definition; {
... member definition;
member definition; member definition;
}; member definition;
(OR) };
struct [structure name] (OR)
{ union [union name]
{
member definition;
member definition;
member definition; member definition;
... ...
member definition; member definition;
}structure variable declaration; }union variable declaration;
Structure Union

We use the struct statement to define a We use the union keyword to define a union.
structure.
Every member is assigned a unique memory All the data members share a memory location.
location.
Change in the value of one data member does Change in the value of one data member
not affect other data members in the structure. affects the value of other data members.

You can initialize multiple members at a time. You can initialize only the first member at once.

A structure can store multiple values of the A union stores one value at a time for all of its
different members. members
A structure’s total size is the sum of the size of A union’s total size is the size of the largest
every data member. data member.
Users can access or retrieve any member at a You can access or retrieve only one member at
time. a time.
Example program::

#include <stdio.h> Output ???


#include <string.h>
union student
{
char name[20];
char subject[20];
float percentage;
}record;
int main()
{
strcpy(record.name, "Raju");
strcpy(record.subject, "Computer");
record.percentage = 86.50;
printf(" Name : %s \n", record.name);
printf(" Subject : %s \n", record.subject);
printf(" Percentage : %f \n", record.percentage);
return 0;
}
Difference between Array and Structure
• Past questions:
1) write a c program to calculate 2 number using pointer.
#include<stdio.h>
int main() {
int *ptr1, *ptr2;
int num;

printf("\nEnter two numbers : ");


scanf("%d %d", ptr1, ptr2);

num = *ptr1 + *ptr2;

printf("Sum = %d", num);


return (0);
}
Write a structure in C to initialize item, quantity and rate and calculate total amount.
#include <stdio.h>

struct Item {
char name[50];
int quantity;
float rate;
};

float calculate_total_amount(struct Item item) {


float total_amount = item.quantity * item.rate;
return total_amount;
}

int main() {
struct Item item1;

// Initialize values for item1


strcpy(item1.name, "Apple");
item1.quantity = 5;
item1.rate = 1.25;

// Calculate total amount for item1


float total_amount1 = calculate_total_amount(item1);

printf("Item name: %s\n", item1.name);


printf("Quantity: %d\n", item1.quantity);
printf("Rate: %.2f\n", item1.rate);
printf("Total amount: %.2f\n", total_amount1);

return 0;
Write a function simple(p,t,r) in C to compute Simple Interest.
#include<stdio.h>
int main()
{
int p,r,t,int_amt;
printf("Input principle, Rate of interest & time to find simple interest: \n");
scanf("%d%d%d",&p,&r,&t);
int_amt=(p*r*t)/100;
printf("Simple interest = %d",int_amt);
return 0;
}
File Handling in C
In programming, we may require some specific input data to be
generated several numbers of times.Sometimes, it is not enough
to only display the data on the console. The data to be displayed
maybe very large, and only a limited amount of data can be
displayed on the console, and since the memory is volatile, it is
impossible to recover the programmatically generated data again
and again.However, if we need to do so, we may store it onto the
local file system which is volatile and can be
accessed every time. Here, comes the need of file handling in C.
• File handling in C enables us to create, update, read, and delete
the files stored on the local file
• system through our C program. The following operations can be
performed on a file.

• • Creation of the new file


• • Opening an existing file
• • Reading from the file
• • Writing to the file
• • Deleting the file
• There are 2 kinds of files in which data can be stored in 2 ways
either in characters coded in their ASCII character set or in
binary format. They are

• Text Files.
• A Text file contains only the text information like alphabets ,digits
and special symbols. The ASCII code of these characters are
stored in these files.It uses only 7 bits allowing 8 bit to be zero.
• Binary Files
• A binary file is a file that uses all 8 bits of a byte for storing the
information. It is the form which can be interpreted and
understood by the computer.
• The only difference between the text file and binary file is the
data contain in text file can be recognized by the word processor
while binary file data can’t be recognized by a word processor.
• EOF

• EOF in any programming language is for End Of File.

• So if you are trying to display the contents of file and want to


stop when the fil The EOF function returns False until the end of
the file has been reached. It returns true when the file ends.
• getc() and feof() // function for EOF in C
• Types of File access in C
depending up on the method of accessing the data stored ,there
are two types of files.
• Sequential file
In this type of files data is kept in sequential order if we want to
read the last record of the file, we need to read all records before
that record so it takes more time.
• Random access file
In this type of files data can be read and modified randomly .If we
want to read the last record we can read it directly. It takes less
time when compared to sequential file.

You might also like