Programas en C
Programas en C
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);
}
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 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
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);
}
$ cc pgm43.c
$ a.out
Enter User name: rajaraman
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
$ cc pgm48.c
$ a.out
Enter two integers
45
89
---------\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
void main()
{
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
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.
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);
}
{
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-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;
}
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
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;
}
}
printf("\n");
return EXIT_SUCCESS;
}
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