C_CPP_Codes
114 subscribers
1 photo
About me :- alokosx.me

Books,notes and more at :- cp_resources.t.me

Discussion :- c_cpp_code.t.me
Download Telegram
Program to print Fibonacci series till 10th term using iteration :
#include <stdio.h>
long fibonacci(int n)
{
long f2 = 0,f1 = 1,f_old;
int i;
for(i =0;i<n;i++)
{
  f_old = f2;
  f2 = f2+f1;
  f1 = f_old;
}
return f2;
}

int main(void)
{
int n;
for(n=1;n<=10;n++)
{
  printf("%d term = %ld\n",n,fibonacci(n));
}
return 0;
}
Output :

1 term = 1
2 term = 1
3 term = 2
4 term = 3
5 term = 5
6 term = 8
7 term = 13
8 term = 21
9 term = 34
10 term = 55
Program to print fibonacci series using recursion :
#include <stdio.h>
long recursive_fibonacci(int n)
{
if(n<=1)
  return n;
else
  return(recursive_fibonacci(n-1)+ recursive_fibonacci(n-2));
}

int main(void)
{
int n;
for(n=1;n<=10;n++)
{
printf("%d term = %ld\n",n,recursive_fibonacci(n));
}
return 0;
}
Output :

1 term = 1
2 term = 1
3 term = 2
4 term = 3
5 term = 5
6 term = 8
7 term = 13
8 term = 21
9 term = 34
10 term = 55
Program to print factorial upto n using recursion :
#include <stdio.h>
long int factorial(int n)
{
if(n == 0 | n == 1)
return 1;
else
return(factorial(n-1)*n);
}

int main(void)
{
int how_many = 0,i;
printf("I want table of factorial upto :");
scanf("%d",&how_many);

for(i=0;i<=how_many;i++)
printf("\n%d!\t=\t%ld\n",i,factorial(i));
return 0;
}
Output :

I want table of factorial upto :10

0! = 1

1! = 1

2! = 2

3! = 6

4! = 24

5! = 120

6! = 720

7! = 5040

8! = 40320

9! = 362880

10! = 3628800
Program to initialize pointer and print its adress in hex and decimal format :
#include <stdio.h>
int main(void)
{
int a = 10,*p = &a;
printf("Adress of pointer is %p or %lu  and is pointed to %d",p,p,*p);
return 0;
}
Output :

Adress of pointer is 0x7fffe569a6f4 or 140737042294516  and is pointed to 10
Program to swap value of 2 variables using pointers :
#include <stdio.h>
void swap(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}

int main(void)
{
int a = 10,b = 20;
printf("Before swap:\n%d = \t%p or %lu \n%d = \t%p or %lu\n\n",a,&a,&a,b,&b,&b);
swap(&a,&b);
printf("After swap:\n%d = \t%p or %lu\n%d = \t%p or %lu\n",a,&a,&a,b,&b,&b);
}
Output :

Before swap:
10 = 0x7fe7e83c9c or 549351603356
20 = 0x7fe7e83c98 or 549351603352

After swap:
20 = 0x7fe7e83c9c or 549351603356
10 = 0x7fe7e83c98 or 549351603352
Program to take input of number of subject and grades from user in a array and calculate percentage:
#include <stdio.h>
int main(void)
{
int SIZE;
printf("Enter number of subjects:\n");
scanf("%d",&SIZE);
int grades[SIZE];
double sum = 0.0;
int i;
printf("\nEnter your grades:\n");
for(i = 0; i<SIZE; i++)
  scanf("%d",&grades[i]);
printf("\nYour grades are:\n");
for(i = 0; i<SIZE; i++)
  printf("%d\t",grades[i]);
printf("\n\n");
                                                                       for(i = 0; i<SIZE; i++)
sum += grades[i];
printf("Your percentage is %.2f %\n\n",sum/SIZE);
return 0;
}
Output :

Enter number of subjects:
5

Enter your grades:
98 96 94 92 90

Your grades are:
98      96      94      92      90

Yout percentage is 94.00 %
Program to bubble sort a array of numbers :
#include <stdio.h>
void swap(int *a,int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}

void print_array(int how_many,int data[],char *str)
{
int i;
printf("%s",str);

for(i = 0;i < how_many;i++)
printf("%d\t",data[i]);
}

void bubble(int data[],int how_many)
{
int i,j;
int go_on;
for(i=0 ; i<how_many ;i++)
{
print_array(how_many,data,"\nInside bubble\n");
printf("\nEnter a number to continue : ");
scanf("%d",&go_on);
for(j=how_many-1;j>i;j--)
if(data[j-1] > data[j])
swap(&data[j-1],&data[j]);
}
}

