0% found this document useful (0 votes)
17 views62 pages

C Prog

The document discusses the types of arrays in C programming, including one-dimensional and multidimensional arrays, and provides syntax and examples for each. It also covers strings in C, their declaration, initialization, and various string handling functions. Additionally, it explains the concept of functions in C, their types, components, and the differences between structures and unions.

Uploaded by

Roopa Sk
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views62 pages

C Prog

The document discusses the types of arrays in C programming, including one-dimensional and multidimensional arrays, and provides syntax and examples for each. It also covers strings in C, their declaration, initialization, and various string handling functions. Additionally, it explains the concept of functions in C, their types, components, and the differences between structures and unions.

Uploaded by

Roopa Sk
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 62

Types of Arrays

• There are two types of arrays based


on the number of dimensions it has.
They are as follows:
1.One Dimensional Arrays (1D Array)
2.Multidimensional Arrays
• 1. One Dimensional Array in C
• The One-dimensional arrays, also
known as 1-D arrays in C are those
arrays that have only one dimension.
• Syntax of 1D Array in C
• array_name [size];
• Array of Characters (Strings)
• In C, we store the words, i.e., a
sequence of characters in the form of
an array of characters terminated by
a NULL character. These are called
strings in C language.
• // C Program to illustrate strings
• #include <stdio.h>
• int main()
• {

• // creating array of character


• char arr[6] = { ‘’I, ‘B', ‘M', ‘R', ‘S', '\0' };

• // printing string
• int i = 0;
• while (arr[i]) {
• printf("%c", arr[i++]);
• }
• return 0;
• }
• 2. Multidimensional Array in C
• Multi-dimensional Arrays in C are those arrays
that have more than one dimension. Some of
the popular multidimensional arrays are 2D
arrays and 3D arrays. We can declare arrays
with more dimensions than 3d arrays but they
are avoided as they get very complex and
occupy a large amount of space.
• A. Two-Dimensional Array in C
• A Two-Dimensional array or 2D array in C is an
array that has exactly two dimensions. They
can be visualized in the form of rows and
columns organized in a two-dimensional plane.
Syntax of 2D Array in C
array_name[size1] [size2];
• Here,
• size1: Size of the first dimension.
• size2: Size of the second dimension.

• // C Program to illustrate 2d array
• #include <stdio.h>

• int main()
• {

• // declaring and initializing 2d array


• int arr[2][3] = { 10, 20, 30, 40, 50, 60 };

• printf("2D Array:\n");
• // printing 2d array
• for (int i = 0; i < 2; i++) {
• for (int j = 0; j < 3; j++) {
• printf("%d ",arr[i][j]);
• }
• printf("\n");
• }

• return 0;
• }
Output
2D Array: 10 20 30
40 50 60
• Three-Dimensional Array in C
• Another popular form of a multi-
dimensional array is Three
Dimensional Array or 3D Array. A 3D
array has exactly three dimensions.
It can be visualized as a collection of
2D arrays stacked on top of each
other to create the third dimension.
Syntax of 3D Array in C
array_name [size1] [size2]
[size3];
• // C Program to illustrate the 3d array
• #include <stdio.h>
• int main()
• {
• // 3D array declaration
• int arr[2][2][2] = { 10, 20, 30, 40, 50, 60 };

• // printing elements
• for (int i = 0; i < 2; i++) {
• for (int j = 0; j < 2; j++) {
• for (int k = 0; k < 2; k++) {
• printf("%d ", arr[i][j][k]);
• }
• printf("\n");
• }
• printf("\n \n");
• }
• return 0;
• }
Output
10 20
30 40
50 60
0 0 0
• Strings in C
• A String in C programming is a sequence
of characters terminated with a null
character ‘\0’. The C String is stored as an
array of characters. The difference
between a character array and a C string
is that the string in C is terminated with a
unique character ‘\0’.

• C String Declaration Syntax
• Declaring a string in C is as simple as declaring a one-
dimensional array. Below is the basic syntax for
declaring a string.
• Char string_name[size];
• In the above syntax string_name is any name given
to the string variable and size is used to define the
length of the string, i.e the number of characters
strings will store.
• There is an extra terminating character which is
the Null character (‘\0’) used to indicate the
termination of a string that differs strings from normal
character arrays.
Initialization of string
There are multiple ways we can initialize a string.

Direct initialization
If we assign string directly with in double quotes, no need to bother about null
character.
Because compiler will automatically assign the null character at the end of string.

i)Assigning direct string with size

char country[6]=”india”;

Note
while giving initial size, we should always give extra one size to store null
character.
To store "india", string size 5 is enough but we should give extra one (+1) size 6 to
store null character.
ii)Assigning direct string without size
Example
char country[]=”india”;

