0% found this document useful (0 votes)
11 views44 pages

Arrays

The document provides a comprehensive overview of arrays in C programming, including their declaration, initialization, and methods for accessing and manipulating elements. It also covers multidimensional arrays, infinite loops, operator precedence, and string handling functions. Additionally, it includes examples and problems for practical understanding.

Uploaded by

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

Arrays

The document provides a comprehensive overview of arrays in C programming, including their declaration, initialization, and methods for accessing and manipulating elements. It also covers multidimensional arrays, infinite loops, operator precedence, and string handling functions. Additionally, it includes examples and problems for practical understanding.

Uploaded by

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

Arrays

What are arrays?

● An array is a variable that can store multiple values.


● For example, if you want to store 100 integers, you can create an
array for it.
How to declare an array
dataType arrayName[arraySize];

For eg: int i[20];

Here, we declared an array, i, of integer type. And its size is 20. Meaning, it can
hold 20 integer values.

float marks[10];

Here, we declared an array, marks, of floating-point type. And its size is 10.
Meaning, it can hold 10 floating-point values.
Access array elements
You can access elements of an array by indices.

Suppose you declared an array mark as above. The first element is mark[0], the
second element is mark[1] and so on.
● Arrays have 0 as the first index, not 1. In this example, mark[0] is the first
element.
● If the size of an array is n, to access the last element, the n-1 index is used. In
this example, mark[4]
● Suppose the starting address of mark[0] is 2120d. Then, the address of the
mark[1] will be 2124d. Similarly, the address of mark[2] will be 2128d and so
on.
This is because the size of a float is 4 bytes.
How to initialize an array
It is possible to initialize an array during declaration. For example,

int mark[5] = {19,10,8,17,9};

You can also initialize an array like this.

int mark[ ] = {19,10,8,17,9};

Here, we haven't specified the size. However, the compiler knows its size is 5 as
we are initializing it with 5 elements.
Changing value of array elements
int mark[5] = {19, 10, 8,17,9};

// make the value of the third element to 3.

mark[2] = 3;

// make the value of fifth element to 0

mark[4]= 0;
Input and Output Array elements
// take input and store it in the 3rd element
scanf("%d", &mark[2]);
// take input and store it in the ith element
scanf("%d", &mark[i-1]);
// print the first element of the array
printf("%d", mark[0]);
// print the third element of the array
printf("%d", mark[2]);
// print ith element of the array
printf("%d", mark[i-1]);
Problems
● WAP to take 5 values from the user and store them in an array and print the
results from the array.
● WAP to find the average of n numbers using array.
● WAP to find the largest among three numbers
● WAP to find largest element in an array.
What is the sizeof(char) in a 32-bit C compiler?
a) 1 bit
b) 2 bits
c) 1 Byte
d) 2 Bytes
What is #include <stdio.h>?
What will happen if the following C code is
a) Preprocessor directive executed?
b) Inclusion directive 1. #include <stdio.h>
c) File inclusion directive 2. int main()
3. {
d) None of the mentioned 4. int main = 3;
Which of the following are C preprocessors? 5. printf("%d", main);
6. return 0;
a) #ifdef 7. }
b) #define
a) It will cause a compile-time error
c) #endif b) It will cause a run-time error
c) It will run without any error and prints 3
d) all of the mentioned d) It will experience infinite looping
What will be the output of the What is the difference between the following 2 C codes?
following C code?
1. #include <stdio.h> //Program 1
1. #include <stdio.h> 2. int main()
2. int main() 3. {
3. { 4. int d, a = 1, b = 2;
4. signed char chr; 5. d = a++ + ++b;
5. chr = 128; 6. printf("%d %d %d", d, a, b);
6. printf("%d\n", chr); 7. }
7. return 0; 1. #include <stdio.h> //Program 2
2. int main()
8. }
3. {
a) 128 4. int d, a = 1, b = 2;
b) -128 5. d = a++ +++b;
6. printf("%d %d %d", d, a, b);
c) Depends on the compiler 7. }

d) None of the mentioned a) No difference as space doesn’t make any difference, values of
a, b, d are same in both the case
b) Space does make a difference, values of a, b, d are different
c) Program 1 has syntax error, program 2 is not
Problems
● WAP to input a character in a variable and display it using other variable.
● WAP to check whether two numbers are equal, greater or lesser than each
other.
● WAP to print the odd numbers from 1 to 20.
● WAP to check the prime number.
● WAP to calculate the factorial of a number.
● WAP to check whether a number is palindrome or not.
● Print the pattern:
1
12
123
1234
12345
MultiDimensional Array
In C programming, you can create an array of arrays. These arrays are known as
multidimensional arrays. For example, float x[3][4].

Here, x is a two-dimensional (2d) array. The array can hold 12 elements. You can
think the array as a table with 3 rows and each row has 4 columns.
Similarly, you can declare a three-dimensional (3d) array. For example,

float c[2][4][3]. Here, the array c can hold 24 elements.


Initializing multi dimensional array
Initialization of a 2d array
/

/ Different ways to initialize two-dimensional array

int c[2][3] = {{1, 3, 0}, {-1, 5, 9}};