int main(void)
{
int SIZE;
printf("Enter no. of numbers you want to sort:");
scanf("%d",&SIZE);
int num[SIZE];
printf("Enter %d digits which you want to sort:\n",SIZE);
for(int i = 0; i<SIZE ; i++)
scanf("%d",&num[i]);
print_array(SIZE,num,"Numbers you entered:\n");
printf("\n\n");
bubble(num,SIZE);
print_array(SIZE,num,"\n\nSorted numbers:\n");
printf("\n\n");
return 0;
}
Output :

Enter no. of numbers you want to sort:5
Enter 5 digits which you want to sort:
27 91 63 29 15
Numbers you entered:
27 91 63 29 15


Inside bubble
27 91 63 29 15

Enter a number to continue : 0

Inside bubble
15 27 91 63 29

Enter a number to continue : 2

Inside bubble
15 27 29 91 63

Enter a number to continue : 9

Inside bubble
15 27 29 63 91

Enter a number to continue : 2

Inside bubble
15 27 29 63 91

Enter a number to continue : 4


Sorted numbers:
15 27 29 63 91
1
Program to merge sort 2 arrays :
#include <stdio.h>
void print_array(int how_many,int data[],char *str)
{
int i;

printf("%s",str);

for(i=0;i<how_many;i++)
printf("%d\t",data[i]);
}

void merge(int a[],int b[],int c[],int how_many)
{
int i=0,j=0,k=0;

while(i<how_many && j<how_many)
if(a[i]<b[j])
c[k++] = a[i++];
else
c[k++] = b[j++];
while(i<how_many)
c[k++] = a[i++];
while(j<how_many)
c[k++] = b[j++];
}

int main(void)
{
const int SIZE = 5;
int a[SIZE] = {45,57,69,81,93};
int b[SIZE] = {44,56,68,80,92};
int c[2*SIZE];
print_array(SIZE,a,"My grades are:\n");
printf("\n\n");
print_array(SIZE,b,"More grades:\n");
merge(a,b,c,SIZE);
printf("\n\n");
print_array(2*SIZE,c,"My sorted grades are:\n");
printf("\n\n");
}
Output :

My grades are:
45 57 69 81 93

More grades:
44 56 68 80 92

My sorted grades are:
44 45 56 57 68 69 80 81 92 93
Program to sort a array given by user using merge sort algorithm :
#include <stdio.h>
void print_array(int how_many,int data[],char *str)
{
int i;

printf("%s",str);

for(i=0;i<how_many;i++)
printf("%d\t",data[i]);
}

void merge(int a[],int b[],int c[],int how_many)
/* here a and b are of same size */
{
int i=0,j=0,k=0;

while(i<how_many && j<how_many)
if(a[i]<b[j])
c[k++] = a[i++];
else
c[k++] = b[j++];
while(i<how_many)
c[k++] = a[i++];
while(j<how_many)
c[k++] = b[j++];
}

void mergesort(int key[],int how_many)
/* how_many is in power of 2*/
{
int j,k;
int w[how_many];

for(k=1;k<how_many;k*=2)
{
for(j=0;j<how_many;j+=2*k)
merge(key+j,key+j+k,w+j,k);
for(j=0;j<how_many;j++)
key[j] = w[j];
}
}

int main(void)
{
int size,i;
printf("Enter size of array:");
scanf("%d",&size);
int a[size];
printf("Enter %d numbers:\n",size);
for(i=0;i<size;i++)
scanf("%d",&a[i]);
print_array(size,a,"Numbers you entered:\n\n");
printf("\n\n");
mergesort(a,size);
print_array(size,a,"Sorted numbers:\n\n");
printf("\n\n");
}
Output :

Enter size of array:8
Enter 8 numbers:
25 72 19 71 10 72 92 93
Numbers you entered:

25 72 19 71 10 72 92 93

Sorted numbers:

10 19 25 71 72 72 92 93
Program to define enum and print today and next day :
#include <stdio.h>
enum day{sun,mon,tue,wed,thr,fri,sat};
typedef enum day day;

void print_day(day d)
{
switch(d)
{
case sun:printf("Sunday\n");break;
case mon:printf("Monday\n");break;
case tue:printf("Tuesday\n");break;
case wed:printf("Wednesday\n");break;
case thr:printf("Thrusday\n");break;
case fri:printf("Friday\n");break;
case sat:printf("Saturday\n");break;
default :printf("This is not a valid day\n");break;
}
}

day next_day(day d)
{
return((d+1)%7);
}
int main(void)
{
day today = sun;
print_day(today);
print_day(next_day(today));
print_day(10);
return 0;
}
Ouput :

Sunday
Monday
This is not a valid day
Program to divide 2 number and remove divide by zero error using assert :
#include <stdio.h>
#include <assert.h>