In the above case, string size will be deter


compiler.
Character by character initialization
we can also assign a string character by character.
If we assign character by character , we must specify the null character '\0
the string.

i)char by char with size


Example
char country[6]={‘i’,’n’,’d’,’i’,’a’,’\0’};

ii)char by char without size


Example
char country[]={‘i’,’n’,’d’,’i’,’a’,’\0’};
Pictorial Explanation
• STRING HANDLING FUNCTIONS
• C library supports a large number of string handling
functions. Those functions are stored under the header
file string.h in the program.
• Let us see about some of the string handling functions.
• (i) strlen() function
• strlen() is used to return the length of the string , that
means counts the number of characters present in a
string.
• Syntax integer variable = strlen (string variable);
Example:
• #include
• void main()
• { char str[20];
• int strlength;
• clrscr();
• printf(‚Enter String:‛);
• gets(str);
• strlength=strlen(str);
• printf(‚Given String Length Is: %d‛, strlength);
• getch();
• }
• Output:
• Enter String
• Welcome
• Given String Length Is:7
• (ii) strcat() function
• The strcat() is used to concatenate two
strings. The second string will be
appended to the end of the first string.
This process is called concatenation.
• Syntax strcat (StringVariable1,
StringVariable 2);
• #include
• void main()
• {
• char str1[20],str2[20];
• clrscr();
• printf(“Enter First String”);
• scanf(‚%s‛,str1);
• printf(“Enter Second String”);
• scanf(‚%s‛,str2);
• printf(“concatenation String is:%s”,strcat(str1,str2));
• getch();
• }
3. strcmp() Function
The strcmp() is a built-in library function in C. This function takes two strings as arguments and
compares these two
strings lexicographically.

Syntax
int strcmp(const char *str1, const char *str2);

Parameters
•str1: This is the first string to be compared.
•str2: This is the second string to be compared.
yntax
har* strcpy(char* dest, const char* src);

