Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 30

Programas en C

Sitio en espaol, incluyendo un manual de C:


http://es.wikibooks.org/wiki/Programaci%C3%B3n_en_C
Puede servir, pero no me parece excelente.
http://www.sanfoundry.com/c-programming-examples/
http://www.c-program-example.com/
http://www.engineersgarage.com/c-language-programs
http://www.cprogrammingexpert.com/C/example.aspx
http://www.programiz.com/c-programming/examples
http://www.programmingsimplified.com/c-program-examples
http://www.sanfoundry.com/simple-c-programs/

01-Check if a given Integer is Odd or Even


http://www.sanfoundry.com/c-program-integer-odd-or-even/
This C Program checks if a given integer is odd or even. Here if a given number is divisible by 2 with the
remainder 0 then the number is even number. If the number is not divisible by 2 then that number will be
odd number.
Here is source code of the C program which checks a given integer is odd or even. The C program is
successfully compiled and run on a Linux system. The program output is also shown below.
/*
* C program to check whether a given integer is odd or even
*/
#include <stdio.h>
void main()
{
int ival, remainder;
printf("Enter an integer : ");
scanf("%d", &ival);
remainder = ival % 2;
if (remainder == 0)
printf("%d is an even integer\n", ival);
else
printf("%d is an odd integer\n", ival);
}

02-Check if a given Integer is Positive or Negative


http://www.sanfoundry.com/c-program-integer-positive-or-negative/
This C Program checks if a given integer is positive or negative. Here if a number is greater than 0 then
that number is a positive number. If a number is less than 0 then the number is negative number.

Here is source code of the C program which checks a given integer is positive or negative. The C
program is successfully compiled and run on a Linux system. The program output is also shown
below.
/*
* C program to check whether a given integer is positive
* or negative
*/

#include <stdio.h>
void main()
{
int number;
printf("Enter a number \n");
scanf("%d", &number);
if (number >= 0)
printf("%d is a positive number \n", number);
else
printf("%d is a negative number \n", number);
}

03-Find the Biggest of 3 Numbers


http://www.sanfoundry.com/c-program-biggest-3-numbers/
This C Program calculates the biggest of 3 numbers.The program assumes 3 numbers as a, b, c. First it
compares any 2 numbers check which is bigger. After that it compares the biggest element with the
remaining number. Now the number which is greater becomes your biggest of 3 numbers.
Here is source code of the C program to calculate the biggest of 3 numbers. The C program is
successfully compiled and run on a Linux system. The program output is also shown below.
/*
* C program to find the biggest of three numbers
*/
#include <stdio.h>
void main()
{
int num1, num2, num3;
printf("Enter the values of num1, num2 and num3\n");
scanf("%d %d %d", &num1, &num2, &num3);
printf("num1 = %d\tnum2 = %d\tnum3 = %d\n", num1, num2, num3);
if (num1 > num2)
{
if (num1 > num3)
{
printf("num1 is the greatest among three \n");
}
else
{
printf("num3 is the greatest among three \n");
}
}
else if (num2 > num3)
printf("num2 is the greatest among three \n");
else
printf("num3 is the greatest among three \n");
}
Enter the values of num1, num2 and num3
6 8 10
num1 = 6 num2 = 8 num3 = 10
num3 is the greatest among three

04-Calculate the Sum of Odd & Even Numbers


http://www.sanfoundry.com/c-program-sum-odd-even-numbers/
This C Program calculates the sum of odd & even numbers. The program first seperates odd and even
numbers. Later it adds the odd and even numbers seperately.

Here is source code of the C program to calculate the sum of odd & even numbers. The C
program is successfully compiled and run on a Linux system. The program output is also shown
below.
/*
* C program to find the sum of odd and even numbers from 1 to N
*/
#include <stdio.h>
void main()
{
int i, num, odd_sum = 0, even_sum = 0;
printf("Enter the value of num\n");
scanf("%d", &num);
for (i = 1; i <= num; i++)
{
if (i % 2 == 0)
even_sum = even_sum + i;
else
odd_sum = odd_sum + i;
}
printf("Sum of all odd numbers = %d\n", odd_sum);
printf("Sum of all even numbers = %d\n", even_sum);
}

Enter the value of num


10
Sum of all odd numbers = 25
Sum of all even numbers = 30
$ a.out
Enter the value of num
100
Sum of all odd numbers = 2500
Sum of all even numbers = 2550

05-Reverse a Number & Check if it is a Palindrome


http://www.sanfoundry.com/c-program-reverse-number-palindrome/
This C Program reverses a number & checks if it is a palindrome or not. First it reverses a number. Then it
checks if given number and reversed numbers are equal. If they are equal, then its a palindrome.
Here is source code of the C program to reverse a number & checks it is a palindrome or not. The
C program is successfully compiled and run on a Linux system. The program output is also shown
below.
/*
* C program to reverse a given integer number and check
* whether it is a palindrome. Display the given number
* with appropriate message
*/
#include <stdio.h>
void main()
{
int num, temp, remainder, reverse = 0;

printf("Enter an integer \n");


scanf("%d", &num);
/* original number is stored at temp */
temp = num;
while (num > 0)
{
remainder = num % 10;
reverse = reverse * 10 + remainder;
num /= 10;
}
printf("Given number is = %d\n", temp);
printf("Its reverse is = %d\n", reverse);
if (temp == reverse)
printf("Number is a palindrome \n");
else
printf("Number is not a palindrome \n");
}

