Uploaded by Pranav Coder

CP file BCA

advertisement
PROGRAMMING IN C
BCA FILE MANUAL (1ST YEAR (1ST
SEMESTER)
1
Q1. Operators and data types in C
a) Write a program to print the size of all the data types supported by C and its
range
#include<stdio.h>
int main() {
int intType;
float floatType;
double doubleType;
char charType;
// sizeof evaluates the size of a variable
printf("Size of int: %zu bytes\n", sizeof(intType));
printf("Size of float: %zu bytes\n", sizeof(floatType));
printf("Size of double: %zu bytes\n", sizeof(doubleType));
printf("Size of char: %zu byte\n", sizeof(charType));
return 0;
}
Output
Size
Size
Size
Size
of
of
of
of
int: 4 bytes
float: 4 bytes
double: 8 bytes
char: 1 byte
b) Write a program to convert temperature from Fahrenheit to Celsius
#include <stdio.h>
int main()
{
float celsius, fahrenheit;
/* Input temperature in fahrenheit */
printf("Enter temperature in Fahrenheit: ");
scanf("%f", &fahrenheit);
/* Fahrenheit to celsius conversion formula */
celsius = (fahrenheit - 32) * 5 / 9;
/* Print the value of celsius */
printf("%.2f Fahrenheit = %.2f Celsius", fahrenheit, celsius);
2
return 0;
}
Input
Temperature in fahrenheit = 205
Output
Temperature in celsius = 96.11 C
c) Write a program to find simple interest and compound interest
void main()
{
float p, r, t, a, si, ci;
printf("Enter Principle=");
scanf("%f",&p);
printf("Enter Rate=");
scanf("%f",&r);
printf("Enter Time=");
scanf("%f",&t);
si=(p*r*t)/100;
printf("Simple Interest=%f",si);
a = p*(pow((1 + r / 100), t));
ci = a - p;
printf("\nCompound Interest=%f",ci);
}
OUTPUT:
Enter principal : 5000 ↲
Enter time: 2 ↲
Enter rate : 18 ↲
Simple Interest = 1800.000
Compound Interest = 1962.000
3
Q2. Control Statements
a) Write a program to check whether the given number is even number or not
#include <stdio.h>
int main() {
int num;
printf("Enter an integer: ");
scanf("%d", &num);
// true if num is perfectly divisible by 2
if(num % 2 == 0)
printf("%d is even.", num);
else
printf("%d is odd.", num);
return 0;
}
Output
Enter an integer: 33
33 is odd.
b) Write a program to accept 3 numbers and find the largest
// C program to find the maximum number out of the three
// given numbers using if-else statement
#include <stdio.h>
int main()
{
int A, B, C;
printf("Enter the numbers A, B and C: ");
scanf("%d %d %d", &A, &B, &C);
// finding max using compound expressions
if (A >= B && A >= C)
printf("%d is the largest number.", A);
else if (B >= A && B >= C)
printf("%d is the largest number.", B);
else
(C >= A && C >= B)
printf("%d is the largest number.", C);
return 0;
4
}
OUTPUT
Enter three numbers:
4
3
5
5 is the largest number.
c) Write a program to count different vowels in line of text
#include <stdio.h>
int main()
{
int c = 0, count = 0;
char s[1000];
printf("Input a string\n");
gets(s);
while (s[c] != '\0')
{
if (s[c] == 'a' || s[c] == 'A' || s[c] == 'e' || s[c] == 'E' || s[c] == 'i' || s[c] == 'I' || s[c]
=='o' || s[c]=='O' || s[c] == 'u' || s[c] == 'U')
count++;
c++;
}
printf("Number of vowels in the string: %d", count);
return 0;
}
OUTPUT
Input a string
You can learn anything
Number of vowels in the string: 7
d) Write a program to accept two numbers and perform various arithmetic
operations (+,-,*,/) based on the symbol entered.
#include <stdio.h>
int main() {
int p, q;
int sum, sub, mul, mod;
5
float div;
// It will take two integer numbers
printf("Enter any two positive integer numbers:\n");
scanf("%d%d", &p, &q);
// It will perform all arithmetic operations
sum = p + q;
sub = p - q;
mul = p * q;
div = (float)p / q;
mod = p % q;
// It will print the final output of the program
printf("\n");
printf("Addition of
%d + %d = %d\n", p, q, sum);
printf("Subtraction of %d - %d = %d\n", p, q, sub);
printf("Multiplication of %d * %d = %d\n", p, q, mul);
printf("Division of
%d / %d = %f\n", p, q, div);
printf("Modulus of
%d %% %d = %d\n", p, q, mod);
return 0;
}
OUTPUT
Enter any two positive integer numbers:
5
7
Addition of
5 + 7 = 12
Subtraction of 5 - 7 = -2
Multiplication of 5 * 7 = 35
Division of
5 / 7 = 0.714286
Modulus of
5%7=5
e) Write a program to find factorial of a number
#include <stdio.h>
int main() {
int n, i;
unsigned long long fact = 1;
printf("Enter an integer: ");
scanf("%d", &n);
// shows error if the user enters a negative integer
if (n < 0)
printf("Error! Factorial of a negative number doesn't exist.");
else {
for (i = 1; i <= n; ++i) {
fact *= i;
}
6
printf("Factorial of %d = %llu", n, fact);
}
return 0;
}
OUTPUT
Enter an integer: 10
Factorial of 10 = 3628800
f) Write a program to check whether a number is prime or not
#include <stdio.h>
int main() {
int n, i, flag = 0;
printf("Enter a positive integer: ");
scanf("%d", &n);
// 0 and 1 are not prime numbers
// change flag to 1 for non-prime number
if (n == 0 || n == 1)
flag = 1;
for (i = 2; i <= n / 2; ++i) {
// if n is divisible by i, then n is not prime
// change flag to 1 for non-prime number
if (n % i == 0) {
flag = 1;
break;
}
}
// flag is 0 for prime numbers
if (flag == 0)
printf("%d is a prime number.", n);
else
printf("%d is not a prime number.", n);
return 0;
}
OUTPUT
Enter a positive integer: 29
29 is a prime number.
7
g) Write a program to print all prime numbers between any 2 given limits.
#include <stdio.h>
int main() {
int low, high, i, flag;
printf("Enter two numbers(intervals): ");
scanf("%d %d", &low, &high);
printf("Prime numbers between %d and %d are: ", low, high);
// iteration until low is not equal to high
while (low < high) {
flag = 0;
// ignore numbers less than 2
if (low <= 1) {
++low;
continue;
}
// if low is a non-prime number, flag will be 1
for (i = 2; i <= low / 2; ++i) {
if (low % i == 0) {
flag = 1;
break;
}
}
if (flag == 0)
printf("%d ", low);
// to check prime for the next number
// increase low by 1
++low;
}
return 0;
}
OUTPUT
Enter two numbers(intervals): 20
50
Prime numbers between 20 and 50 are: 23 29 31 37 41 43 47
h) Write a program to check whether a number is palindrome or not
#include<stdio.h>
int main()
8
{
int n,r,sum=0,temp;
printf("enter the number=");
scanf("%d",&n);
temp=n;
while(n>0)
{
r=n%10;
sum=(sum*10)+r;
n=n/10;
}
if(temp==sum)
printf("palindrome number ");
else
printf("not palindrome");
return 0;
}
OUTPUT
Enter an integer: 1001
1001 is a palindrome.
i) Write a program to print all the Armstrong numbers between any 2 given
limits.
#include <math.h>
#include <stdio.h>
int main() {
int low, high, number, originalNumber, rem, count = 0;
double result = 0.0;
printf("Enter two numbers(intervals): ");
scanf("%d %d", &low, &high);
printf("Armstrong numbers between %d and %d are: ", low, high);
// swap numbers if high < low
if (high < low) {
high += low;
low = high - low;
high -= low;
}
// iterate number from (low + 1) to (high - 1)
// In each iteration, check if number is Armstrong
for (number = low + 1; number < high; ++number) {
originalNumber = number;
// number of digits calculation
while (originalNumber != 0) {
originalNumber /= 10;
9
++count;
}
originalNumber = number;
// result contains sum of nth power of individual digits
while (originalNumber != 0) {
rem = originalNumber % 10;
result += pow(rem, count);
originalNumber /= 10;
}
// check if number is equal to the sum of nth power of individual digits
if ((int)result == number) {
printf("%d ", number);
}
// resetting the values
count = 0;
result = 0;
}
return 0;
}
OUTPUT
Enter two numbers(intervals): 200
2000
Armstrong numbers between 200 and 2000 are: 370 371 407 1634
10
Q3. Arrays and Strings
a) Write a program to find largest element in an array
int largest(int arr[], int n)
{
int i;
// Initialize maximum element
int max = arr[0];
// Traverse array elements from second and
// compare every element with current max
for (i = 1; i < n; i++)
if (arr[i] > max)
max = arr[i];
return max;
}
// Driver code
int main()
{
int arr[] = { 10, 324, 45, 90, 9808 };
int n = sizeof(arr) / sizeof(arr[0]);
// Function call
printf("Largest in given array is %d", largest(arr, n));
return 0;
}
OUTPUT
Enter the number of elements (1 to 100): 5
Enter number1: 34.5
Enter number2: 2.4
Enter number3: -35.5
Enter number4: 38.7
Enter number5: 24.5
Largest element = 38.70
b) Write a program to find sum and average of numbers stored in an array.
#include<stdio.h>
int main()
{
float a[100], sum=0, avg;
int i, n;0
11
printf("Enter n: ");
scanf("%d", &n);
/* Reading array */
printf("Enter numbers:\n");
for(i=0; i< n; i++)
{
printf("a[%d] = ", i);
scanf("%f", &a[i]);
}
/* Finding sum */
for(i=0; i< n; i++)
{
sum = sum + a[i];
}
/* Calculating average */
avg = sum/n;
/* Displaying Result */
printf("Sum is %f\n", sum);
printf("Average is %f", avg);
return 0;
}
OUTPUT
Enter n: 4↲
Enter numbers:
a[0] = 11.5↲
a[1] = 5.5↲
a[2] = 8.5↲
a[3] = 10.5↲
Sum is 36.000000
Average is 9.000000
c) Write a program to check whether a string is a Palindrome
#include <stdio.h>
#include <string.h>
int main(){
char string1[20];
int i, length;
int flag = 0;
printf("Enter a string:");
scanf("%s", string1);
12
length = strlen(string1);
for(i=0;i < length ;i++){
if(string1[i] != string1[length-i-1]){
flag = 1;
break;
}
}
if (flag) {
printf("%s is not a palindrome", string1);
}
else {
printf("%s is a palindrome", string1);
}
return 0;
}
OUTPUT
Enter a String: wow
Wow is a palindrome
d) Write a program to perform matrix addition
#include <stdio.h>
int main() {
int a[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int b[3][3] = {{9, 8, 7}, {6, 5, 4}, {3, 2, 1}};
int c[3][3];
int i, j;
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
c[i][j] = a[i][j] + b[i][j];
}
}
printf("Result of addition: \n");
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
printf("%d ", c[i][j]);
}
printf("\n");
13
}
return 0;
}
OUPUT
Result of addition:
10 10 10
10 10 10
10 10 10
e) Write a program to perform matrix multiplication
#include<stdio.h>
#include<stdlib.h>
int main(){
int a[10][10],b[10][10],mul[10][10],r,c,i,j,k;
system("cls");
printf("enter the number of row=");
scanf("%d",&r);
printf("enter the number of column=");
scanf("%d",&c);
printf("enter the first matrix element=\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("enter the second matrix element=\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf("%d",&b[i][j]);
}
}
printf("multiply of the matrix=\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
mul[i][j]=0;
for(k=0;k<c;k++)
{
mul[i][j]+=a[i][k]*b[k][j];
}
14
}
}
//for printing result
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf("%d\t",mul[i][j]);
}
printf("\n");
}
return 0;
}
OUTPUT
enter the number of row=3
enter the number of column=3
enter the first matrix element=
111
222
333
enter the second matrix element=
111
222
333
multiply of the matrix=
666
12 12 12
18 18 18
15
4. Functions and Recursion
a) Write a program to find the roots of a quadratic equation using function.
# include<stdio.h>
# include<math.h>
int main () {
float a,b,c,r1,r2,d;
printf ("Enter the values of a b c: ");
scanf (" %f %f %f", &a, &b, &c);
d= b*b - 4*a*c;
if (d>0) {
r1 = -b+sqrt (d) / (2*a);
r2 = -b-sqrt (d) / (2*a);
printf ("The real roots = %f %f", r1, r2);
}
else if (d==0) {
r1 = -b/(2*a);
r2 = -b/(2*a);
printf ("Roots are equal =%f %f", r1, r2);
}
else
printf("Roots are imaginary");
return 0;
}
OUTPUT
Case 1:
Enter the values of a b c: 1 4 3
The real roots = -3.000000 -5.000000
Case 2:
Enter the values of a b c: 1 2 1
Roots are equal =-1.000000 -1.000000
Case 3:
Enter the values of a b c: 1 1 4
Roots are imaginary
b) Write a recursive program to find the factorial of a number.
#include<stdio.h>
long int multiplyNumbers(int n);
16
int main() {
int n;
printf("Enter a positive integer: ");
scanf("%d",&n);
printf("Factorial of %d = %ld", n, multiplyNumbers(n));
return 0;
}
long int multiplyNumbers(int n) {
if (n>=1)
return n*multiplyNumbers(n-1);
else
return 1;
}
OUTPUT
Enter a positive integer: 6
Factorial of 6 = 720
c) Write a recursive program to find the nth Fibonacci number.
#include <stdio.h>
int fibo(int);
int main()
{
int num;
int result;
printf("Enter the nth number in fibonacci series: ");
scanf("%d", &num);
if (num < 0)
{
printf("Fibonacci of negative number is not possible.\n");
}
else
{
result = fibo(num);
printf("The %d number in fibonacci series is %d\n", num, result);
}
return 0;
}
int fibo(int num)
{
if (num == 0)
{
17
return 0;
}
else if (num == 1)
{
return 1;
}
else
{
return(fibo(num - 1) + fibo(num - 2));
}
}
OUTPUT
Enter the nth number in fibonacci series: 8
The 8 number in fibonacci series is 21
18
5. Structures and Unions
a) Create an employee structure and display the same.
#include <stdio.h>
struct Employee
{
int id, age, salary;
char name[30], designation[30], department[30];
};
int main()
{
struct Employee e;
printf("Enter the id of the Employee: ");
scanf("%d", &e.id);
printf("Enter the age of the Employee: ");
scanf("%d", &e.age);
printf("Enter the name of the Employee: ");
getchar();
fgets(e.name, 30, stdin);
printf("Enter the designation of the Employee: ");
fgets(e.designation, 30, stdin);
printf("Enter the department of the Employee: ");
fgets(e.department, 30, stdin);
printf("Enter the salary of the Employee: ");
scanf("%d", &e.salary);
printf("\nEmployee Details:\n");
printf("Employee Id: %d\n", e.id);
printf("Employee Name: %s", e.name);
printf("Employee age: %d\n", e.age);
printf("Employee designation: %s", e.designation);
printf("Employee department: %s", e.department);
printf("Employee salary: %d\n", e.salary);
19
return 0;
}
OUTPUT
Enter the id of the Employee: 1231
Enter the age of the Employee: 21
Enter the name of the Employee: James Smith
Enter the designation of the Employee: Manager
Enter the department of the Employee: Dept-A
Enter the salary of the Employee: 120000
Employee Details:
Employee Id: 1231
Employee Name: James Smith
Employee age: 21
Employee designation: Manager
Employee department: Dept-A
Employee salary: 120000
b) Create a student database storing the roll no, name, class etc and sort by name.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// struct person with 3 fields
struct Student {
char* name;
int id;
char age;
};
// setting up rules for comparison
// to sort the students based on names
int comparator(const void* p, const void* q)
{
20
return strcmp(((struct Student*)p)->name,
((struct Student*)q)->name);
}
// Driver program
int main()
{
int i = 0, n = 5;
struct Student arr[n];
// Get the students data
arr[0].id = 1;
arr[0].name = "bd";
arr[0].age = 12;
arr[1].id = 2;
arr[1].name = "ba";
arr[1].age = 10;
arr[2].id = 3;
arr[2].name = "bc";
arr[2].age = 8;
arr[3].id = 4;
arr[3].name = "aaz";
arr[3].age = 9;
arr[4].id = 5;
arr[4].name = "az";
arr[4].age = 10;
// Print the Unsorted Structure
printf("Unsorted Student Records:\n");
for (i = 0; i < n; i++) {
printf("Id = %d, Name = %s, Age = %d \n",
arr[i].id, arr[i].name, arr[i].age);
}
21
// Sort the structure
// based on the specified comparator
qsort(arr, n, sizeof(struct Student), comparator);
// Print the Sorted Structure
printf("\n\nStudent Records sorted by Name:\n");
for (i = 0; i < n; i++) {
printf("Id = %d, Name = %s, Age = %d \n",
arr[i].id, arr[i].name, arr[i].age);
}
return 0;
}
OUTPUT
Unsorted Student Records:
Id = 1, Name = bd, Age = 12
Id = 2, Name = ba, Age = 10
Id = 3, Name = bc, Age = 8
Id = 4, Name = aaz, Age = 9
Id = 5, Name = az, Age = 10
Student Records sorted by Name:
Id = 4, Name = aaz, Age = 9
Id = 5, Name = az, Age = 10
Id = 2, Name = ba, Age = 10
Id = 3, Name = bc, Age = 8
Id = 1, Name = bd, Age = 12
22
6. Pointers
a) Write a function to swap two numbers using pointers
void swap(int*, int*);
int main()
{
int a, b;
printf("Enter values for a and b\n");
scanf("%d%d", &a, &b);
printf("\n\nBefore swapping: a = %d and b = %d\n", a, b);
swap(&a, &b);
printf("\nAfter swapping: a = %d and b = %d\n", a, b);
return 0;
}
void swap(int *x, int *y)
{
int temp;
temp = *x;
*x = *y;
*y = temp;
}
OUTPUT
Enter values for a and b
100
200
Before swapping: a = 100 and b = 200
After swapping: a = 200 and b = 100
b. Write a program to access an array of integers using pointers
#include <stdio.h>
int main() {
int data[5];
printf("Enter elements: ");
for (int i = 0; i < 5; ++i)
scanf("%d", data + i);
printf("You entered: \n");
for (int i = 0; i < 5; ++i)
23
printf("%d\n", *(data + i));
return 0;
}
OUTPUT
Enter elements:
1
2
3
5
4
You entered:
1
2
3
5
4
24
7. Files
a. Create a file and store some records in it. Display the contents of the same. Count
numbers of characters, words and lines in the file.
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE * file;
char path[100];
char ch;
int characters, words, lines;
/* Input path of files to merge to third file */
printf("Enter source file path: ");
scanf("%s", path);
/* Open source files in 'r' mode */
file = fopen(path, "r");
/* Check if file opened successfully */
if (file == NULL)
{
printf("\nUnable to open file.\n");
printf("Please check if file exists and you have read privilege.\n");
exit(EXIT_FAILURE);
}
/*
* Logic to count characters, words and lines.
*/
characters = words = lines = 0;
while ((ch = fgetc(file)) != EOF)
{
characters++;
/* Check new line */
if (ch == '\n' || ch == '\0')
lines++;
/* Check words */
if (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\0')
words++;
}
/* Increment words and lines for last word */
if (characters > 0)
{
25
words++;
lines++;
}
/* Print file statistics */
printf("\n");
printf("Total characters = %d\n", characters);
printf("Total words
= %d\n", words);
printf("Total lines
= %d\n", lines);
/* Close files to release resources */
fclose(file);
return 0;
}
OUTPUT
Suppose if data\file3.txt contains
I love programming.
Working with files in C programming is fun.
I am learning C programming at Codeforwin.
Enter source file path: data\file3.txt
Total characters = 106
Total words
Total lines
= 18
=3
26
Download