• 4. strcpy
• The strcpy() is a standard library
function in C and is used to copy one
string to another. In C, it is present
in <string.h> header file.
Syntax
char* strcpy(char* dest, const char*
src);
• Parameters
• dest: Pointer to the destination array
where the content is to be copied.
• src: string which will be copied.
5. strchr()
The strchr() function in C is a predefined
function used for string handling. This
function is used to find the first occurrence
of a character in a string.
Syntax
char *strchr(const char *str, int c);
strrchr() Function
In C, strrchr() function is similar to strchr() function. This function is
used
to find the last occurrence of a character in a string.
Syntax
char* strchr(const char *str, int ch);
7. strtok()
The strtok() function is used to split the st
tokens
based on a set of delimiter characters.
Syntax
char * strtok(char* str, const char
• Parameters
• str: It is the string to be tokenized.
• delims: It is the set of delimiters
Functions in C
• Definition
• A function is a self contained block
of code that performs a certain
task/job. For example, we can write a
function for reading an integer or we
can write a function to add numbers
from 1 to 100 etc.
• Generally a function can be imagined like
a Black Box, which accepts data input and
transforms the data into output results. The
user knows only about the inputs and
outputs. User has no knowledge of the
process going on inside the box which
converts the given input into output.
Types of Functions

• Based on the nature of functions,


they can be divided into two
categories. They are:
1.Predefined functions / Library
functions
2.User defined functions

Function or Library function
• A predefined function or library function
is a function which is already written by
another developer. The users generally
use these library functions in their own
programs for performing the desired
task.
• The predefined functions are available
in the header files. So, the user has to
include the respective header file to use
the predefined functions available in it.

User defined functions

• A user defined function is a function


which is declared and defined by the
user himself. While writing programs,
if there are no available library
functions for performing a particular
task, we write our own function to
perform that task. Example for user
defined function is main function.

Need for functions

• Functions have many advantages in programming.
Almost all the languages support the concept of
functions in some way. Some of the advantages of
writing/using functions are:
1. Functions support top-down modular programming.
2. By using functions, the length of the source code
decreases.
3. Writing functions makes it easier to isolate and debug
the errors.
4. Functions allow us to reuse the code..

C Library Functions

• The Standard Function Library in C is a huge


library of sub-libraries, each of which
contains the code for several functions.
• In order to make use of these libraries, link
each library in the broader library through
the use of header files. The actual
definitions of these functions are stored in
separate library files, and declarations in
header files. In order to use these functions,
we have to include the header file in the
program
S No. Header Files Description

It checks the value of an


expression that we expect to
be true under normal
1 <assert.h> circumstances.
If the expression is a nonzero
value, the assert macro does
nothing.

A set of functions for


2 <complex.h> manipulating complex
numbers.

Defines macro constants


specifying the implementation-
3 <float.h> specific properties of the
floating-point library.
The math.h header defines
various mathematical
functions and one macro. All
4 <math.h> the Functions
in this library take double as
an argument and return
double as the result.

The stdio.h header defines


three variable types, several
5 <stdio.h> macros, and various
function for performing input
and output.

Defines date and time


6 <time.h>
handling functions.

Strings are defined as an


array of characters. The
difference between a
7 <string.h> character array
and a string is that a string is
terminated with a special
character ‘\0’.
Components of function
declaration
• There are three aspects of a C function.
• Function declaration A function must be
declared globally in a c program to tell the
compiler about the function name, function
parameters, and return type.
• Function call Function can be called from
anywhere in the program. The parameter list
must not differ in function calling and function
declaration. We must pass the same number of
functions as it is declared in the function
declaration.
• Function definition It contains the
actual statements which are to be
executed. It is the most important
aspect to which the control comes
when the function is called. Here, we
must notice that only one value can
be returned from the function.
SN C function aspects Syntax

return_type function_name
1 Function declaration
(argument list);

2 Function call function_name (argument_list)

return_type function_name
3 Function definition
(argument list) {function body;}
• Return Value
• A C function may or may not return a
value from the function. If you don't have
to return any value from the function,
use void for the return type.
• Example without return value:
1.void hello(){
2.printf("hello c");
3.}
• Example with return value:
1.int get(){
2.return 10;
3.}
• In the above example, we have to
return 10 as a value, so the return type
is int. If you want to return floating-
point value (e.g., 10.2, 3.1, 54.5, etc),
you need to use float as the return type
of the method.
1.float get(){
2.return 10.2;
3.}
Different aspects of function
calling
• A function may or may not accept any argument. It
may or may not return any value. Based on these
facts, There are four different aspects of function
calls.

• function without arguments and without


return value
• function without arguments and with return
value
• function with arguments and without return
value
• function with arguments and with return value
• Function without argument and return value
Example 1
#include<stdio.h>
void printName();
void main ()
{
printf("Hello ");
printName();
}
void printName()
{
printf("Javatpoint");
}
• Function without argument and with return value
• Example 1
• #include<stdio.h>
• int sum();
• void main()
• {
• int result;
• printf("\nGoing to calculate the sum of two numbers:");
• result = sum();
• printf("%d",result);
• }
• int sum()
• {
• int a,b;
• printf("\nEnter two numbers");
• scanf("%d %d",&a,&b);
• return a+b;
• }
Structures and Unions in C

• Structures and unions are two of many user


defined data types in C. Both are similar to each
other but there are quite some significant
differences. In this article, we will discuss about
both of these data types and differentiate both
these data types based on the functionalities.
• STRUCTURES:
• A structure simply can be defined as a user-
defined data type which groups logically related
items under one single unit. We can use all the
different data items by accessing that single
unit.
• All the data item are stored in
contiguous memory locations. It is
not only permitted to one single data
type items. It can store items of
different data items. It has to be
defined before using (Just like we
define a variable before using it in
the program).
• Structure definition syntax:
1.struct_structure_name
2.{
3.data_type_variable_name;
4.data_type_variable_name;
5.........
6.data_type_variable_name;
7.};
• UNION:
• Just like a structure, a union is also a user-defined data type that
groups together logically related variables into a single unit.
• Almost all the properties and syntaxes are same, except some of
the factors.
• Syntax:
1. union union_name
2. {
3. data_type variable_name;
4. data_type variable_name;
5. ........
6. data_type variable_name;
7. };
1.union Emp
2.{
3. char address[50];
4. int dept_no;
5. int age;
6.};
Memory allocation in a union:
• In a structure, the memory occupied by it is
simply the sum of the memory occupied by all
its members as they are organized contiguously
and every member has its own memory.
• But, in a union, data items are organized one on
another. So, the total memory space required to
store a union is the memory required to store
the largest memory required element in it.
• Another major attachment here is that in a
structure, we can access any number of items
anytime. But, in a union, only one item can be
accessed at a time.
tructuresS Unions

The keyword "struct" is used to define a structure. The keyword "union" is used to define a structure.

A unique memory location is given to every member of a


One single memory location is shared by all its members
structure

Modifying the value of one item won't affect the other items Modifying one single data item affects other members of
or the structure at all. the union thus affecting the whole unit.

We initialize several members at once. We can initialize only the first member of union.

The total size of the structure is the sum of the size of The total size of the union is the size of the largest data
every data member member

It is mainly used for storing one of the many data types that
It is mainly used for storing various data types
are available.

It occupies space for each and every member written in It occupies space for a member having the highest size
inner parameters written in inner parameters

We can retrieve any member at any time We can only access one member at a time in the union.

You might also like