[go: up one dir, main page]

0% found this document useful (0 votes)
59 views19 pages

CP Mid2

The document contains C code snippets for various programming problems. The first snippet shows a program that splits an integer into two prime numbers. The second snippet stores student name and marks in a file. The third snippet calculates the sum of natural numbers using recursion.

Uploaded by

anuragak
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)
59 views19 pages

CP Mid2

The document contains C code snippets for various programming problems. The first snippet shows a program that splits an integer into two prime numbers. The second snippet stores student name and marks in a file. The third snippet calculates the sum of natural numbers using recursion.

Uploaded by

anuragak
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/ 19

1.

Program to split an integer into 2 prime numbers


#include <stdio.h>
int checkPrime(int n);
int main()
{
int n, i, flag = 0;

printf("Enter a positive integer: ");


scanf("%d", &n);

for(i = 2; i <= n/2; ++i)


{
if (checkPrime(i) && checkPrime(n - i))
{
printf("%d = %d + %d\n", n, i, n - i);
}

}
}

int checkPrime(int n)
{
int i, isPrime = 1;
for(i = 2; i <= n/2; ++i)
{
if(n % i == 0)
{
isPrime = 0;
break;
}
}
return isPrime;
}

2. Program to store name, marks of n students in a file


#include <stdio.h>
#include <stdlib.h>
int main()
{
char name[50];
int marks, i, n;
printf("Enter number of students: ");
scanf("%d", &n);
FILE *fptr;
fptr = (fopen("student.txt", "w"));
if(fptr == NULL)
{
printf("Error!");
exit(1);
}

for(i = 0; i < n; ++i)


{
printf("For student %d\nEnter name: ", i+1);
scanf("%s", name);

printf("Enter marks: ");


scanf("%d", &marks);

fprintf(fptr,"Name: %s, Marks: %d \n", name, marks);


}

fclose(fptr);
return 0;
}

3. Sum of n natural numbers using recursion


#include <stdio.h>
int add(int n);

int main()
{
int n;
printf("Enter a number: ");
scanf("%d", &n);
printf("Sum = %d",add(n));
return 0;
}

