Programming in C BCA 1st Sem
Programming in C BCA 1st Sem
Unit I
Introduction to Programming in C
A. Compiler
1. Compiler used to translate high level language code to machine code.
2. Compiler scans complete program as once and translate it as a whole into machine code.
3. Compiler has slow speed because it scans complete program as once and translate it as
a whole into machine code.
4. Compiler generates all errors at a time, hence debugging is difficult than interpreter.
5. Compiler generate intermediate code which required linking hence compiler required
more memory.
6. Compiler checks all kind of limits, ranges, errors etc.
7. Program language like C, C++ uses compiler.
B. Interpreter
1. Interpreter used to translate high level language code to machine code.
2. Interpreter reads line by line program and translate it into machine code.
3. Therefor Interpreter is faster than Compiler.
4. Interpreter generates single error at a time, hence debugging is easy than compiler.
5. Interpreter will not generate intermediate code hence Interpreter required less memory.
6. Program language like Python, Ruby uses Interpreter.
Compiler Interpreter
A compiler translates the entire source code in An interpreter translates the entire source code
a single run. line by line.
It consumes less time to translate source code It consumes more time to translate source code
to machine code to machine code
Compiler Interpreter
It consumes more time to execute machine It consumes less time to execute machine code.
code.
Both syntactic and semantic errors can be Only syntactic errors are checked.
checked.
The localization of errors is difficult. The localization of error is easier than the
compiler.
The compiler is used by the language such as An interpreter is used by languages such as
C, C++. Java.
1.3 Algorithms
1. An algorithm is set of well-defined instructions to solve problem.
2. It takes set of inputs and produce desired output.
3. It is not a complete program or code.
4. The instruction in algorithm can be implemented in any language with the same output.
Step 1: Start
Step 2: Declare variable num1, num2 and sum.
Step 3: Read value num1 and num2
Step 4: Add num 1 and num2 and assign the result to sum
Sum num1 + num2
Step 5: Display sum
Step 6: Stop
Step 1: Start
Step 2: Declare variables a, b and c
Step 3: Read value of a, b and c
Step 4: if a > b and a > c
Display a is largest number
else if b > c
Display b is largest number
else
Display c is largest number
Step 5: Stop
1.4 Flowchart
1. Flowchart is a sequential, logical and stepwise diagrammatic representation of a
program.
2. Flowchart uses simple geometric shapes and arrows to show the flow of program.
3. Flowchart can have only one start and stop symbol.
4. General flow of process is from top to bottom or from left to right.
5. Arrows should not cross each other.
I. Documentation Section
1. In this section, we use header files such as stdio.h, conio.h, string.h etc.
2. Header files are used to link function used in c program.
3. These file are used using # include statement.
4. E.g #include <conio.h>
1. The variable, which used in more than one function are called as global variable.
2. Global variable are declared in global declaration section i.e. outside of all functions.
1. Every C has only one main function which starts with { and ends with }.
2. Main function has two sub sections.
A. Declaration part
i. In this part, variables are declared before used in program.
ii. Eg. int a,b,c;
B. Execution part
i. In this section, execution statements and function call statements are used.
ii. e.g. if(), printf(), scanf(). Clrscr(), etc.
1. In this section, user can define function which is called as user defined function.
The Character set
1. Every language has it’s own character set ex;- In English language there are 26
alphabets are used to create word, sentence, paragraph.
2. Similarly ‘C’ language has it’s own character sets i.e. ASCII character set.
3. In C language character set, 256 characters are available.
4. Using these characters we write the C program.
5. C language uses four types of characters.
1.6 Token
1. Token is smallest individual element of program.
2. For example, we cannot create sentence without word; similarly, we cannot create
statement without token.
3. Therefore we can say that tokens are basic component or building blocks to create
program.
Classification of tokens in C
Tokens in C language can be divided into seven categories
1. Keywords 2. Identifiers 3. Strings 4. Operators 5. Constant
6. Special Characters
1.6.1 Keywords
1. Keywords are the words whose meaning has already been explained to the C compiler.
2. The keywords cannot be used as variable names.
3. There are 32 keywords used in C all keywords must be written in lower case.
4. List of keywords:
2. Identifiers
1. Identifiers are the names given to variables, functions, arrays constants, structures,
unions and labels of statements.
2. The rules for naming identifiers are as follows −
3. Identifier names are unique.
4. Cannot use a keyword as identifiers.
5. Identifier has to begin with a letter or underscore (_).
6. It should not contain white space.
7. Special characters are not allowed.
8. Identifiers can consist of only letters, digits, or underscore.
3. String
Any group of characters defined between double quotation marks is a string constant.
Eg. “Nandigram Institute of Information Technology”.
4. Constants
1. Constants are fixed values that never change during execution of program.
2. The types of constant can be integer constant, floating point constant, character
constant, string constant, Boolean constant etc.
a) Integer constant
1. Any integer value using 0 to digits are integer constant.
2. ‘,’, ‘.’ Space ‘$’ or’ R’ sign are not allowed in integer constant e.g. 12,480 and $380
are illegal constants
c) Character Constants
1. Character Constants are enclosed in single quotes, e.g., 'x'
d) String constant
1. Any group of characters defined between double quotation marks is a string constant.
Eg. “Nandigram Institute of Information Technology”.
NANDIGRAM INSTITUTE OF INFORMATION TECHNOLOGY,NANDED 8
www.nandigramiit.org
C PROGRAMMING UNIT I
5. Special characters
Some of the special characters that are used in C programming are as follows
1. Brackets[] −used for array element
2. Parentheses() − are used for function calls and function parameters.
3. Braces{} −indicates the start and end of a block of code
4. Comma (, ) −used to separate more than one variables or parameters in function.
5. Semicolon(;) − It is called as a statement terminator
6. Asterisk (*) − It is used to create a pointer variable.
1.6.2 Variables
1. Variables are containers for storing data values, like numbers and characters.
2. In C, we can define variables according to the data type such as int, char, float,
double, long etc.
3. Syntax:
type variableName = value; or type variableNaame;
4. Example:
int age=19;
float weight;
Size in Format
Data Type Range
Byte String
char -128 to 127 or -27 to 27-1 1 %c
unsigned char 0 to 255 or 0 to 28-1 1 %c
int -32768 to 32767 or -215 to 215-1 2 %i or %d
unsigned int 0 to 65535 or 0 to 216-1 2 %u
-2147483648 to 2147483647
long int 4 %ld
or -231 to 231-1
unsigned long int 0 to 4294967295 or 0 to 232-1 4 %lu
Size in Format
Data Type Range
Byte String
Float 3.4e-38 to 3.4e+38 4 %f
Double 1.7e-308 to 1.7e+308 8 %lf
Long double 3.4e-4932 to 1.1e+4932 10 %lf
c. Void Type
1. The Void type has no value.
2. This is usually used to specify the type of functions.
3. The type of a function is said to be void when it does not return any value to the calling
function.
1.6.4 Operators
1. An operator is a symbol that tells the compiler to perform mathematical or logical
operations.
2. C language providing eight types of operators.
1. Logical Operators
Logical operator works on Boolean types of operands or conditions.
1. &&, || and ! are the logical operators.
2. Logical AND operator (&&) - If both the operands are true, then the condition becomes
true. E.g. if((a>b) && (a>c)), if a is greater than both b and c then it returns true
3. Logical OR Operator (||) - If any of the two operands is true, then the condition becomes
true.
E.g. if((a>b) || (a>c)), if a is greater than b or c then it returns true.
4. Logical NOT operator (!): Is unary operator. If the condition is true it returns false and
if the condition is false it returns true.
E.g. if(!(a>b)), if a is greater than b then it returns false else it returns true.
2. Arithmetic Operators
The following table shows all the arithmetic operators supported by the C language.
Assume A=10 and B=20.
3. Relational Operators
If we want to compare two values, then Relational operators are used.
C supports six Relational operators
Assume A=10 and B=20.
Operator Example
== (A == B) is not true.
!= (A != B) is true.
4. Assignment Operator
The assignment operators are used to assign values or result of the expression to
variables.
ex:-a=10;
5. Increment and Decrement operators
Prefix Increment and Decrement operators
In the prefix operators the values of variables is Increment and Decrement First and then
assigned to the expression
++a and - - a
a=3
y=++a
y=4
Postfix Increment and Decrement operators
Postfix operators first assign the values to variables on left side and then
increment the operand
a=5;
y=a++;
y=6
6. Special Operators
Below are some of the special operators that the C programming language offers.
Operators Description
7. Bit-wise Operator
Bitwise operator works on bits and perform bit-by-bit operation.
Assume a=4 (0100) and b=3 (0011)
Operator Example
| (A | B) = 7, i.e., 0111
8. Conditional operators
This is only one ternary operator in C programming language.
Syntax:
Expirations ? expression2 : expression3
Example:
x=(a<b)? a:b;
it means that –
if (a>b)
x=a
else
x=b;
A. printf()
1. This function is used to display result on the screen.
2. It can be used to display any combination of numerical value or char or string value.
3. This function is defined in the stdio.h header file.
4. Syntax:
printf (“format string”, v1, v2, . . . , vn);
NANDIGRAM INSTITUTE OF INFORMATION TECHNOLOGY,NANDED 15
www.nandigramiit.org
C PROGRAMMING UNIT I
5. For eg.
printf (“%f”, s);
printf (“\n sum=%6.2f”, s);
printf (“\n %d factorial is %d”, k, kfact);
B. scanf()
1. This function is used to receive input from keyboard.
2. It can be used to receive any combination of numerical value or char or string value.
3. This function is defined in the stdio.h header file.
4. Syntax:
scanf (“format string”, &v1, &v2, . . . , &vn);
5. For eg.
scanf (“%f”, &s);
scanf (“%c”,&ans);
scanf (“%d %d”,&k, &kfact);
4. getch(), getche(), getchar(), putch(), putchar() and clrscr() are commonly used
unformatted functions provide by conio.h header file and gets() and puts() are the
unformatted functions provided by stdio.h header file.
a. getch()
1. getch() function reads a single character from the keyboard.
2. The character entered by user doesn’t display on the screen.
3. There is no need to press enter key from keyboard. As soon as any key pressed from
keyboard getch() read a single character.
4. getch() is also used for hold the screen.
5. Example:
ch=getch(); // where ch is a char variable.
b. getche()
1. getche() function reads a single character from the keyboard.
2. The character entered by user is displayed on the screen.
3. There is no need to press enter key from keyboard. As soon as any key pressed from
keyboard getch() read a single character.
4. Example:
ch=getche(); // where ch is a char variable.
c. getchar()
1. The getchar() function is used to read only a first single character from the keyboard
whether multiple characters is typed by the user and this function reads one character
at one time until and unless the enter key is pressed.
2. Example:
ch=getchar(); // where ch is a char variable.
d. gets()
1. gets() function reads a group of characters or strings from the keyboard.
2. These characters get stored in a character array.
3. This function allows us to write space-separated texts or strings.
4. Syntax:
e. puts()
1. puts() function is used to display a group of characters or strings which is already stored
in a character array.
2. Syntax:
puts(str); // where str is a string (array of characters)
3. Example :
char str[20]=" Hello World";
puts(str);
f. clrscr()
1. clrscr() function is used to clear the monitor screen.
2. It has the following syntax :
clrscr();
Unit II
Controlling Statement
2.1.1 if statement
1. The if statement is a powerful decision making statement used to control the flow of
program.
2. if statement first of all check the condition and if condition is true, if block will be
executed and if the condition is false, if block will not be executed and program
control goes next to if block statement.
3. The general format of if statement is below:
if (test expression)
{
Block of statements
}
1. After test expression of if statement, block of statements are written inside open and
closed curly brackets {}.
2. Block of statements may contain single statement or group of statements.
3. If block of statements contain single statement, open and closed curly brackets {} are
optional.
Void main()
{
int a,b;
printf(“\n Enter the Number a & b”);
scanf(“%d%d”,&a,&b);
if(a>b)
printf(“A is greater number”);
if(b>a)
printf(“B is greater number”);
getch();
}
Note:
if(test expression)
{
true statements block
}
else
{
false statements block
}
void main()
{
int num;
printf(“\nEnter the any number”);
scanf(“%d”,&num);
if(num%2==0)
{
void main()
{
int year;
printf(“\nEnter the year”);
scanf(“%d”,&year);
if(year%4==0 && year%400==0 && year%100!=0)
{
printf(“The given year is leap year”);
}
else
{
printf(“The given year is not leap year”);
}
getch();
}
if(condition 1)
{
Block of statements
if(condition 2)
{
Block of statements
if(condition 3)
{
Block of statements
}
}
}
if(condtion 1)
{
Block of statements
if(condtion 2)
{
Block of statements
}
else
{
Block of statements
}
}
else
{
Block of statements
if(condtion 3)
{
Block of statements
}
else
{
Block of statements
}
}
void main()
{
int a,b,c;
printf(“Enter any three numbers”);
scanf(“%d %d %d”, &a, &b, &c);
if(a>b)
{
if(a>c)
{
printf(“%d is grater”,a);
}
else
{
printf(“%d is grater”,c);
}
}
else
{
if(b>c)
{
printf(“%d is grater”,b);
}
else
{
printf(“%d is grater”,c);
}
}
}
//Write a program that display the class obtained by student if percentage of the
student is input through the keyboard.
void main()
{
float per;
printf(“\nEnter the percentage”);
scanf(“%f”,&per);
if(per<0 && per>100)
{
printf(“Invalid input”);
exit();
}
if(per<40)
printf(“Fail”);
else
{
if(per<50)
printf(“Pass”);
else
{
if(per<60)
printf(“Second class class”);
else
printf(“First class”);
}
}
}
//Write a program find out entered key is upper case or lower case.
#include<stdio.h>
#include<conio.h>
void main()
{
char x;
clrscr();
printf("\nEnter any char");
scanf("%c",&x);
if((x>=65&&x<=90)||(x>=97&&x<=122))
{
if(x>=65&&x<=90)
printf("it is an upper case alphabet");
else
printf("It is lower case alphabet");
}
else
printf("It is not alphabet");
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
int num;
printf("\nenter any number");
scanf("%d",&num);
if(num>0)
{
printf("given number is positive");
}
else
{
if(num<0)
{
printf("given num is negative");
}
else
{
printf("Zero");
}
}
getch();
}
If(condition 1)
{
Block of statements
}
else if(condition 2)
{
Block of statements
}
else if(condition 3)
{
Block of statements
}
else
{
Default block of statements
}
//Write a program that display the class obtained by student if percentage of the
student is input through the keyboard.
void main()
{
float per;
printf(“Enter the value”);
scanf(“%f”,&per);
if(per>80)
{
printf(“grade is merit”);
}
else if(per>70)
{
printf(“Distinction”);
}
else if(per>60)
{
printf(“Grade A”);
}
else if(per>50)
{
printf(“Grade is B”);
}
else if(per>=35)
{
printf(“Grade is C”);
}
else
{
printf(“Failed”);
}
getch();
}
2.1.5 switch … case Statement
1. Instead of writing nested if..else if statements, we can use the switch statement.
2. The switch statement selects one of many code blocks to be executed.
3. The switch expression is evaluated once.
4. The value of the expression is compared with the values of each case.
switch(expression)
{
case value 1:
block of statements
break;
case value 2:
block of statements
break;
case value 3:
block of statements
break;
default:
default block of statements
}
// Write a program that reads a number between 1 to 7 and display the day name
void main()
{
int day;
printf(“Enter a number between 1 to 7 \n”);
scanf(“%d”,&day);
switch(day)
{
case 1: printf(“Monday\n”);
break;
case 2: printf(“Tuesday\n”);
break;
case 3: printf(“Wednesday\n”);
break;
case 4: printf(“Thursday\n”);
break;
case 5:printf(“Friday\n”);
break;
case 6:printf(“Saturday\n”);
break;
case 7:printf(“Sunday\n”);
break;
default:printf(“Monday\n”);
}
getch();
}
void main()
{
int a,b,n,p;
float c;
clrscr();
xyz:printf(“\nenter two number”);
scanf(“%d%d”,&a,&b);
printf(“\n 1 addition of two number”);
printf(“\n 2 subtraction of two number”);
printf(“\n 3 multiplication of two number”);
printf(“\n 4 division of two number”);
printf(“\nenter your choice”);
scanf(“%d”,&n);
switch(n)
{
case 1: c=a+b;
printf(“\naddition of two number is%f”,c);
break;
case 2: c+a-b;
printf(“\subtraction of two number is%f”,c);
break;
case 3: c+a*b;
printf(“\multiplication of two number is%f”,c);
break;
case 4: c+a-b;
printf(“\division of two number is%f”,c);
break;
default:
printf(“\nentered choice incorrect”);
}
printf(“\nDo you want to continue (Y/N)….”);
printf(“\nEnter 6 for Yes and 7 for No”);
scanf(“%d”,&p);
swatch(p)
{
case 6: goto xyz;
case 7:exit();
}
getch();
}
2.2.1for loop
1. When we exactly know how many times we want to execute loop, we use for loop
instead of while and do…while loop.
2. for loop consist of three statements i.e. initialization statement, test expression /
conditional statement and increment / decrement statement.
3. Syntax
Example
#include<stdio.h>
#include<conio.h>
Void main()
{
int sum=0;
clrscr();
for(int i=1;i<=10;i++)
sum+=i;
printf(“/nAddition of 1 to 10 numbers is %d”,sum);
getch();
}
//Write program to print all numbers from 1 to 200 divisible by 3,4 and 5.
#include<stdio.h>
#include<conio.h>
Void main()
{
clrscr();
printf(“All numbers from 1 to 200 divisible by 3,4 and 5\n”);
for(int i=1;i<=100;i++)
{
if(i%3==0 && i%4==0 && i%5==0)
printf(“%d/t”,i);
}
getch();
}
#include<stdio.h>
#include<conio.h>
Void main()
{
clrscr();
for(int i=1;i<=10;i++)
{
for(int j=1;j<=20;j++)
printf(“%4d”,(i*j));
printf(“\n”);
}
getch();
}
Syntax:
while(condition)
{
Body of loop
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
int i=2;
clrscr();
while(i<=100)
{
printf(“%3d”,i);
i=i+2;
}
getch();
}
Syntax:
do
{
Body of loop
} while(condition);
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
int i=1;
clrscr();
do
{
printf(“%3d”,i);
i=i+2;
} while(i<=100)
getch();
}
#include<conio.h>
#include<stdio.h>
void main()
{
int i=1,n,f,f1,f2;
clrscr();
printf("Enter Number of Fibonacci Values Needed : ");
scanf("%d",&n);
f=0;
f1=1;
f2=1;
do
{
i++;
printf("%d\n",f);
f1=f2;
f2=f;
f=f1+f2;
}
while(i<=n);
getch();
}
OUTPUT:
Enter Number of Fibonacci Values Needed : 10
0
1
1
2
3
5
8
13
21
34
//Write program to addition of numbers.
#include <stdio.h>
#include<conio.h>
void main()
{
int number, sum = 0;
clrscr();
do
{
printf("Enter a number: (To stop enter 0) ”);
scanf("%lf", &number);
sum += number;
}
while(number != 0);
printf("Sum = %.d",sum);
getch();
}
In above example, if condition is true when i =6,12 and 18 and continue statement will
be execute. Therefore printf(“\n%d”,i) statement will not execute after continue statement
execution. The above program will not print the numbers 6, 12 and 18.
goto label;
Statement 1
Statement 2
Statement n
label: Statement x1
Statement x2
Statement xn
label : Statement 1
Statement 2
Statement n
go to label;
Statement x1
Statement x2
Statement xn
Example
#include<stdio.h>
#include<conio.h>
#include<process.h>
void main ()
{
int a,b;
clrscr();
xyz:printf("enter the number");
scanf("%d",&a);
if(a%2==0)
{
printf("given num is even ");
}
else
{
}
printf("\nif you want to continue");
printf("\n Enter 6 to yes 7 to no");
scanf("%d",&b);
if(b==6) goto xyz;
if(b==7) exit(0);
}
Unit III
Functions in C
Types of functions in C
There are two main types of functions in programming:
A. Library Function
1. In C programming, a library function (or built-in function) refers to a function that is
provided as part of the standard C library.
2. These functions are predefined and come with the C programming language.
3. Library functions are designed to perform common and useful operations, making them
readily available for C programmers to use.
4. Library functions are already defined in C, so you don't need to declare or define them
yourself.
5. Many library functions are part of the Standard C Library, such as functions for
input/output (e.g., printf, scanf), string manipulation (e.g., strlen, strcpy), mathematical
operations (e.g., sqrt, sin), and more.
6. Library functions are well-documented in C language specifications and library
documentation. You can easily find information on how to use these functions and their
required parameters.
7. E.g.
NANDIGRAM INSTITUTE OF INFORMATION TECHNOLOGY,NANDED 1
www.nandigramiit.org
C PROGRAMMING UNIT III
#include <stdio.h>
#include <math.h> // Include the math library for sqrt() function
int main()
{
double number = 16.0;
double result = sqrt(number); // Using the sqrt() library function
printf("The square root of %f is %f\n", number, result);
return 0;
}
8. In the code above, we included the math library (using #include <math.h>) to access
the sqrt() function, which calculates the square root of a number.
Type: Functions that do not return any value are called "void functions."
3.3.1 Declaration: You declare a void function by specifying its name, parameters, and the
void keyword as the return type.
For example:
3.3.2 Definition: The definition of the function contains the actual code to be executed when
the function is called.
For example:
void greetUser(char name[]) {
printf("Hello, %s!\n", name);
}
3.3.3 Function Calling: You call a void function in your program by using its name and
providing any required arguments.
For example:
int main() {
char username[] = "John";
greetUser(username); // Call the greetUser function
return 0;
}
3.3.1 Declaration: You declare a function with a return value by specifying its name,
parameters, and the data type of the return value.
For example:
3.3.2 Definition: The definition of the function contains the code to be executed and a return
statement to send back a value of the specified data type.
For example:
3.3.3 Function Calling: You call a function with a return value in your program and store the
returned value in a variable.
For example:
int main() {
int result = add(3, 4); // Call the add function and store the result
printf("The sum is %d\n", result);
return 0;
}
3.4 Recursion
1. Recursion is a programming technique where a function calls itself in order to solve a
problem.
2. In C, a recursive function is a function that, within its own definition, makes one or
more calls to itself.
3. This can be a powerful way to solve problems that can be broken down into smaller,
similar sub-problems.
4. Here's the basic structure of a recursive function in C:
return_type function_name(parameters) {
// Base case (exit condition)
if (base_case_condition) {
// Return a value
}
// Recursive case
else {
// Make one or more recursive calls
// Modify parameters
}
}
#include <stdio.h>
int main() {
int num = 5;
int result = factorial(num);
printf("Factorial of %d is %d\n", num, result); // Output: Factorial of 5 is 120
return 0;
}
In this example, the factorial function is defined recursively. The base case checks if n is 0 and
returns 1 because the factorial of 0 is defined as 1. In the recursive case, it calculates the
factorial of n by multiplying n with the factorial of (n - 1). This process continues until the base
case is reached.
At this point, the base case is reached, and each function call starts returning values:
factorial(0) returns 1
factorial(1) returns 1 * 1 = 1
factorial(2) returns 2 * 1 = 2
factorial(3) returns 3 * 2 = 6
factorial(4) returns 4 * 6 = 24
factorial(5) returns 5 * 24 = 120
Unit IV
Array and Structure
4.1 Array
1. Arrays used to store multiple values in a single variable, instead of declaring separate
variables for each value.
2. An array is a group of similar type of data elements stored in contiguous memory
location. These data elements addressed by common name.
3. Instead of declaring individual variables, such as number0, number1, ..., and number99,
you declare one array variable such as numbers and use numbers[0], numbers[1], and
..., numbers[99] to represent individual variables.
1. An array is declared by writing the data types, followed by the name, followed by the
size in brackets.
2. Syntax:
data type array_name[size];
3. Example:
int n[12];
4. Here declares the n as an array to contain a maximum of 12 integer constants.
5. The c language treats character strings simply as arrays of characters.
6. The size in a character string represents the maximum number of characters that the
string can hold.
7. Example:
char n[20];
8. Here declare the variable n as a character array variable that can hold a maximum of 20
characters. Suppose we read the following string constant into the string variable name.
“Nandigram Institute”
9. Each character of the string is treated as an element of the array name and is stored in
the memory as follow.
n[0] n[1] n[2] n[3] n[4] n[5] n[6] n[7] ….. …..n[20]
‘N ‘a ‘n ‘d ‘i ‘g ‘r ‘a ‘m ‘ ‘I ‘n ‘s ‘t ‘i ‘t ‘u ‘t ‘e ‘/n
’ ’ ’ ’ ’ ’ ’ ’ ’ ‘ ’ ’ ’ ’ ’ ’ ’ ’ ’ ’
10. When the compiler finds a character string. It terminates it with an additional null
character. The element n[20] holds the null character ‘\0’.
11. When declaring character arrays, we must allow one extra element space for the null
terminator.
Types of Arrays
There are three types of arrays
1. One dimensional array
2. Two dimensional array
3. Multi-dimensional array
2. Syntax:
data type array_name[size];
3. example:
int n[12];
4. Here declare the variable number as an array of size 3 and will assign zero to each
elements.
5. If the number of values in the list is less than the number of elements will be set to
zero automatically.
float total[5]={0.0,15.75,-10.0};
6. Here initialize the first three elements to 0.0, 15.75 and -10.0 and the remaining two
elements to 0.0.
7. We also declare the array as variant. In that no need to enter the size of array.
Ex int a[]={1,3,4};
8. That is called as variant and in that we can store the number of element.
9. Similar, We can also declare the character array but we must end the string with ‘\0’
int marks[30];
for ( i = 0 ; i <= 29 ; i++ )
{
printf ( "\nEnter marks " ) ;
scanf ( "%d", &marks[i] ) ;
}
The ‘for’ loop causes the process of asking and receiving a student’s marks from the user to be
repeated 30 times.
3. example:
int n[12][10];
Initialization of one dimensional array
1. We can initialize the elements of arrays in the same way as the ordinary variables
when they are declared.
2. Syntax:
Data type array-name[row-size][column-size]={{list of values in first row},
{list of values in second row}, . . . . , {list of values in row-size th row}} ;
4. Here declare the two dimensional array number as an array of row-size 3 and colum-
size 4 will assign value as shown in { } each elements.
5. We also declare the array as variant. In that no need to enter the size of array.
6. That is called as variant and in that we can store the number of element.
Entering data into an two dimensional array
int marks[30][4];
for ( i = 0 ; i <= 29 ; i++ )
{
for(int j=0; j<4; j++}
{
printf ( "\nEnter marks " ) ;
scanf ( "%d", &marks[i] ) ;
}
}
The ‘for’ loop causes the process of asking and receiving a 30 student’s marks of four subject
from the user to be repeated 30 times.
4.8 Unions
1. In C, a union is a user-defined data type that allows you to store different types of data
in a single memory location, but only one of them at a time.
2. It is similar to a structure in that it can hold multiple variables of different data types,
but unlike a structure, a union uses the same memory location for all its members.
3. This means that only one member of the union can be used at any given time, and
accessing a different member will overwrite the current value.
4. Here's the basic structure of a union in C:
union union_name {
data_type member1;
data_type member2;
// ...
};
5. Here's an example of a union that can store either an integer or a float value:
#include <stdio.h>
union NumericValue {
int intValue;
float floatValue;
};
int main() {
union NumericValue number;
number.intValue = 42;
printf("Integer value: %d\n", number.intValue);
number.floatValue = 3.14;
printf("Float value: %f\n", number.floatValue);
return 0;
}
Unions are commonly used in situations where you need to store different types of data in a
single variable but only use one type at a time.
However, you must be careful when using unions to ensure that you access the correct member,
depending on the context, as there's no built-in mechanism to determine which member is
currently valid.
Shares the same memory location for all Allocates separate memory for each
members. It is as large as the largest member. The size is the sum of all
Memory Usage member. members' sizes.
Typical Efficient for saving memory when only one Used for organizing and grouping
Operations member is used at a time. related data.