Enter an integer
6789
Given number is = 6789
Its reverse is = 9876
Number is not a palindrome
$ a.out
Enter an integer
58085
Given number is = 58085
Its reverse is = 58085
Number i

06-Find the Number of Integers Divisible by 5


http://www.sanfoundry.com/c-program-number-divisible-by-5/
This C Program calculates the number of integers divisible by 5. This program checks if the given number
is divisible by 5 and then prints an appropriate message.
Here is source code of the C program to calculate the number of integers divisible by 5. The C
program is successfully compiled and run on a Linux system. The program output is also shown
below.
/*
* C program to find the number of integers divisible by
* 5 between the given range num1 and num2, where num1 < num2.
*
* Also find the sum of all these integer numbers which are divisible
* by 5 and display the total.
*/
#include <stdio.h>
void main()
{
int i, num1, num2, count = 0, sum = 0;
printf("Enter the value of num1 and num2 \n");
scanf("%d %d", &num1, &num2);
/* Count the number and compute their sum*/
printf("Integers divisible by 5 are \n");
for (i = num1; i < num2; i++)
{

if (i % 5 == 0)
{
printf("%3d,", i);
count++;
sum = sum + i;
}
}
printf("\n Number of integers divisible by 5 between %d and %d =
%d\n", num1, num2, count);
printf("Sum of all integers that are divisible by 5 = %d\n", sum);
}

Enter the value of num1 and num2


12 17
Integers divisible by 5 are
15,
Number of integers divisible by 5 between 12 and 17 = 1
Sum of all integers that are divisible by 5 = 15

07-Read Two Integers M and N & Swap their Values


http://www.sanfoundry.com/c-program-swap-values/
This C Program reads two integers & swap their values.
Here is source code of the C program to read two integers & swap their values. The C program is
successfully compiled and run on a Linux system. The program output is also shown below.
/*
* C program to read two integers M and N and to swap their values.
* Use a user-defined function for swapping. Output the values of M
* and N before and after swapping.
*/
#include <stdio.h>
void swap(float *ptr1, float *ptr2);
void main()
{
float m, n;
printf("Enter the values of M and N \n");
scanf("%f %f", &m, &n);
printf("Before Swapping:M = %5.2ftN = %5.2f\n", m, n);
swap(&m, &n);
printf("After Swapping:M = %5.2ftN = %5.2f\n", m, n);
}
/* Function swap - to interchanges the contents of two items */
void swap(float *ptr1, float *ptr2)
{
float temp;
temp = *ptr1;
*ptr1 = *ptr2;
*ptr2 = temp;
}

Enter the values of M and N


23
Before Swapping:M = 2.00 N = 3.00
After Swapping:M = 3.00 N = 2.00

08-Convert the given Binary Number into Decimal


http://www.sanfoundry.com/c-program-binary-number-into-decimal/
This C Program converts the given binary number into decimal. The program reads the binary number,
does a modulo operation to get the remainder, multiples the total by base 2 and adds the modulo and
repeats the steps.
Here is source code of the C program to covert binary number to decimal. The C program is
successfully compiled and run on a Linux system. The program output is also shown below.
/*
* C program to convert the given binary number into decimal
*/
#include <stdio.h>
void main()
{
int num, binary_val, decimal_val = 0, base = 1, rem;
printf("Enter a binary number(1s and 0s) \n");
scanf("%d", &num); /* maximum five digits */
binary_val = num;
while (num > 0)
{
rem = num % 10;
decimal_val = decimal_val + rem * base;
num = num / 10 ;
base = base * 2;
}
printf("The Binary number is = %d \n", binary_val);
printf("Its decimal equivalent is = %d \n", decimal_val);
}

Enter a binary number(1s and 0s)


10101001
The Binary number is = 10101001
Its decimal equivalent is = 169S

09-Reverse a Given Number


http://www.sanfoundry.com/c-program-to-reverse-a-given-number/
This C Program reverses a given number by using modulo operation.
Here is source code of the C program to reverse a given number. The C program is successfully
compiled and run on a Linux system. The program output is also shown below.
/*
* C program to accept an integer and reverse it
*/
#include <stdio.h>
void main()
{
long num, reverse = 0, temp, remainder;
printf("Enter the number\n");
scanf("%ld", &num);
temp = num;

while (num > 0)


{
remainder = num % 10;
reverse = reverse * 10 + remainder;
num /= 10;
}
printf("Given number = %ld\n", temp);
printf("Its reverse is = %ld\n", reverse);
}

Enter the number


567865
Given number = 567865
Its reverse is = 568765

10-Illustrate how User Authentication is Done


http://www.sanfoundry.com/c-program-illustrate-user-authentication/
This C Program illustrate how user authentication is done. The program accepts the username and
password. It checks whether the password is correct with respect to the username.
Here is source code of the C program to illustrate user authentication. The C program is
successfully compiled and run on a Linux system. The program output is also shown below.
/*
* C program is to illustrate how user authentication is done.
* Program asks for the user name and password and displays
* the password as '*' character
*/
#include <stdio.h>
void main()
{
char password[10], username[10], ch;
int i;
printf("Enter User name: ");
gets(username);
printf("Enter the password < any 8 characters>: ");
for (i = 0; i < 8; i++)
{
ch = getchar();
password[i] = ch;
ch = '*' ;
printf("%c", ch);
}
password[i] = '\0';
/* Original password can be printed, if needed */
printf("\n Your password is :");
for (i = 0; i < 8; i++)
{
printf("%c", password[i]);
}
}

$ cc pgm43.c
$ a.out
Enter User name: rajaraman

Enter the password <any 8 characters>: shashi12


********
Your password is :shashi12

11-Convert a Decimal Number to Binary & Count the Number of 1s


http://www.sanfoundry.com/c-program-decimal-binary-count-1-binary/
This C Program converts a decimal number into binary & count the number of 1s. The program uses
module operation and multiplication with base 2 operation for conversion. It also uses modulo operation to
check for 1s and accordingly increments the count of 1s.
Here is source code of the C program to convert a decimal number to binary & count the number
of 1s. The C program is successfully compiled and run on a Linux system. The program output is
also shown below.
/*
* C program to accept a decimal number and convert it to binary
* and count the number of 1's in the binary number
*/
#include <stdio.h>
void main()
{
long num, decimal_num, remainder, base = 1, binary = 0, no_of_1s = 0;
printf("Enter a decimal integer \n");
scanf("%ld", &num);
decimal_num = num;
while (num > 0)
{
remainder = num % 2;
/* To count no.of 1s */
if (remainder == 1)
{
no_of_1s++;
}
binary = binary + remainder * base;
num = num / 2;
base = base * 10;
}
printf("Input number is = %d\n", decimal_num);
printf("Its binary equivalent is = %ld\n", binary);
printf("No.of 1's in the binary number is = %d\n", no_of_1s);
}
Enter a decimal integer
134
Input number is = 134
Its binary equivalent is = 10000110
No.of 1's in the binary number is = 3

12-Find if a given Year is a Leap Year


http://www.sanfoundry.com/c-program-check-year-leap/
This C Program checks whether a given year is a leap year. When A year is divided by 4. If remainder
becomes 0 then the year is called a leap year.
Here is source code of the C program to check a given year is leap year. The C program is successfully
compiled and run on a Linux system. The program output is also shown below.
/*
* C program to find whether a given year is leap year or not
*/
void main()
{

int year;
printf("Enter a year \n");
scanf("%d", &year);
if ((year % 400) == 0)
printf("%d is a leap year \n", year);
else if ((year % 100) == 0)
printf("%d is a not leap year \n", year);
else if ((year % 4) == 0)
printf("%d is a leap year \n", year);
else
printf("%d is not a leap year \n", year);
}
Enter a year
2012
2012 is a leap year
$ a.out
Enter a year
2009
2009 is not a leap year

13-Swap the Contents of two Numbers using Bitwise XOR Operation


http://www.sanfoundry.com/c-program-swap-numbers-bitwise-xor-operation/
This C Program swaps the contents of two numbers using bitwise XOR operation.
Here is source code of the C program to swap the contents of two numbers using bitwise XOR operation.
The C program is successfully compiled and run on a Linux system. The program output is also shown
below.
/*
* C program to swap the contents of two numbers using bitwise XOR
* operation. Don't use either the temporary variable or arithmetic
* operators
*/
#include <stdio.h>
void main()
{
long i, k;
printf("Enter two integers \n");
scanf("%ld %ld", &i, &k);
printf("\n Before swapping i= %ld and k = %ld", i, k);
i = i ^ k;
k = i ^ k;
i = i ^ k;
printf("\n After swapping i= %ld and k = %ld", i, k);
}

$ cc pgm48.c
$ a.out
Enter two integers
45
89

Before swapping i= 45 and k = 89


After swapping i= 89 and k = 45

14-Convert a Given Number of Days in terms of Years, Weeks &


Days
http://www.sanfoundry.com/c-program-days-in-years-weeks-days/
This C Program converts a given number of Days in terms of years, weeks & days. This program accepts
the number of days. Given the number of days, then it calculates the years, weeks & days for this number.
Here is source code of the C program to converts a given number of Days in terms of years, weeks & days.
The C program is successfully compiled and run on a Linux system. The program output is also shown
below.
/*
* C program to convert given number of days to a measure of time given
* in years, weeks and days. For example 375 days is equal to 1 year
* 1 week and 3 days (ignore leap year)
*/
#include <stdio.h>
#define DAYSINWEEK 7
void main()
{
int ndays, year, week, days;
printf("Enter the number of daysn");
scanf("%d", &ndays);
year = ndays / 365;
week =(ndays % 365) / DAYSINWEEK;
days =(ndays % 365) % DAYSINWEEK;
printf ("%d is equivalent to %d years, %d weeks and %d daysn",
ndays, year, week, days);
}
Enter the number of days
29
29 is equivalent to 0 years, 4 weeks and 1 days
$ a.out
Enter the number of days
1000
1000 is equivalent to 2 years, 38 weeks and 4 days

15-Display the Inventory of Items in a Store


http://www.sanfoundry.com/c-program-inventory-items-store/
This C Program display the inventory of items in a store. The program accepts the value of item name, item
code, price, quantity & manufacture date. Then display those value in a structured way.
Here is source code of the C program to display the inventory of items in a storage. The C program is
successfully compiled and run on a Linux system. The program output is also shown below.
/*
* C program to display the inventory of items in a store / shop
* The inventory maintains details such as name, price, quantity
* and manufacturing date of each item.

OJO: CORREGIR LOS ERRORES


*/
#include <stdio.h>
void main()
{
struct date
{
int day;
int month;
int year;
};
struct details
{
char name[20];
int price;
int code;
int qty;
struct date mfg;
};
struct details item[50];
int n, i;
printf("Enter number of items:");
scanf("%d", &n);
fflush(stdin);
for (i = 0; i < n; i++)
{
fflush(stdin);
printf("Item name: \n");
scanf("%s", item[i].name);
fflush(stdin);
printf("Item code: \n");
scanf("%d", &item[i].code);
fflush(stdin);
printf("Quantity: \n");
scanf("%d", &item[i].qty);
fflush(stdin);
printf("price: \n");
scanf("%d", &item[i].price);
fflush(stdin);
printf("Manufacturing date(dd-mm-yyyy): \n");
scanf("%d-%d-%d", &item[i].mfg.day,
&item[i].mfg.month, &item[i].mfg.year);
}
printf("
***** INVENTORY ***** \n");
printf("-----------------------------------------------------------------\n");
printf("S.N.| NAME
| CODE | QUANTITY | PRICE
| MFG.DATE \n");
printf("---------------------------------------------------------

---------\n");
for (i = 0; i < n; i++)
printf("%d
%-15s
%-d
%-5d
%-5d
%d/%d/%d \n", i + 1, item[i].name, item[i].code, item[i].qty,
item[i].price, item[i].mfg.day, item[i].mfg.month,
item[i].mfg.year);
printf("-----------------------------------------------------------------\n");
}
Enter number of items:3
Item name:
pendrive
Item code:
123
Quantity:
6
price:
3000
Manufacturing date(dd-mm-yyyy):
30-9-2012
Item name:
computer
Item code:
124
Quantity:
10
price:
10000
Manufacturing date(dd-mm-yyyy):
30-7-2012
Item name:
optical mouse
Item code:
Quantity:
price:
Manufacturing date(dd-mm-yyyy):
***** INVENTORY *****
-----------------------------------------------------------------S.N.| NAME
| CODE | QUANTITY | PRICE | MFG.DATE
-----------------------------------------------------------------1
pendrive
123
6
3000
30/9/2012
2
computer
124
10
10000 30/7/2012
3
optical
0
0
0
0/0/0
-----------------------------------------------------------------$ a.out
Enter number of items:3
Item name:
pendrive
Item code:

123
Quantity:
6
price:
3000
Manufacturing date(dd-mm-yyyy):
30-9-2012
Item name:
computer
Item code:
124
Quantity:
10
price:
10000
Manufacturing date(dd-mm-yyyy):
30-7-2012
Item name:
Mouse
Item code:
125
Quantity:
10
price:
1500
Manufacturing date(dd-mm-yyyy):
30-6-2012
***** INVENTORY *****
-----------------------------------------------------------------S.N.| NAME
| CODE | QUANTITY | PRICE | MFG.DATE
-----------------------------------------------------------------1
pendrive
123
6
3000
30/9/2012
2
computer
124
10
10000
30/7/2012
3
Mouse
125
10
1500
30/6/2012

16-Multiply given Number by 4 using Bitwise Operators


http://www.sanfoundry.com/c-program-multiply-number-4-using-bitwise-operators/
This C Program multiplies given number by 4 using bitwise operators. The bitwise operators are or, and,
xor, not, left shift, right shift. Program uses left shift operator for this.
Here is source code of the C program to multiply given number by 4 using bitwise operators. The C
program is successfully compiled and run on a Linux system. The program output is also shown below.
/*
* C program to multiply given number by 4 using bitwise operators
*/
#include <stdio.h>

void main()
{

long number, tempnum;


printf("Enter an integer \n");
scanf("%ld", &number);
tempnum = number;
/* left shift by two bits */
number = number << 2;
printf("%ld x 4 = %ld\n", tempnum, number);
}
Enter an integer
450
450 x 4 = 1800

17-Find the Sum of first 50 Natural Numbers using For Loop


http://www.sanfoundry.com/c-program-sum-first-n-natural-numbers/
This C Program finds sum of first 50 natural numbers using for loop.
Here is source code of the C program to find the sum of first 50 natural numbers using for loop. The C
program is successfully compiled and run on a Linux system. The program output is also shown below.
/*
* C program to find the sum of first 50 natural numbers
* using for loop
*/
#include <stdio.h>
void main()
{
int num, sum = 0;
for (num = 1; num <= 50; num++)
{
sum = sum + num;
}
printf("Sum = %4d\n", sum);
}
Sum = 1275

18-Create a File & Store Information


http://www.sanfoundry.com/c-program-create-file-store-information/
This C Program creates a file & store information. We frequently use files for storing information which can
be processed by our programs. In order to store information permanently and retrieve it we need to use
files and this program demostrate file creation and writing data in that.
Here is source code of the C program to create a file & store information.The C program is successfully
compiled and run on a Linux system. The program output is also shown below.
/*
* C program to create a file called emp.rec and store information
* about a person, in terms of his name, age and salary.
*/
#include <stdio.h>
void main()
{
FILE *fptr;

char name[20];
int age;
float salary;
/* open for writing */
fptr = fopen("emp.rec", "w");
if (fptr == NULL)
{
printf("File does not exists \n");
return;
}
printf("Enter the name \n");
scanf("%s", name);
fprintf(fptr, "Name = %s\n", name);
printf("Enter the age\n");
scanf("%d", &age);
fprintf(fptr, "Age
= %d\n", age);
printf("Enter the salary\n");
scanf("%f", &salary);
fprintf(fptr, "Salary = %.2f\n", salary);
fclose(fptr);
}
Enter the name
raj
Enter the age
40
Enter the salary
4000000

19-Reading of Data from a File


http://www.sanfoundry.com/c-program-illustrate-reading-datafile/
This C Program illustrates reading of data from a file. The program opens a file which is present. Once the
file opens successfully, it uses libc fgetc() library call to read the content.
Here is source code of the C program to illustrate reading of data from a file. The C program is successfully
compiled and run on a Linux system. The program output is also shown below.
/*
* C program to illustrate how a file stored on the disk is read
*/
#include <stdio.h>
#include <stdlib.h>
void main()
{
FILE *fptr;
char filename[15];
char ch;
printf("Enter the filename to be opened \n");
scanf("%s", filename);
/* open the file for reading */

fptr = fopen(filename, "r");


if (fptr == NULL)
{
printf("Cannot open file \n");
exit(0);
}
ch = fgetc(fptr);
while (ch != EOF)
{
printf ("%c", ch);
ch = fgetc(fptr);
}
fclose(fptr);
}
Enter the filename to be opened
main.c
En la consola se ve el listado de este mismo programa.

20-Agregar a un archivo
Combinando los dos proyectos anteriores, hacemos un programa que lee el archivo "emp.rec", lo muestra
en la consola, puego pide un nuevo juego de datos (o sea un employee record) y los graba al final del
mismo archivo que antes ley.
/*
Reading of Data from a File
This C Program illustrates reading of data from a file.
The program opens a file which is present.
Once the file opens successfully, it uses libc fgetc()
library call to read the content.
*/
#include <stdio.h>
#include <stdlib.h>
void main() {
FILE *fptr;// declaro un puntero al file
char filename[15];// declaro un string para el nombre del file
char ch;// declaro una variable de tipo char
printf("Enter the filename to be opened: ");// cartel para el usuario
scanf("%s", filename);// leo del teclado un string que es el nombre del file
/* open the file for reading */
fptr = fopen(filename, "r");
if (fptr == NULL) {
// el file no existe
printf("Cannot open file \n");
exit(0);
}
// el file est y lo pude abrir
ch = fgetc(fptr);//leo el primer byte del file
while (ch != EOF) {
printf ("%c", ch);// imprimo el que tengo
ch = fgetc(fptr);// leo el siguiente
}
fclose(fptr);// cierro el file
}
El nombre del archivo puede ser cualquiera. Si no existe, lo crea.

21-Delete a specific Line from a Text File


http://www.sanfoundry.com/c-program-delete-line-text-file/
This C Program delete a specific line from a text file.
Here is source code of the C Program to delete a specific line from a text file. The C program is
successfully compiled and run on a Linux system. The program output is also shown below.
/*
* C Program Delete a specific Line from a Text File
*/
#include <stdio.h>
int main()
{
FILE *fileptr1, *fileptr2;
char filename[40];
char ch;
int delete_line, temp = 1;
printf("Enter file name: ");
scanf("%s", filename);
//open file in read mode
fileptr1 = fopen(filename, "r");
ch = getc(fileptr1);
` while (ch != EOF)
{
printf("%c", ch);
ch = getc(fileptr1);
}
//rewind
rewind(fileptr1);
printf(" \n Enter line number of the line to be deleted:");
scanf("%d", &delete_line);
//open new file in write mode
fileptr2 = fopen("replica.c", "w");
ch = getc(fileptr1);
while (ch != EOF)
{
ch = getc(fileptr1);
if (ch == '\n')
temp++;
//except the line to be deleted
if (temp != delete_line)
{
//copy all lines in file replica.c
putc(ch, fileptr2);
}
}
fclose(fileptr1);
fclose(fileptr2);
remove(filename);
//rename the file replica.c to original name
rename("replica.c", filename);

printf("\n The contents of file after being modified are as follows:\n");


fileptr1 = fopen(filename, "r");
ch = getc(fileptr1);
while (ch != EOF)
{
printf("%c", ch);
ch = getc(fileptr1);
}
fclose(fileptr1);
return 0;
}

22-Append the Content of File at the end of Another


http://www.sanfoundry.com/c-program-to-append-file/
This C Program appends the content of file at the end of another.
Here is source code of the C Program to append the content of file at the end of another. The C program is
successfully compiled and run on a Linux system. The program output is also shown below.
/*
Append the Content of File at the end of Another
*/
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *pFile1, *pFile2, *pfTemp;
char ch, file1[20], file2[20], file3[20];
printf("Enter name of first file ");
gets(file1);
printf("Enter name of second file ");
gets(file2);
printf("Enter name to store merged file ");
gets(file3);
pFile1 = fopen(file1, "r");
pFile2 = fopen(file2, "r");
if (pFile1 == NULL || pFile2 == NULL) {
/* C Standard pdf p. 357
7.21.10.4 The perror function
Synopsis
1 #include <stdio.h>
void perror(const char *s);
Description
2 The perror function maps the error number in the integer expression errno to
an
error message. It writes a sequence of characters to the standard error stream
thus: first
(if s is not a null pointer and the character pointed to by s is not the null
character), the
string pointed to by s followed by a colon (:) and a space; then an appropriate
error

message string followed by a new-line character. The contents of the error


message
strings are the same as those returned by the strerror function with argument
errno.
*/
perror("Error has occured");
printf("Press any key to exit...\n");
/*
EXIT_FAILURE es una macro definida en stdlib.h.
Ver C Standard, pdf pgina 358
7.22 General utilities <stdlib.h>
*/
exit(EXIT_FAILURE);
}
pfTemp = fopen(file3, "w");
if (pfTemp == NULL) {
perror("Error has occures");
printf("Press any key to exit...\n");
exit(EXIT_FAILURE);
}
while ((ch = fgetc(pFile1)) != EOF)
fputc(ch, pfTemp);
fclose(pFile1);
while ((ch = fgetc(pFile2) ) != EOF)
fputc(ch, pfTemp);
fclose(pFile2);
fclose(pfTemp);
printf("Two files merged %s successfully.\n", file3);
return 0;
}
Enter name of first file a.c
Enter name of second file b.c
Enter name to store merged file c.c
Two files merged merge.txt successfully.

23-List Files in Directory


http://www.sanfoundry.com/c-program-list-files-directory/
ESTE REQUIERE LA BIBLIOTECA dirent.h QUE NO ES STANDARD DE C
This C Program lists files in directory.
Here is source code of the C Program to list files in directory. The C program is successfully compiled and
run on a Linux system. The program output is also shown below.
/*
List Files in Directory
*/
#include <dirent.h>
#include <stdio.h>

int main(void)
{
DIR *d;
struct dirent *dir;
d = opendir(".");
if (d)
{
while ((dir = readdir(d)) != NULL)
{
printf("%s\n", dir->d_name);
}
closedir(d);
}
return(0);
}

24-Sort N Numbers in Ascending Order using Bubble Sort


http://www.sanfoundry.com/c-program-sorting-bubble-sort/
This C Program sorts the numbers in ascending order using bubble sort. Bubble sort is a simple sorting
algorithm that works by repeatedly stepping through the list to be sorted, comparing each pair of adjacent
items and swapping them if they are in the wrong order. Here we need to sort a number in ascending order.
Here is source code of the C program to sort the numbers in ascending order using bubble sort. The C
program is successfully compiled and run on a Linux system. The program output is also shown below.
/*
* C program to sort N numbers in ascending order using Bubble sort
* and print both the given and the sorted array
*/
#include <stdio.h>
#define MAXSIZE 10
void main()
{
int array[MAXSIZE];
int i, j, num, temp;
printf("Enter the value of num \n");
scanf("%d", &num);
printf("Enter the elements one by one \n");
for (i = 0; i < num; i++)
{
scanf("%d", &array[i]);
}
printf("Input array is \n");
for (i = 0; i < num; i++)
{
printf("%d\n", array[i]);
}
/* Bubble sorting begins */
for (i = 0; i < num; i++)

{
for (j = 0; j < (num - i - 1); j++)
{
if (array[j] > array[j + 1])
{
temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
printf("Sorted array is...\n");
for (i = 0; i < num; i++)
{
printf("%d\n", array[i]);
}
}

25-Accept Sorted Array and do Search using Binary Search


http://www.sanfoundry.com/c-program-accept-sorted-array-search-using-binary-search/
This C Program accepts the sorted array and does search using Binary search. Binary search is an
algorithm for locating the position of an item in a sorted array. A search of sorted data, in which the middle
position is examined first. Search continues with either the left or the right portion of the data, thus
eliminating half of the remaining search space. In other words, a search which can be applied to an ordered
linear list to progressively divide the possible scope of a search in half until the search object is found.
Here is source code of the C program to accept the sorted array and do Search using Binary Search. The C
program is successfully compiled and run on a Linux system. The program output is also shown below.
/*
* C program to accept N numbers sorted in ascending order
* and to search for a given number using binary search.
* Report success or failure.
*/
#include <stdio.h>
void main()
{
int array[10];
int i, j, num, temp, keynum;
int low, mid, high;
printf("Enter the value of num \n");
scanf("%d", &num);
printf("Enter the elements one by one \n");
for (i = 0; i < num; i++)
{
scanf("%d", &array[i]);
}
printf("Input array elements \n");
for (i = 0; i < num; i++)
{
printf("%d\n", array[i]);
}

/* Bubble sorting begins */


for (i = 0; i < num; i++)
{
for (j = 0; j < (num - i - 1); j++)
{
if (array[j] > array[j + 1])
{
temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
printf("Sorted array is...\n");
for (i = 0; i < num; i++)
{
printf("%d\n", array[i]);
}
printf("Enter the element to be searched \n");
scanf("%d", &keynum);
/* Binary searching begins */
low = 1;
high = num;
do
{
mid = (low + high) / 2;
if (keynum < array[mid])
high = mid - 1;
else if (keynum > array[mid])
low = mid + 1;
} while (keynum != array[mid] && low <= high);
if (keynum == array[mid])
{
printf("SEARCH SUCCESSFUL \n");
}
else
{
printf("SEARCH FAILED \n");
}
}

25-Typedef
/*
Ver Tipos de datos definidos por el usuario
Urrutia pgina 107
*/
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
typedef struct {
int dia;

int mes;
int anio;
} FechaCompleta;
FechaCompleta fecha, fecha2;
fecha.dia = 12;
fecha.mes = 3;
fecha.anio = 15;
fecha2.dia = 1;
fecha2.mes = 5;
fecha2.anio = 2010;
printf("Fecha: %02d-%02d-20%02d\n", fecha.dia, fecha.mes, fecha.anio);
printf("Fecha2: %02d-%02d-%04d", fecha2.dia, fecha2.mes, fecha2.anio);
return 0;
}

26-Punteros
/*
2004 Curso de C, Urrutia.docx, pg. 57 Punteros
*/
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
/*
C Standard 7.21.6.1 p. 333
%s If no l length modifier is present, the argument shall be a pointer to the initial
element of an array of character type.280) Characters from the array are
written up to (but not including) the terminating null character. If the
precision is specified, no more than that many bytes are written. If the
precision is not specified or is greater than the size of the array, the array shall
contain a null character.
If an l length modifier is present, the argument shall be a pointer to the initial
element of an array of wchar_t type. Wide characters from the array are
converted to multibyte characters (each as if by a call to the wcrtomb
function, with the conversion state described by an mbstate_t object
initialized to zero before the first wide character is converted) up to and
including a terminating null wide character. The resulting multibyte
characters are written up to (but not including) the terminating null character
(byte). If no precision is specified, the array shall contain a null wide
character. If a precision is specified, no more than that many bytes are
written (including shift sequences, if any), and the array shall contain a null
wide character if, to equal the multibyte character sequence length given by
the precision, the function would need to access a wide character one past the
end of the array. In no case is a partial multibyte character written.
%p The argument shall be a pointer to void. The value of the pointer is
converted to a sequence of printing characters, in an implementation-defined
manner.
*/
char str[] = "Esta es una string";
printf( "String: %s\nDireccion: %p\n", str, str);
/*
C Standard 6.5.3.2 Address (&) and indirection (*) operators
Constraints

1 The operand of the unary & operator shall be either a function designator, the result of a
[] or unary * operator, or an lvalue that designates an object that is not a bit-field and is
not declared with the register storage-class specifier.
2 The operand of the unary * operator shall have pointer type.
Semantics
3 The unary & operator yields the address of its operand. If the operand has type type,
the result has type pointer to type. If the operand is the result of a unary * operator,
neither that operator nor the & operator is evaluated and the result is as if both were
omitted, except that the constraints on the operators still apply and the result is not an
lvalue. Similarly, if the operand is the result of a [] operator, neither the & operator nor
the unary * that is implied by the [] is evaluated and the result is as if the & operator
were removed and the [] operator were changed to a + operator. Otherwise, the result is
a pointer to the object or function designated by its operand.
4 The unary * operator denotes indirection. If the operand points to a function, the result is
a function designator; if it points to an object, the result is an lvalue designating the
object. If the operand has type pointer to type, the result has type type. If an
invalid value has been assigned to the pointer, the behavior of the unary * operator is
undefined.
*/
// Urrutia pg. 58 y 65
int a = 10;// declaro y asigno la variable a
int b = 10;// declaro y asigno la variable b
int *pa = &a;// declaro y asigno un puntero a a
int *pb = &b;// declaro y asigno un puntero a b
// Imprimo la variable y su direccin
printf("Valor de a = %i, direccion de a: %p\n", a, &a);
printf("Valor de a = %i, direccion de a: %p\n", *pa, pa );
// Comparo a con b
if ( a == b )
printf( "a == b\n" );
else
printf( "a != b\n" );
if ( pa == pb )
printf( "pa == pb\n" );
else
printf( "pa != pb\n" );
if ( *pa == *pb )
printf( "*pa == *pb\n" );
else
printf( "*pa != *pb\n" );
return 0;
}

27-Operadores de incremento pre y post fijos


#include <stdio.h>
#include <stdlib.h>
/* Diferencia entre los operadores de incremento pre y postfijos.
Ambos hacen i = i + 1;
Pero son diferentes:
++i retorna i+1
i++ retorna i
*/
int main() {
int i = 0;

printf("%d\n",i);// imprime 0
// i vale 0
printf("%d\n",i++);// imprime 0, y hace i = 1
printf("%d\n",i);// imprime 1
// i vale 1
printf("%d\n",++i);// imprime 2, y hace i = 2
// i vale 2
printf("%d\n",i);// imprime 2
return 0;
}

28-Multiplicar 3 nmeros
#include <stdio.h>
#include <stdlib.h>
/* Diferencia entre los operadores de incremento pre y postfijos.
Ambos hacen i = i + 1;
Pero son diferentes:
++i retorna i+1
i++ retorna i
*/
int main() {
int i = 0;
printf("%d\n",i);// imprime 0
// i vale 0
printf("%d\n",i++);// imprime 0, y hace i = 1
printf("%d\n",i);// imprime 1
// i vale 1
printf("%d\n",++i);// imprime 2, y hace i = 2
// i vale 2
printf("%d\n",i);// imprime 2
return 0;
}

29-Formatos de impresin
/*
Explicacin y demostracin de los formatos de impresin
C Standard
7.21.6 Formatted input/output functions
% [flags] [ancho mnimo de campo] [precisin] [modificador de longitud] [tipo de conversin]
Flags
- Alineado a izquierda
+ Poner signo inicial siempre
espacio
#
0 (es un cero, no una O mayscula)
Tipo de conversin
c carcter sin signo
d entero
e cientfica
f punto flotante
g general
o octal sin signo
s string de caracteres
u decimal sin signo

x hexadecimal sin signo


*/
#include <stdio.h>
void main() {
int i = 123;
int j = -345;
float x = 1.23456;
char *str = "arrrrrrrrrrrrrrrrz";
//long num, decimal_num, remainder, base = 1, binary = 0, no_of_1s = 0;
printf("int i = %-6d %+5d % 5d %05d\n", i, i, i, i);
printf("int j = %d %+d % 6d\n", j, j, j);
printf("float x = %f %+f % f\n", x, x, x);
printf("float x = %014.8f %+f % f\n", x, x, x);
printf("char *str = %s\n", str);
}

30-Strings
#include <stdio.h>
//#include <stdlib.h>
#include "header.h"
char *test (void) {
return("Este es un string.");
}
int main() {
/*
En C no existe un tipo string, como en otros lenguajes.
Para declarar un string en C, se declara un array de char.
*/
char str1[] = "";
/*
pStr es un pointer al primer carcter del string str
*/
char *pStr1a = &str1[0];
char *pStr1b = str1;
//long num;
//printf("Entrar un entero decimal:");
// recordar que scanf requiere la referencia a num, o sea &num
// para poder grabar en la variable el nmero que entra el usuario
//scanf("%ld", &num);
printf("Introduzca de 1 a 4 letras y presione Enter: ");
scanf( "%s", str );
printf( "str: %s sizeof(str): %d\n", str, sizeof(str));
//printf( "&str[0] %%s: %s\n", &str[0]);
//printf("str %%#12X: %#12X\n", str);
printf("str[0] %c %#4X\n", str[0], str[0]);
printf("str[1] %c %#4X\n", str[1], str[1]);
//printf("str[2] %s %#12X\n", str[2], str[2]);
//printf("pStr %%#12X: %#12X\n", pStr);
//printf("pStr %%s: %s\n", pStr);
puts (test());
}

31-Leer teclado
/*
Urrutia pgina 40
*/
#include <stdio.h>
int main() {
char letra;
printf( "Introducir una letra: " );
fflush( stdout );
letra = getch();
printf( "\nHas introducido la letra: %c", letra );
printf( "\nIntroducir una letra: " );
fflush( stdout );
letra = getche();
printf( "\nHas introducido la letra: %c", letra );
return 0;
}

32- Generate N Number of Passwords of Length M Each


http://www.sanfoundry.com/c-program-generate-n-number-passwords-length-m/
/*
This C program generates N passwords, each of length M.
This problem focuses on finding the N permutations each of length M.
*/
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
/* Length of the password */
int length;
int num;
int temp;
printf("Enter the length of the password: ");
scanf("%d", &length);
printf("\nEnter the number of passwords you want: ");
scanf("%d", &num);
/* Seed number for rand() */
srand((unsigned int) time(0) + getpid());
while(num--)
{
temp = length;
printf("\n");
while(temp--) {
putchar(rand() % 56 + 65);
srand(rand());
}
temp = length;

}
printf("\n");
return EXIT_SUCCESS;
}

33-Identificador de proceso (PID)


/* getpid: print a process' process ID */
/* Paul Krzyzanowski */
// https://www.cs.rutgers.edu/~pxk/416/notes/c-tutorials/getpid.html
#include <stdlib.h> /* needed to define exit() */
#include <unistd.h> /* needed to define getpid() */
#include <stdio.h>
/* needed for printf() */
int main(int argc, char **argv) {
printf("my process ID is %d\n", getpid());
exit(0);
}

34 Diamante sin recursin


http://www.programmingsimplified.com/c/source-code/c-program-print-diamond-pattern
Diamond pattern in c: This code print diamond pattern of stars. Diamond shape is as follows:
*
***
*****
***
*
#include <stdio.h>
int main()
{
int n, c, k, space = 1;
printf("Enter number of rows\n");
scanf("%d", &n);
space = n - 1;
for (k = 1; k <= n; k++)
{
for (c = 1; c <= space; c++)
printf(" ");
space--;
for (c = 1; c <= 2*k-1; c++)
printf("*");
printf("\n");
}
space = 1;

for (k = 1; k <= n - 1; k++)


{
for (c = 1; c <= space; c++)
printf(" ");
space++;
for (c = 1 ; c <= 2*(n-k)-1; c++)
printf("*");
printf("\n");
}
return 0;
}

35 Diamante con recursin


http://www.programmingsimplified.com/c/source-code/c-program-print-diamond-pattern
#include <stdio.h>
void print (int);
int main () {
int rows;
scanf("%d", &rows);
print(rows);
return 0;
}
void print (int r) {
int c, space;
static int stars = -1;
if (r <= 0)
return;
space = r - 1;
stars += 2;
for (c = 0; c < space; c++)
printf(" ");
for (c = 0; c < stars; c++)
printf("*");
printf("\n");
print(--r);
space = r + 1;
stars -= 2;
for (c = 0; c < space; c++)
printf(" ");
for (c = 0; c < stars; c++)

printf("*");
printf("\n");
}
http://www.studytonight.com/c/pointers-to-structure-in-c.php
http://en.wikipedia.org/wiki/Struct_(C_programming_language)
http://www.programmingsimplified.com/c-program-shutdown-computer
http://www.programmingsimplified.com/c-program-get-ip-address

You might also like