int add(int n)
{
if(n != 0)
return n + add(n-1);
else
return n;
}
4. Average, using an array
#include<stdio.h>
void main(){
int a[100], n, i, sum = 0;
float avg;
printf("Enter the number of elements in the array: ");
scanf("%d", &n);
printf("Enter the elements:\n");
for(i = 0; i<n;i++){
scanf("%d", &a[i]);
sum += a[i];
}
printf("\nSum: %d, %d", sum, n);
avg = (float)sum/(float)n;
printf("\nAverage: %.2f", avg);

5. Prime Numbers between two limits


#include <stdio.h>
int checkPrime(int n);
int main()
{
int n1, n2, i;
printf("Enter two positive integers: ");
scanf("%d %d", &n1, &n2);
printf("Prime numbers between %d and %d are: ", n1, n2);
for(i=n1+1; i<n2; ++i)
{
if(checkPrime (i))
printf("%d ",i);
}
}
int checkPrime (int n){
int j, flag = 1;
for(j=2; j <= n/2; ++j){
if (n%j == 0){
flag =0;
break;
}
}
return flag;
}
6. Program to pass structures to a function, pass an address to a function
#include <stdio.h>
typedef struct Complex{
float real;
float imag;
} complex;
void addNumbers(complex c1, complex c2, complex *result);
int main(){
complex c1, c2, result;
printf("For first number,\n");
printf("Enter real part, imaginary part: ");
scanf("%f %f", &c1.real, &c1.imag);
printf("For second number, \n");
printf("Enter real part, imaginary part: ");
scanf("%f %f", &c2.real, &c2.imag);
addNumbers(c1, c2, &result);
printf("\nresult.real = %.1f\n", result.real);
printf("result.imag = %.1f", result.imag);
return 0;
}
void addNumbers(complex c1, complex c2, complex *result){
result->real = c1.real + c2.real;
result->imag = c1.imag + c2.imag;
}
7. Program to store details in a structure and display them
#include <stdio.h>
struct student{
char name[50];
int roll;
float marks;
} s[5];

int main(){
int i;
printf("Enter information of students:\n");
for(i=0; i<5; ++i){
s[i].roll = i+1;
printf("\nFor roll number%d,\n",s[i].roll);
printf("Enter name: ");
scanf("%s",s[i].name);
printf("Enter marks: ");
scanf("%f",&s[i].marks);
printf("\n");
}
printf("Displaying Information:\n\n");
for(i=0; i<5; ++i){
printf("\nRoll number: %d\n",i+1);
printf("Name: ");
puts(s[i].name);
printf("Marks: %.1f",s[i].marks);
printf("\n");
}
return 0;
}

8. Program to Calloc memory and find the largest element


#include <stdio.h>
#include <stdlib.h>
int main(){
int i, num;
float *data;
printf("Enter total number of elements(1 to 100): ");
scanf("%d", &num);
data = (float*) calloc(num, sizeof(float));
if(data == NULL){
printf("Error.");
exit(0);
}
printf("\n");
for(i = 0; i < num; ++i){
printf("Enter Number %d: ", i + 1);
scanf("%f", data + i);
}
for(i = 1; i < num; ++i){
if(*data < *(data + i))
*data = *(data + i);
}
printf("Largest element = %.2f", *data);
return 0;
}

9. Program to reverse a string


#include <stdio.h>
void reverseSentence();
int main(){
printf("Enter a sentence: ");
reverseSentence();
}
void reverseSentence(){
char c;
scanf("%c", &c);
if( c != '\n'){
reverseSentence();
printf("%c",c);
}
}

10. Program to read/write structures to a file using fwrite()


#include <stdio.h>
struct student{
char name[50];
int height;
};
int main(){
struct student s1[5], s2[5];
FILE *fptr;
int i;
fptr = fopen("studet.txt","wb");
for(i = 0; i < 5; ++i){
fflush(stdin);
printf("Enter Name: ");
gets(s1[i].name);
printf("Enter Height: ");
scanf("%d", &s1[i].height);
}
fwrite(s1, sizeof(s1), 1, fptr);
fclose(fptr);
fptr = fopen("file.txt", "rb");
fread(s2, sizeof(s2), 1, fptr);
for(i = 0; i < 5; ++i){
printf("Name: %s\tHeight: %d\n", s2[i].name, s2[i].height);
}
fclose(fptr);
}

11. Program to update employee details


#include<stdio.h>
#include<stdlib.h>
typedef struct employee{
int eID;
char *name;
}emp;
void update(char *a);
void add(char *a);
void show(char *a);
void main(){
int n;
char fname[30];
printf("Enter a filename: ");
scanf("%s", fname);
while (1)
{
printf("\n------------------\nMENU:\n");
printf("1.Add a record\n");
printf("2.Display the file\n");
printf("3.Update the record\n");
printf("Enter your choice:");
scanf("%d", &n);

switch(n)
{
case 1:
add(fname);
break;
case 2:
show(fname);
break;
case 3:
update(fname);
break;
case 4:
exit(0);
default:
printf("Wrong choice.\n");
}
}
}
void add(char *a){
FILE *fp;
fp = fopen(a, "a+");
emp* temp = (emp*) malloc(sizeof(emp));
temp -> name = (char*) malloc(50 * sizeof(char));
if(fp == NULL)
printf("Couldn't open FILE");
else{
printf("Enter Employee's id, name: ");
scanf("%d %s", &temp -> eID, temp -> name);
fwrite(&temp -> eID, sizeof(int), 1, fp);
fwrite(temp -> name, 50, 1, fp);
}
fclose(fp);
free(temp);
free(temp -> name);
}
void update(char *a){
FILE *fp;
int id;
char name[50];
fp = fopen(a, "a+");
emp *temp = (emp*) malloc(sizeof(emp));
temp -> name = (char*) malloc(50 * sizeof(char));
if(fp == NULL)
printf("Couldn't open FILE");
else{
printf("Enter Employee's id and name: ");
scanf("%d %s", &id, name);
fseek(fp, 0L, SEEK_SET);
fread(&temp -> eID, sizeof(int), 1, fp);
while(temp -> eID != id){
fread(&temp -> eID, sizeof(int), 1, fp);
fread(temp -> name, (50 * sizeof(char)), 1, fp);
}
printf("Record Found for eID: %d", temp -> eID);
fwrite(name, (50 * sizeof(char)), 1, fp);
}
fclose(fp);
free(temp);
free(temp -> name);
}
void show(char *a){
FILE *fp;
char name[50];
long size, n, ctr;
fp = fopen(a, "a+");
emp* temp = (emp*) malloc(sizeof(emp));
temp -> name = (char*) malloc(50 * sizeof(char));
if(fp == NULL)
printf("Couldn't open FILE");
else{
fseek(fp, 0L, SEEK_END);
size = ftell(fp);
int emps = sizeof(int) + 50;
rewind(fp);
n = size/emps;
printf("\nNo. Of Records: %d", n);
ctr = 0;
while(ctr < n){
fread(&temp -> eID, sizeof(int), 1, fp);
printf("\nID: %d", temp -> eID);
fread(temp -> name, (50 * sizeof(char)), 1, fp);
printf("Name: %s\n", temp -> name);
ctr++;
}
fclose(fp);
free(temp);
free(temp -> name);
}
}
12. Program to read 2 files and merge them alternatively
#include<stdio.h>
void main(){
char f1[20], f2[20], ch1, ch2, s[100];
FILE *fp1, *fp2, *fp3;
printf("Enter the two filenames: ");
scanf("%s %s", f1, f2);
fp1 = fopen(f1, "r");
fp2 = fopen(f2, "r");
fp3 = fopen("merged.txt", "w");

while(((ch1 = fgetc(fp1)) != EOF) && ((ch2 = fgetc(fp2)) != EOF)){


ungetc(ch1, fp1);
fgets(s, 99, fp1);
fputs(s, fp3);
//2
ungetc(ch2, fp2);
fgets(s, 99, fp2);
fputs(s, fp3);
}
printf("Result:\n");
rewind(fp3);
while((ch1 = fgetc(fp3)) != EOF){
ungetc(ch1, fp1);
fscanf(fp3, "%s", s);
printf("%s", s);
}

13. Program to extract function names from a C program


#include<stdio.h>
#include<string.h>
void extractName(int start, int end, char*);
void printName(int, int, char*);

void main(int arc, char **argv){


int i, bracl = 0, bracr = 0, semic = -1;
FILE *fp;
char line[200];
fp = fopen(argv[1], "r");
rewind(fp);
while((fgets(line, 200, fp)) != NULL){
bracl =0;
bracr = 0;
semic = -1;
for(i = 0; i< 200;i++){
if(line[i] == '(')
bracl = i;
if(line[i] == ')')
bracr = i;
if(line[i] == ';')
semic = i;
}
if(semic == -1 && bracl && bracr){
extractName(bracl, bracr, line);
}
}
_fcloseall();
}
void extractName(int start, int end, char *line){
int i, nst = start;
while(line[nst--] != ' ');
char prev = line[nst -1];
if((prev >= 65 && prev <= 90) || (prev >= 97 && prev <= 122)){
printf("\n");
for(i= nst + 1; i< start; i++){
printf("%c", line[i]);
}
}
}
void printName(int start, int end, char *line){
int i;
printf("\n");
for(i=start; i< end; i++){
printf("%c", line[i]);
}
}

14. Program to Count no of lines, blank lines and comment lines.


#include<stdio.h>
void main(int argc, char **argv){
int lines =0, blank_l =0 , comm = 0, i, prev, next;
FILE *fp;
char s[100];
fp = fopen(argv[1], "r");
while((fgets(s, 100, fp)) != NULL){
for(i =0; i<100;i++){
if(s[0] == '\n' && s[1] == '\0'){
blank_l++;
break;
}
else if(s[i] == '/' && s[i+1] == '/')
comm++;
}
lines++;
}
printf("\nNo of Lines: %d: ", lines);
printf("\nNo of Blank Lines: %d ", blank_l);
printf("\nNo of Comment Lines: %d ", comm);
}

15. Program to copy one file to another


#include <stdio.h>
void main(int argc,char **argv)
{
FILE *fp1, *fp2;
int ch;
int cursor = 0;
fp1 = fopen(argv[1], "r");
fp2 = fopen(argv[2], "w");
while(fgetc(fp1) != EOF){
cursor++;
}
rewind(fp1);
while(cursor--){
ch = fgetc(fp1);
fputc(ch, fp2);
}

}
16. Program to append one file to another #include <stdio.h>
#inclde<stdio.h>
void main(int argc,char **argv)
{
FILE *fp1, *fp2;
int ch;
int cursor = 0;
fp1 = fopen(argv[1], "a");
fp2 = fopen(argv[2], "r");
while(((ch = fgetc(fp2))) != EOF){
fputc(ch, fp1);
}

C++:
1. Program to find the factorial of a number.
#include<iostream>
using namespace std;
int main(){
int n,i,fact=1;
cout<<"Enter a number:";
cin>>n;
for(i=1;i<=n;i++){
fact=fact*i;
}
cout<< "Factorial: " << fact << endl;
}

2. Program to generate Fibonacci series


#include<iostream>
using namespace std;
int main(){
int n,i,a=0,b=1,temp=0;
cout<<"Enter no of terms:";
cin>>n;
cout<<a<<" "<<b<<" ";
for(i=0;i<n-2;i++){
temp=a+b;
a=b;
b=temp;
cout<<temp<<" ";
}
return 0;
}

3. Program to get prime nos. between 2 limits


#include<iostream>
using namespace std;
int main(){
int a,b,i,j,c=1;
cout<<"Enter the starting and ending numbers:";
cin>>a>>b;
for(i=a+1;i<b;i++){
for(j=2;j<=i/2;j++){
c=1;
if(i%j==0){
c=0;
break;
}
}
if(c==1)
cout<<i<<" ";
}
}

4. Program to check if a number is a perfect number or not


#include <iostream>
using namespace std;
int main(){
int n, i, sum=0;
cout << "Enter a number: ";
cin >> n;
for(i = 1; i < n; i++){
if(n % i == 0)
sum += i;
}
if(sum == n )
cout << n <<" is a perfect number"<<endl;
else
cout << n <<" is not a perfect number"<<endl;
return 0;
}
5. Program to check if a number is an Armstrong number
#include <iostream>
using namespace std;
int main(){
int origNum, num, rem, sum = 0;
cout << "Enter a no: ";
cin >> origNum;
for(num=origNum; num!=0; num/=10){
rem = num % 10;
sum += rem * rem * rem;
}
if(sum == origNum)
cout << origNum << " is an Armstrong number.";
else
cout << origNum << " is not an Armstrong number.";
return 0;
}

6. Program to print a ‘*’ pyramid.


#include <iostream>
using namespace std;
int main(){
int rows, i, j, space;
cout << "Enter number of rows: ";
cin >> rows;
for(i = 1; i <= rows; i++){
for(space = i; space < rows; space++){
cout <<" ";
}
for(j = 1; j <= (2*i - 1); j++){
cout << "*";
}
cout <<endl;
}
return 0;
}
7. Add 2 matrices
#include<iostream>
using namespace std;
int main(){
int a[10][10], b[10][10], c[10][10], i, j, m, n;
cout << "Enter number of rows and columns: " ;
cin >> m >> n;
cout << "Enter elements of first matrix: " << endl;
for(i = 0; i < m; i++){
for(j = 0; j < n; j++){
cin >> a[i][j];
}
}
cout << "Enter elements of second matrix: " << endl;
for(i = 0; i < m; i++){
for(j = 0; j < n; j++){
cin >> b[i][j];
}
}
cout << "Addition Matrix:" << endl;
for(i = 0; i < m; i++){
for(j = 0; j < n; j++){
c[i][j] = a[i][j] + b[i][j];
}
}
for(i=0;i<m;i++){
for(j=0;j<n;j++){
cout<< c[i][j] << " ";
}
cout << endl;
}
}

8. Multiply Matrices
#include<iostream>
using namespace std;
int main()
{
int a[10][10],b[10][10],c[10][10],i,j,k,m,n,p,q;
cout<<"Enter number of rows and columns of first matrix:";
cin>>m>>n;
cout<<"Enter number of rows and columns of second matrix:";
cin>>p>>q;
if(n!=p)
{
cout<<"Matrices cannot be multiplied!"<<endl;
}
cout<<"Enter elements of first matrix: ";
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
cin>>a[i][j];
}
}
cout<<"Enter elements of second matrix: ";
for(i=0;i<p;i++)
{
for(j=0;j<q;j++)
{
cin>>b[i][j];
}
}
cout<<"Mulplication Matrix:"<<endl;

for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
c[i][j]=0;
}
}
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
for(k=0;k<p;k++)
{
c[i][j]+=a[i][k]*b[k][j];
}
}
}

for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
cout<<c[i][j]<<" ";
}
cout<<endl;
}
}

9. Sort Elements
#include<iostream>
using namespace std;
int main(){
int n, i, a[50], j, temp;
cout<<"Enter total number of elements:";
cin>>n;
cout<<"Enter numbers:";
for(i=0; i<n; i++){
cin>>a[i];
}
for(i=0; i<(n-1); i++){
for(j=0; j<(n-i-1); j++){
if(a[j]>a[j+1]){
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
cout<<"Sorted list:"<<endl;
for(i=0; i<n; i++){
cout<<a[i]<<" ";
}
}

10. Max, Min from an Array


#include<iostream>
using namespace std;
int main(){
int a[50], max, min, i, n;
cout << "Enter number of elements:";
cin >> n;
cout << "Enter numbers:";
for(i=0;i<n;i++){
cin >> a[i];
}
max=a[0];
min=a[0];
for(i=0;i<n;i++){
if(max<a[i])
max=a[i];
if(min>a[i])
min=a[i];
}
cout<<"Max: "<< max << endl;
cout<<"Min: "<< min << endl;
}

You might also like