Assignment 1 – Programming in C
(Array & Strings)
Write and execute the code in C Programming Language for following exercises
based on Arrays and String.
Paste your code and Screenshot after writing and executing your code in
solution section provided in this document.
Exercise 1: Array Declaration and Initialization
Declare an integer array named myArray with a size of 5.
Initialize the array with values 1, 2, 3, 4, and 5.
Write a loop to print the elements of the array.
Solution:
#include <stdio.h>
void main()
{ int myArray[5],i;
for( i=0;i<5;i++)
{
myArray[i]=i+1;
}
for(i=0;i<5;i++)
{
printf("\n%d",myArray[i]);
}
}
Exercise 2: Array Sum
Declare an integer array named numbers with a size of 10.
Initialize the array with any 10 integer values.
Write a loop to calculate and print the sum of all elements in the array.
Solution:
#include <stdio.h>
void main()
{
int Numbers[10],sum,i;
sum=0;
printf("enter 10 numbers=\n");
for(i=0;i<10;i++)
{
scanf("%d",&Numbers[i]);
}
for(i=0;i<10;i++)
{
sum+=Numbers[i];
}
printf("\nSum of elements entered in Array = %d",sum);}
Exercise 3: Finding Maximum and Minimum
Declare an integer array named data with a size of 7.
Initialize the array with some integer values.
Write a program to find and print the maximum and minimum values in the
array.
Solution:
#include <stdio.h>
void main()
{int Data[7],i;
int max,min;
printf("\nenter 7 elements in array -\n");
for(i=0;i<7;i++)
{ scanf("%d",&Data[i]);
}
max=Data[0];
min=Data[0];
for(i=0;i<7;i++)
{if(Data[i]>max)
{max=Data[i];
}
if(Data[i]<min)
{min=Data[i];
}
}
printf("\nmax=%d\nmin=%d",max,min);
}
Exercise 4: String Declaration and Initialization
Declare a character array named myString to store a string of your choice.
Initialize the array with the chosen string.
Write code to print the string to the console.
Solution:
#include <stdio.h>
void main()
{
char mystring[20]="God is Love";
printf("%s",mystring);
}
Exercise 5: String Length
Declare a character array named inputString to store a string of your choice.
Initialize the array with the chosen string.
Write a program to calculate and print the length of the string.
Solution:
#include<stdio.h>
#include<string.h>
void main()
{
char inputString[20]="Indian Airforce";
int lenstring;
lenstring=strlen(inputString);
printf("entered string inputString=%s\n",inputString);
printf("\nlength of inputString = %d",lenstring);
}
Exercise 6: String Concatenation
Declare two character arrays named str1 and str2 to store two strings.
Initialize str1 and str2 with different strings.
Write a program to concatenate these two strings and print the result.
Solution:
#include<stdio.h>
#include<string.h>
void main()
{
char str1[20]="Indian";
char str2[20]="Airforce";
printf("entered str1 = %s\n entered str2 =%s\n",str1,str2);
strcat(str1,str2);
printf("str1 After strcat(str1,str2) = %s",str1);
}