int main(void)
{
double a,b;
while(1)
{
printf("Enter 2 number:");
scanf("%lf %lf",&a,&b);
assert(b!=0);
printf("a/b = %0.3lf\n",a/b);
}
return 0;
}
Output :

Enter 2 number:5 9
a/b = 0.556
Enter 2 number:10 2
a/b = 5.000
Enter 2 number:8 0
assert.c:15: int main(void): assertion "b!=0" failed
Aborted
Program to define employee details struct and print detail of 10 employee by generating random salary,ssn using srand function :
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

typedef enum dept{HR, Sales, Research, Software, Executive} dept;
typedef struct employee{
dept department;
int annual_sal;
unsigned int ssn;
} employee;

const char* dept_to_string(dept department) {
switch(department) {
case HR: return "HR";
case Sales: return "Sales";
case Research: return "Research";
case Software: return "Software";
case Executive: return "Executive";
default: return "Unknown";
}
}

int salary_gen(dept department)
{
int base_salary;
int offset = rand() % 10000;
if(department == HR)
base_salary = 100000;
else if(department == Sales)
base_salary = 30000;
else if(department == Research)
base_salary = 50000;
else if(department == Software)
base_salary = 60000;
else
base_salary = 80000; //for executive
return base_salary + offset;
}

int main(void)
{
srand(time(NULL)); // seed the random number generator
struct employee emp[10];
for(int i = 0; i < 10; i++)
{
emp[i].department = rand() % 5; // assign a random department
emp[i].annual_sal = salary_gen(emp[i].department); // generate a random salary
emp[i].ssn = rand() % 1000000000 + 100000000; // generate a random SSN

printf("Department: %s\n", dept_to_string(emp[i].department));
printf("Annual Salary: %d\n", emp[i].annual_sal);
printf("SSN: %u\n", emp[i].ssn);
}
}

Output :

Department: Executive
Annual Salary: 87266
SSN: 172060583


Department: Sales
Annual Salary: 35895
SSN: 803820085


Department: Executive
Annual Salary: 84152
SSN: 245588248


Department: Research
Annual Salary: 54407
SSN: 210668417


Department: HR
Annual Salary: 105633
SSN: 919574966


Department: Research
Annual Salary: 54230
SSN: 788124279


Department: Sales
Annual Salary: 35233
SSN: 506739685


Department: Software
Annual Salary: 62650
SSN: 725260271


Department: HR
Annual Salary: 104504
SSN: 550906751


Department: HR
Annual Salary: 100993
SSN: 480413954
👏1
Program to reverse a string using ADT stack :
#include <stdio.h>
#include <ctype.h>

#define MAX_LEN 1000 #define EMPTY -1
#define FULL MAX_LEN-1

typedef struct stack{char s[MAX_LEN];int top;} stack;

void reset(stack *stk){stk->top = EMPTY;} void push(char c,stack *stk)
{
stk->top++;
stk->s[stk->top] = c;
}

char pop(stack *stk){return (stk->s[stk->top--]);}
char top(stack *stk){return (stk->s[stk->top]);}

int is_empty(const stack *stk){return (stk->top==EMPTY);}
int is_full(const stack *stk){return(stk->top==FULL);}

int main(void)
{
stack stack_of_char;
char *str = "i am alok";
char str_back[10];
int i=0; reset(&stack_of_char); printf("Given string is: %s\n\nPushing to stack:\n\n",str);
while(str[i]!='\0')
{
printf("%c\n",str[i]);
push(str[i++],&stack_of_char);
}
i=0;
while(!is_empty(&stack_of_char)&&i<10)
{
str_back[i++]=pop(&stack_of_char);
}
printf("\nPoping from stack:\n\n");
i=0;
while(i<10)
{
printf("%c\n",str_back[i]);
i++;
}
printf("Reversed string is: %s\n",str_back);
return 0;
}
Output :

Given string is: i am alok

Pushing to stack:

i

a
m

a
l
o
k

Poping from stack:

k
o
l
a

m
a

i

Reversed string is: kola ma i
👍2
Code to create a singly linked list from a array :

#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>

typedef struct list {
int data; struct list *next;
} list;

int is_empty(const list *l) {
return (l == NULL);
}
list* create_list(int d) {
list* head = malloc(sizeof(list));
head->data = d;
head->next = NULL;
return head;
}
list* add_to_front(int d, list *h) {
list* head = create_list(d);
head->next = h;
return head;
}
list *array_to_list(int d[], int size) {
list *head = create_list(d[0]);
for(int i = 1; i < size; i++) {
head = add_to_front(d[i], head);
}
return head;
}
void print_list(list *h, char *title) {
printf("%s\n", title);
while(h != NULL) {
printf("%d :", h->data);
h = h->next;
}
}