int c[][3] = {{1, 3, 0}, {-1, 5, 9}};

int c[2][3] = {1, 3, 0, -1, 5, 9};


Initializing multi dimensional array

Initialization of a 3d array

int test[2][3][4] = {

{{3, 4, 2, 3}, {0, -3, 9, 11}, {23, 12, 23, 2}},

{{13, 4, 56, 3}, {5, 9, 3, 5}, {3, 1, 4, 9}}};


Addition of multidimensional matrix
#include <stdio.h>
int main()
{
int sum[2][2],i,j,r=2,c=2;
int a[2][2]={{1,2},{3,4}};
int b[2][2]={{1,1},{1,1}};
for(i=0;i<r;i++)
for(j=0;j<c;j++)
sum[i][j]=a[i][j]+b[i][j];
printf("Matrix Addition\n");
for(i=0;i<r;i++)
for(j=0;j<c;j++){
printf("%d ",sum[i][j]);
if(j==c-1){
printf("\n");
}
}
return 0;
Infinite Loop
An infinite loop is a looping construct that does not terminate the loop and executes the loop
forever. It is also called an indefinite loop or an endless loop. It either produces a continuous
output or no output.

An infinite loop is useful for those applications that accept the user input and generate the
output continuously until the user exits from the application manually. In the following situations,
this type of loop can be used:

● All the operating systems run in an infinite loop as it does not exist after performing some
task. It comes out of an infinite loop only when the user manually shuts down the system.
● All the servers run in an infinite loop as the server responds to all the client requests. It
comes out of an indefinite loop only when the administrator shuts down the server
manually.
● All the games also run in an infinite loop. The game will accept the user requests until the
user exits from the game.
For loop (infinite)
Syntax: for(; ;)
1. #include <stdio.h>
2. int main()
3. {
4. for(;;)
5. {
6. printf("Hello World\n");
7. }
8. return 0;
9. }
While loop (infinite)
Syntax: while(1)
1. #include <stdio.h>
2. int main()
3. {
4. int i=0;
5. while(1)
6. {
7. i++;
8. printf("Value of i is :%d\n",i);
9. }
10. return 0;
11. }
Order of precedence with regards to operators in C
● Unary Operators (++,--,....)
● Mathematical Operators (* / % followed by + - )
● Relational Operators ( <, <=, >, >=) followed by (== and !=)
● Logical Operators (&& ||)
● Assignment Operator (=)
Questions
● What would happen to X in this expression: X += 15; (assuming the value of X is 5).
● In C language, the variables NAME, name, and Name are all the same. TRUE or
FALSE?
● What will be the outcome of the following conditional statement if the value of variable s
is 10? s >=10 && s < 25 && s!=12
● What does the format %10.2 mean when included in a printf statement?
● How do you access the values within an array?
● What is the difference between =value and ==value?
● What is the equivalent code of the following statement in WHILE LOOP format?

for (a=1; a<=100; a++)

printf ("%d\n", a * a);


#include <stdio.h>
int main()
{
char a,b,c;
int d;
a='A';
b='4';
c=a+b;
d=a+b;
printf("C has value = %c\n",c);
printf("d has value = %d",d);
return 0;
}
ASCII
The full form of ASCII is the American Standard Code for information interchange. It is a
character encoding scheme used for electronics communication. Each character or a special
character is represented by some ASCII code, and each ascii code occupies 7 bits in
memory.

In C programming language, a character variable does not contain a character value itself
rather the ascii value of the character variable. The ascii value represents the character
variable in numbers, and each character variable is assigned with some number range from
0 to 127. For example, the ascii value of 'A' is 65.

In the above example, we assign 'A' to the character variable whose ascii value is 65, so 65
will be stored in the character variable rather than 'A'.
Example
#include <stdio.h>
int main()
{
char ch;
printf("Enter a character:");
scanf("%c",&ch); // user input
printf("\n The ascii value of the ch variable is : %d", ch);
return 0;
}
Strings
In C programming, a string is a sequence of characters terminated with a null
character \0. For example:

char c[ ] = “c string”

When the compiler encounters a sequence of characters enclosed in the double


quotation marks, it appends a null character \0 at the end by default.
How to declare string?
char s[5];

Here, we have declared a string of 5 characters.


How to initialize strings?
You can initialize strings in a number of ways
char c[] = "abcd";

char c[50] = "abcd";

char c[] = {'a', 'b', 'c', 'd', '\0'};

char c[5] = {'a', 'b', 'c', 'd', '\0'};


Assigning values to strings
char c[100];

c = "C programming"; // Error! array type is not assignable.

Read String from the user

You can use the scanf() function to read a string.

The scanf() function reads the sequence of characters until it encounters


whitespace (space, newline, tab, etc.).
#include <stdio.h>
Also notice that we have used the code name
int main() instead of &name with scanf().
{ This is because name is a char array, and we
char name[20]; know that array names decay to pointers in C.

printf("Enter name: "); Thus, the name in scanf() already points to the
address of the first element in the string, which
scanf("%s", name); is why we don't need to use &

printf("Your name is %s.", name);


return 0;
}
You can use the gets() function to read a line of string.
And, you can use puts() to display the string.
#include <stdio.h>
int main()
{
char name[30];
printf("Enter name: ");
gets(name); // read string
printf("Name: ");
puts(name); // display string
return 0;
}
#include <stdio.h>
int main()
{
char name[30];
printf("Enter name: ");
fgets(name, sizeof(name), stdin); // read string
printf("Name: ");
puts(name); // display string
return 0;
}
You need to often manipulate strings according to the need of a problem. Most, if
not all, of the time string manipulation can be done manually but, this makes
programming complex and large.

To solve this, C supports a large number of string handling functions in the


standard library "string.h".
Function Work of Function

strlen() computes string's length

strcpy() copies a string to another

strcat() concatenates(joins) two strings

strcmp() compares two strings

strlwr() converts string to lowercase

strupr() converts string to uppercase


strlen()
#include <stdio.h>
#include <string.h>
int main()
{
char a[20]="Program";
char b[20]={'P','r','o','g','r','a','m','\0'};
// using the %zu format specifier to print size_t
printf("Length of string a = %d \n",strlen(a));
printf("Length of string b = %d \n",strlen(b));
return 0;
}
strcpy() Syntax: strcpy(char* destination, const char* source);
#include <stdio.h>
#include <string.h>
int main() {
char str1[20] = "C programming";
char str2[20];
// copying str1 to str2
strcpy(str2, str1);
puts(str2); // C programming
return 0;
}
strcat: strcat(char *destination, const char *source)
#include <stdio.h>
#include <string.h>
int main() {
char str1[100] = "This is ", str2[] = "C programming";
// concatenates str1 and str2
// the resultant string is stored in str1.
strcat(str1, str2);
puts(str1);
puts(str2);
return 0;
strcmp()
The strcmp() compares two strings character by character. If the strings are equal,
the function returns 0.

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


#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "abCd", str2[] = "abcd", str3[] = "abcD";
int result;
// comparing strings str1 and str2
result = strcmp(str1, str2);
printf("strcmp(str1, str2) = %d\n", result);
// comparing strings str1 and str3
result = strcmp(str2, str3);
printf("strcmp(str2, str3) = %d\n", result);
return 0;
}
Read full string after whitespace using scanf
The format specifier "%[^\n]" tells to the compiler that read the characters until
"\n" is not found.

#include <stdio.h>
int main()
{
char name[30];
printf("Enter name: ");
scanf("%[^\n]",name);

printf("Name is: %s\n",name);


return 0;
}
WAP to find the frequency of a character
#include <stdio.h>
int main() {
char str[1000], ch;
int count = 0;

printf("Enter a string: ");


fgets(str, sizeof(str), stdin);

printf("Enter a character to find its frequency: ");


scanf("%c", &ch);

for (int i = 0; str[i] != '\0'; ++i) {


if (ch == str[i])
++count;
}

printf("Frequency of %c = %d", ch, count);


return 0;
}
C Program to Count the Number of Vowels, Consonants
#include <stdio.h> // if it is not a vowel and if it is an alphabet, it is a consonant
void main() { else if ((line[i] >= 'a' && line[i] <= 'z')) {
char line[150]; ++consonant;
int vowels, consonant, digit, space; }
// initialize all variables to 0
vowels = consonant = digit = space = 0; // check if the character is a digit
// get full line of string input else if (line[i] >= '0' && line[i] <= '9') {
printf("Enter a line of string: "); ++digit;
fgets(line, sizeof(line), stdin); }
// loop through each character of the string
for (int i = 0; line[i] != '\0'; ++i) { // check if the character is an empty space
// convert character to lowercase else if (line[i] == ' ') {
line[i] = tolower(line[i]); ++space;
// check if the character is a vowel }
if (line[i] == 'a' || line[i] == 'e' || line[i] == 'i' || }
line[i] == 'o' || line[i] == 'u') { printf("Vowels: %d", vowels);
// increment value of vowels by 1 printf("\nConsonants: %d", consonant);
++vowels; printf("\nDigits: %d", digit);
} printf("\nWhite spaces: %d", space);
}
#include<stdio.h>
#include<string.h>
int main()
Reverse a string {
char s1[100], s2[100];
#include<stdio.h>
int i, j,;
#include<string.h> printf("Enter a string: ");
gets(s1);
int main() //find String length
for(i=0; s1[i]!='\0';i++);
{ printf("The length of the string is %d\n",i);
i=strlen(s1)-1;
char str[100];
//Copying string in reverse order
printf("Enter string: "); for(j=0; i>=0; j++)
{
fgets(str, sizeof(str), stdin); s2[j]=s1[i];
i–;
strrev(str); }
s2[j]='\0';
printf("The reverse of the string is: ");
puts(str); printf("The reverse string is:");
puts(s2);
return 0; } return 0;
#include<stdio.h>
#include<string.h>
main()
{
int i,j,len;
char c[]="Programming";
len=strlen(c);
for(i=0;i<len;i++)
{
for(j=0;j<=i;j++)
{
printf("%c",c[j]);
}
printf("\n");
}
}

You might also like