October 3, 2020
You can find at https://spots.augusta.edu/caubert/teaching/general/C/prog.c and below a simple C
program:
/*
* I'm a comment.
*/
#include <stdio.h> // To perform input / output, printf and scanf
#include <stdlib.h> // To add EXIT_SUCCESS and EXIT_FAILURE, cf end of the main method.
long cube(long x){
return x * x * x;
}
int main(){
int a;
a = 10;
int b = 11;
printf("The value of a is %d, its address is %p\n", a, &a);
//%d is for sigmed integers, %p for pointer address
int* pointer = &a;
// You can also see the syntax "int *pointer = &a;".
printf("The value pointed is %d, the address of the pointer is %p, the address the pointer points to is %p.\n", *pointer, &pointer, pointer);
// Notice that if the value of change a, so does the value pointed at. We can read the new value from the user:
printf("Enter the new value for a and press enter:\n");
scanf("%d", &a);
printf("The value pointed is %d\n", *pointer);
// Basic control stucture:
if (a == 10){
printf("You did not changed the value of a.\n");
}
else
{
printf("You changed the value of a.\n");
}
int counter;
printf("Let's count to ten:\n");
for (counter = 0; counter <= 10 ; counter++)
{
printf("%d ", counter);
}
printf("\n");
printf("Let's count back to 0:\n");
while (counter > 0)
{
counter--;
printf("%d ", counter);
}
printf("\n");
// Calling the previously defined cube function, performing implicit casting from int to long:
printf("Here is your number, cubed: %d\n", cube(a));
/* To exit informing the environment that our program completed successfully, we can use:
* return(0);
* exit(0);
* or, more portable:
*/
exit(EXIT_SUCCESS);
}
You can find services to compile C code online, but I recommend you install gcc or another C compiler on your computer or virtual machine.
To compile and execute it, use
If you have questions, feel free to reach me at caubert@augusta.edu.
This is a really straightforward program in C
, hopefully allowing you to get familiar with this programming language.
Among the things that may confuse you:
C
is not an object-oriented programming language!C
doesn’t offer “native” boolean. You can import them or simulate them, cf. https://stackoverflow.com/a/1921557/C
offers fine-grained memory management, especially through the free
and malloc
operations of pointers.There are two excellent textbooks that I recommend:
Playing with the code won’t hurt, and here are some suggestions of exercises:
and
int
and a double
, and store the result in a variable before displaying it again.String
and iterate over it.String
from the user and then display its first character at the screen.String
into an int
.