int main(void) {
list list_of_int;
list* head = NULL;
int data[6] = {0,1,2,3,4,5};
head = array_to_list(data, 6);
print_list(head, "Singly linked list:");
printf("\n\n");
return 0;
}
Output :

Singly linked list:
5 :4 :3 :2 :1 :0 :
Code to create a file encryptor/decryptor with help of argc & argv :
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void printfile(FILE *ifp)
{
int c;
rewind(ifp);
while((c=getc(ifp))!=EOF)
putc(c,stdout);
}

void encrypt(FILE *ifp,FILE *ofp)
{
int c;
rewind(ifp);
while((c=getc(ifp))!=EOF){
if((c>=65 && c<=77) || (c>=97&& c<=109))
putc(c+13,ofp);
else if((c>=78 && c<=90) || (c>=110 && c<=122))
putc(c-13,ofp);
else
putc(c,ofp);
}
}

void decrypt(FILE *ifp,FILE *ofp)
{
int c;
rewind(ifp);
while((c=getc(ifp))!=EOF){
if((c>=65 && c<=77) || (c>=97 && c<=109))
putc(c+13,ofp);
else if((c>=78 && c<=90) || (c>=110 && c<=122))
putc(c-13,ofp);
else
putc(c,ofp);
}
}

int main(int argc,char *argv[])
{
FILE *ifp,*ofp;
if(argc!=4){
printf("Need executable,operation,input file,output file");
exit(1);
}
ifp = fopen(argv[2],"r+");
ofp = fopen(argv[3],"w+");
if(strcmp(argv[1],"encrypt") == 0){
printf("%s File before encryption :\n\n", argv[2]);
printfile(ifp);
printf("\n\n");
encrypt(ifp,ofp);
printf("%s file is encrypted into file %s.\n\n Encrypted text:\n\n", argv[2], argv[3]);
printfile(ofp);
printf("\n\n");
}
else if(strcmp(argv[1],"decrypt") == 0){
decrypt(ifp,ofp);
printf("%s file is decrypted into file %s.\n\nDecrypted text:\n\n", argv[2], argv[3]);
printfile(ofp);
printf("\n\n");
}
}
👍3
Code to calculate the probability of sum of 2 dices using Monte Carlo Simulation method :
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define SIDES 6
#define R_SIDE (rand() % SIDES + 1)
int main(void)
{
int trials;
int d1, d2;
int outcomes[13] = {0};
const int n_dice = 2;
srand(clock());
printf("Enter number of trials: ");
scanf("%d", &trials);
for (int j = 0; j < trials; ++j)
outcomes[(d1 = R_SIDE) + (d2 = R_SIDE)]++;
printf("Probability:\n");
for (int j = 2; j < n_dice * SIDES + 1; ++j)
printf("j=%d p=%lf\n", j, (double)(outcomes[j]) / trials);
return 0;
}
Output :

Enter number of trials: 10
Probability:
Sum=2 P=0.000
Sum=3 P=0.100
Sum=4 P=0.200
Sum=5 P=0.100
Sum=6 P=0.300
Sum=7 P=0.000
Sum=8 P=0.100
Sum=9 P=0.000
Sum=10 P=0.100
Sum=11 P=0.000
Sum=12 P=0.100
22👍2
Code to print x pattern (twitter new logo xd) in c :
#include <stdio.h>
int main(void){
int n;
printf("Enter no. of lines:");
scanf("%d",&n);
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
if(i==j)
printf("\\\\");
else if(i==n+1-j)
printf("/");
else
printf(" ");
}
printf("\n");
}
return 0;
}
Output :

Enter no. of lines:5
\\ /
\\ /
\\
/ \\
/ \\
👍21
11🤩3🥰2😍111
A program that replaces tabs in the input file with the proper number of
blanks to the next tab stop ( A problem from the book C by K&R):


#include <stdio.h>
#include <stdlib.h>

void tab_to_space(FILE *ifp, FILE *ofp) {
int c;
int space = 0,
count = 0;
rewind(ifp);
while((c = getc(ifp)) != EOF) {
if(c == '\t') {
space = (8-(count%8));
while(space != 0) {
putc(' ', ofp);
space--;
count++;
}
} else {
putc(c, ofp);
++count;
}
if(c == '\n')
count = 0;

}
}

int main(int argc, char *argv[]) {
FILE *ifp,
*ofp;
if(argc != 3) {
printf("Need ifp,ofp files");
exit(1);
}
ifp = fopen(argv[1], "r");
ofp = fopen(argv[2], "w");
tab_to_space(ifp, ofp);
fclose(ifp);
fclose(ofp);
return 0;
}
👍54👀1
👩‍💻🔤👩‍💻
🔤🔤🔤🔤🔤✈️
Please open Telegram to view this post
VIEW IN TELEGRAM
5