Tom Kelliher, CS 320
Jan. 26, 2005
Read 1.1--4.
Structures, pointers, and memory allocation in C
printf
#include <stdio.h>
int main()
{
/* Variable declarations must occur at the _start_ of a block. */
int sum = 12;
double min = 0.1, max = 5.5;
char name[] = "Tom Kelliher";
printf("I am a constant string.\n");
printf("The sum is: %d\n", sum);
printf("Min is: %g. Max is: %g.\n", min, max);
printf("Your name is %s.\n", name);
return 0;
}
Refer to printf(3C) on phoenix. (man -s 3C printf)
scanf
#include <stdio.h>
int main()
{
int i, age;
double weight;
char name[80];
printf("Enter your age: ");
scanf("%d", &age);
printf("You entered %d.\n", age);
printf("Enter sample weight: ");
scanf("%lg", &weight);
printf("You entered %g.\n", weight);
printf("Enter your name: ");
scanf("%s", name);
printf("Your name is %s.\n", name);
/* Eliminate whitespace following previous name. */
while (getc(stdin) != '\n')
;
printf("Enter your name: ");
fgets(name, 80, stdin);
/* Eliminate the newline following name */
i = 0;
while (name[i] != '\n')
i++;
name[i] = '\0';
printf("Your name is %s.\n", name);
return 0;
}
Refer to scanf(3C).
foo arg1 arg2 arg3
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int sum, current, i;
if (argc <= 1)
{
printf("No arguments!\n");
return 1;
}
sum = 0;
for (i = 1; i < argc; i++)
{
current = atoi(argv[i]);
sum += current;
printf("Arg %d: %d\n", i, current);
}
printf("\nThe sum is %d.\n", sum);
return 0;
}