August 6, 2021
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;
10;
a = int b = 11;
"The value of a is %d, its address is %p\n", a, &a);
printf(//%d is for sigmed integers, %p for pointer address
int* pointer = &a;
// You can also see the syntax "int *pointer = &a;".
"The value pointed is %d, the address of the pointer is %p, the address the pointer points to is %p.\n", *pointer, &pointer, pointer);
printf(
// Notice that if the value of change a, so does the value pointed at. We can read the new value from the user:
"Enter the new value for a and press enter:\n");
printf("%d", &a);
scanf("The value pointed is %d\n", *pointer);
printf(
// Basic control stucture:
if (a == 10){
"You did not changed the value of a.\n");
printf(
}else
{"You changed the value of a.\n");
printf(
}
int counter;
"Let's count to ten:\n");
printf(for (counter = 0; counter <= 10 ; counter++)
{"%d ", counter);
printf(
}"\n");
printf(
"Let's count back to 0:\n");
printf(while (counter > 0)
{
counter--;"%d ", counter);
printf(
}"\n");
printf(
// Calling the previously defined cube function, performing implicit casting from int to long:
"Here is your number, cubed: %d\n", cube(a));
printf(
/* 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
gcc prog.c
./a.out
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:
You can also consult a brief cheatsheet if you simply want to remind yourself of some basic keywords and notions.
Playing with the code won’t hurt, and here are some suggestions of exercises:
void plus(int a){
1;
a = a+"The parameter is now %d", a);
printf( }
and
void plus(int* p){
1;
*p = *p+"The parameter is now %d", *p);
printf( }
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
.